This commit is contained in:
zanon committed 2026-11-14 12:58:29 -03:00
commit 60cdd1c49f
2212 files changed
+270330

No files matched your search

@@ -0,0 +1,263 @@
package dev.azurite.spigot;
import dev.azurite.spigot.api.pearls.PearlHandler;
import dev.azurite.spigot.api.protocol.MovementHandler;
import dev.azurite.spigot.api.protocol.PacketHandler;
import dev.azurite.spigot.async.ThreadingManager;
import dev.azurite.spigot.betterslowdown.BetterSlowdown;
import dev.azurite.spigot.command.*;
import dev.azurite.spigot.configs.AzuriteConfig;
import dev.azurite.spigot.configs.EnchantConfig;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.configs.PearlConfig;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigEdit;
import dev.azurite.spigot.framework.commands.Command;
import dev.azurite.spigot.framework.menu.MenuManager;
import dev.azurite.spigot.framework.plugin.AzuriteFakePlugin;
import dev.azurite.spigot.generator.GeneratorManager;
import dev.azurite.spigot.knockback.KnockbackManager;
import dev.azurite.spigot.listeners.ChatListener;
import dev.azurite.spigot.listeners.MenuListener;
import dev.azurite.spigot.listeners.PearlListener;
import dev.azurite.spigot.optimizations.ObjectMapList;
import dev.azurite.spigot.redstone.EigencraftRedstoneWire;
import dev.azurite.spigot.redstone.PandaRedstoneWire;
import dev.azurite.spigot.utils.NettyWatchdog;
import dev.azurite.spigot.utils.Utils;
import net.minecraft.server.BlockRedstoneWire;
import net.minecraft.server.GameRules;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.command.defaults.BukkitCommand;
import org.bukkit.plugin.PluginManager;
import java.util.*;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class Azurite implements IAzurite {
private static Azurite instance;
private static AzuriteFakePlugin pluginInstance;
private final Map<UUID, ConfigEdit> configEdits;
private final List<Config> configs;
private final List<Command> commands;
private final ObjectMapList<PacketHandler> packetHandlers;
private final ObjectMapList<MovementHandler> movementHandlers;
private final ObjectMapList<PearlHandler> pearlHandlers;
private final AzuriteConfig azuriteConfig;
private final LanguageConfig languageConfig;
private final PearlConfig pearlConfig;
private final EnchantConfig enchantConfig;
private final ThreadingManager threadingManager;
private final KnockbackManager knockbackManager;
private final GeneratorManager generatorManager;
private final MenuManager menuManager;
private final NettyWatchdog nettyWatchdog;
private final BetterSlowdown betterSlowdown;
private int noTrackRange;
public Azurite() {
instance = this;
pluginInstance = new AzuriteFakePlugin();
this.configEdits = new HashMap<>();
this.configs = new ArrayList<>();
this.commands = new ArrayList<>();
this.packetHandlers = new ObjectMapList<>(PacketHandler.class, 0);
this.movementHandlers = new ObjectMapList<>(MovementHandler.class, 0);
this.pearlHandlers = new ObjectMapList<>(PearlHandler.class, 0);
this.azuriteConfig = new AzuriteConfig(this);
this.languageConfig = new LanguageConfig(this);
this.pearlConfig = new PearlConfig(this);
this.enchantConfig = new EnchantConfig(this);
this.configs.forEach(Config::load);
this.threadingManager = new ThreadingManager();
this.knockbackManager = new KnockbackManager();
this.generatorManager = new GeneratorManager();
this.menuManager = new MenuManager();
this.nettyWatchdog = new NettyWatchdog();
this.noTrackRange = 0;
this.betterSlowdown = new BetterSlowdown();
}
public void shutdown() {
threadingManager.shutdown();
knockbackManager.save(false);
generatorManager.save(false);
}
public void registerListeners() {
PluginManager pluginManager = Bukkit.getPluginManager();
pluginManager.registerEvents(new PearlListener(), pluginInstance);
pluginManager.registerEvents(new ChatListener(), pluginInstance);
pluginManager.registerEvents(new MenuListener(), pluginInstance);
}
public void registerCommands(boolean reload) {
if (AzuriteConfig.enableSpigotConfigCommand.getValue()) commands.add(new AzuriteSpigotCommand());
if (AzuriteConfig.enablePingCommand.getValue()) commands.add(new PingCommand());
if (AzuriteConfig.enableTPSCommand.getValue()) commands.add(new TPSCommand());
if (AzuriteConfig.enableClearLagCommand.getValue()) commands.add(new ClearLagCommand());
if (AzuriteConfig.enableSetMaxPlayersCommand.getValue()) commands.add(new SetMaxPlayersCommand());
if (AzuriteConfig.enableChunkUnloadCommand.getValue()) commands.add(new UnloadChunksCommand());
if (AzuriteConfig.enableNoTrackCommand.getValue()) commands.add(new NoTrackCommand());
commands.add(new KnockbackCommand());
commands.add(new VersionCommand());
for (Command command : commands) {
BukkitCommand bukkitCommand = command.asBukkitCommand();
String name = bukkitCommand.getName();
if (name.equals("tps")) Utils.register("spigot", bukkitCommand, reload);
if (name.equals("version")) Utils.register("minecraft", bukkitCommand, reload);
Utils.register(AzuriteConfig.serverBranding.getValue().toLowerCase(), bukkitCommand, reload);
}
}
public void reload() {
for (Config config : configs) {
config.reload();
}
for (Command command : commands) {
command.unregister();
}
for (WorldServer world : MinecraftServer.getServer().worlds) {
GameRules gameRules = world.worldData.x();
gameRules.set("doMobSpawning", AzuriteConfig.naturalMobSpawn.getValue().toString());
}
this.commands.clear();
this.registerCommands(true);
}
public BlockRedstoneWire getRedstoneOptimization() {
switch (AzuriteConfig.redstoneOptimization.getValue().toUpperCase()) {
case "EIGENCRAFT":
return new EigencraftRedstoneWire();
case "PANDAWIRE":
return new PandaRedstoneWire();
default:
return new BlockRedstoneWire();
}
}
public static Azurite getInstance() {
return instance;
}
public static AzuriteFakePlugin getPluginInstance() {
return pluginInstance;
}
public Map<UUID, ConfigEdit> getConfigEdits() {
return configEdits;
}
public List<Config> getConfigs() {
return configs;
}
public List<Command> getCommands() {
return commands;
}
public ThreadingManager getThreadingManager() {
return threadingManager;
}
public GeneratorManager getGeneratorManager() {
return generatorManager;
}
public MenuManager getMenuManager() {
return menuManager;
}
public AzuriteConfig getAzuriteConfig() {
return azuriteConfig;
}
public LanguageConfig getLanguageConfig() {
return languageConfig;
}
public PearlConfig getPearlConfig() {
return pearlConfig;
}
public EnchantConfig getEnchantConfig() {
return enchantConfig;
}
public NettyWatchdog getNettyWatchdog() {
return nettyWatchdog;
}
public int getNoTrackRange() {
return noTrackRange;
}
public void setNoTrackRange(int noTrackRange) {
this.noTrackRange = noTrackRange;
}
public BetterSlowdown getBetterSlowdown() {
return betterSlowdown;
}
@Override
public void addMovementHandler(MovementHandler movementHandler) {
movementHandlers.add(movementHandler);
}
@Override
public void addPacketHandler(PacketHandler packetHandler) {
packetHandlers.add(packetHandler);
}
@Override
public void addPearlHandler(PearlHandler pearlHandler) {
pearlHandlers.add(pearlHandler);
}
@Override
public ObjectMapList<PacketHandler> getPacketHandlers() {
return packetHandlers;
}
@Override
public ObjectMapList<MovementHandler> getMovementHandlers() {
return movementHandlers;
}
@Override
public ObjectMapList<PearlHandler> getPearlHandlers() {
return pearlHandlers;
}
@Override
public KnockbackManager getKnockbackManager() {
return knockbackManager;
}
}
@@ -0,0 +1,16 @@
package dev.azurite.spigot.api;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.IAzurite;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class SpigotAPI {
public static IAzurite getInstance() {
return Azurite.getInstance();
}
}
@@ -0,0 +1,53 @@
package dev.azurite.spigot.api.chunk;
import net.minecraft.server.NibbleArray;
public class ChunkSectionSnapshot {
private final int yPos;
private final int nonEmptyBlockCount;
private final int tickingBlockCount;
private final char[] blockIds;
private final NibbleArray emittedLight;
private final NibbleArray skyLight;
boolean isDirty; // PaperSpigot
public ChunkSectionSnapshot(int yPos, int nonEmptyBlockCount, int tickingBlockCount, char[] blockIds, NibbleArray emittedLight, NibbleArray skyLight, boolean isDirty) {
this.yPos = yPos;
this.nonEmptyBlockCount = nonEmptyBlockCount;
this.tickingBlockCount = tickingBlockCount;
this.blockIds = blockIds;
this.emittedLight = emittedLight;
this.skyLight = skyLight;
this.isDirty = isDirty;
}
public int getYPos() {
return yPos;
}
public int getNonEmptyBlockCount() {
return nonEmptyBlockCount;
}
public int getTickingBlockCount() {
return tickingBlockCount;
}
public char[] getBlockIds() {
return blockIds;
}
public NibbleArray getEmittedLight() {
return emittedLight;
}
public NibbleArray getSkyLight() {
return skyLight;
}
public boolean isDirty() {
return isDirty;
}
}
@@ -0,0 +1,20 @@
package dev.azurite.spigot.api.chunk;
import net.minecraft.server.NBTTagCompound;
import java.util.ArrayList;
import java.util.List;
public class CraftChunkSnapshot implements ChunkSnapshot {
private final ChunkSectionSnapshot[] sections = new ChunkSectionSnapshot[16];
private final List<NBTTagCompound> tileEntities = new ArrayList<>();
public ChunkSectionSnapshot[] getSections() {
return sections;
}
public List<NBTTagCompound> getTileEntities() {
return tileEntities;
}
}
@@ -0,0 +1,55 @@
package dev.azurite.spigot.async;
import dev.azurite.spigot.async.threads.AsyncExecutorThread;
import dev.azurite.spigot.async.threads.TrackerExecutorThread;
import dev.azurite.spigot.async.worker.TaskQueueWorker;
import dev.azurite.spigot.configs.AzuriteConfig;
import dev.azurite.spigot.pathsearch.PathSearchThrottlerThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadingManager {
private final AsyncExecutorThread asyncExecutorThread;
private final TrackerExecutorThread trackerExecutorThread;
private final PathSearchThrottlerThread pathSearchExecutorThread;
public ThreadingManager() {
this.asyncExecutorThread = new AsyncExecutorThread();
this.trackerExecutorThread = new TrackerExecutorThread();
this.pathSearchExecutorThread = new PathSearchThrottlerThread(AzuriteConfig.pathSearchThreads.getValue());
}
public void shutdown() {
pathSearchExecutorThread.shutdown();
TaskQueueWorker files = asyncExecutorThread.getFilesWorker();
ExecutorService service = asyncExecutorThread.getExecutor();
while (files.isActive() && !service.isTerminated()) {
try {
service.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
}
}
if (!service.isTerminated()) {
service.shutdownNow();
try {
service.awaitTermination(10L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public AsyncExecutorThread getAsyncExecutor() {
return asyncExecutorThread;
}
public TrackerExecutorThread getTrackerExecutor() {
return trackerExecutorThread;
}
public PathSearchThrottlerThread getPathSearchExecutor() {
return pathSearchExecutorThread;
}
}
@@ -0,0 +1,37 @@
package dev.azurite.spigot.async.factory;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class NamePriorityThreadFactory implements ThreadFactory {
private String name = "Spigot_Async-Thread";
private final int priority;
private int idCounter;
private boolean isDaemon;
public NamePriorityThreadFactory(int priority) {
this.priority = Math.min(Math.max(priority, Thread.MIN_PRIORITY), Thread.MAX_PRIORITY);
}
public NamePriorityThreadFactory(int priority, String name) {
this(priority);
this.name = name;
}
public NamePriorityThreadFactory setDaemon(boolean daemon) {
this.isDaemon = daemon;
return this;
}
@Override
public Thread newThread(@NotNull Runnable runnable) {
Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setPriority(priority);
thread.setName(name + "-" + idCounter++);
thread.setDaemon(isDaemon);
return thread;
}
}
@@ -0,0 +1,29 @@
package dev.azurite.spigot.async.tasks;
import net.minecraft.server.NBTCompressedStreamTools;
import net.minecraft.server.NBTTagCompound;
import java.io.File;
import java.io.FileOutputStream;
public class NBTFileSaveJob implements Runnable {
private NBTTagCompound compound;
private File file;
public NBTFileSaveJob(NBTTagCompound compound, File file) {
this.compound = compound;
this.file = file;
}
@Override
public void run() {
try (FileOutputStream fileoutputstream = new FileOutputStream(file)) {
NBTCompressedStreamTools.a(compound, fileoutputstream);
} catch (Exception e) {
e.printStackTrace();
}
compound = null;
file = null;
}
}
@@ -0,0 +1,34 @@
package dev.azurite.spigot.async.tasks;
import net.minecraft.server.NBTCompressedStreamTools;
import net.minecraft.server.NBTTagCompound;
import java.io.File;
import java.io.FileOutputStream;
public class PlayerDataSaveJob implements Runnable {
private File target;
private NBTTagCompound data;
public PlayerDataSaveJob(File target, NBTTagCompound data) {
this.target = target;
this.data = data;
}
@Override
public void run() {
File temp = new File(target.getPath() + ".tmp");
try (FileOutputStream fileoutputstream = new FileOutputStream(temp)) {
NBTCompressedStreamTools.a(data, fileoutputstream);
if (target.exists()) {
target.delete();
}
temp.renameTo(target);
} catch (Exception e) {
e.printStackTrace();
}
target = null;
data = null;
}
}
@@ -0,0 +1,30 @@
package dev.azurite.spigot.async.tasks;
import net.minecraft.server.ServerStatisticManager;
import net.minecraft.server.Statistic;
import net.minecraft.server.StatisticWrapper;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class PlayerStatsSaveJob implements Runnable {
private final File target;
private final Map<Statistic, StatisticWrapper> stats;
public PlayerStatsSaveJob(File target, Map<Statistic, StatisticWrapper> stats) {
this.target = target;
this.stats = stats;
}
@Override
public void run() {
try {
FileUtils.writeStringToFile(target, ServerStatisticManager.a(stats)); // The stats map is a concurrenthashmap by default so we can serialize it asynchronously
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,20 @@
package dev.azurite.spigot.async.tasks;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.UserCache;
import java.util.List;
public class UserCacheSaveJob implements Runnable {
private final List<UserCache.UserCacheEntry> entries;
public UserCacheSaveJob(List<UserCache.UserCacheEntry> entries) {
this.entries = entries;
}
@Override
public void run() {
MinecraftServer.getServer().getUserCache().saveEntries(this.entries);
}
}
@@ -0,0 +1,48 @@
package dev.azurite.spigot.async.tasks;
import net.minecraft.server.NBTCompressedStreamTools;
import net.minecraft.server.NBTTagCompound;
import net.minecraft.server.WorldData;
import java.io.File;
import java.nio.file.Files;
//Vortex Async World Saving
public class WorldDataSaveJob implements Runnable {
private WorldData target;
private NBTTagCompound data;
private File dir;
public WorldDataSaveJob(WorldData target, NBTTagCompound data, File dir) {
this.target = target;
this.data = data;
this.dir = dir;
}
@Override
public void run() {
NBTTagCompound nbttagcompound1 = target.a(data);
NBTTagCompound nbttagcompound2 = new NBTTagCompound();
nbttagcompound2.set("Data", nbttagcompound1);
try {
final File file1 = new File(this.dir, "level.dat_new");
final File file2 = new File(this.dir, "level.dat_old");
final File file3 = new File(this.dir, "level.dat");
NBTCompressedStreamTools.a(nbttagcompound2, Files.newOutputStream(file1.toPath()));
if (file2.exists())
file2.delete();
file3.renameTo(file2);
if (file3.exists())
file3.delete();
file1.renameTo(file3);
if (file1.exists())
file1.delete();
} catch (Exception exception) {
exception.printStackTrace();
}
this.target = null;
this.data = null;
this.dir = null;
}
}
@@ -0,0 +1,57 @@
package dev.azurite.spigot.async.threads;
import dev.azurite.spigot.async.worker.TaskQueueWorker;
import dev.azurite.spigot.async.factory.NamePriorityThreadFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class AsyncExecutorThread {
private final ExecutorService asyncExecutor;
private final TaskQueueWorker files;
private final TaskQueueWorker heads;
private final TaskQueueWorker chat;
public AsyncExecutorThread() {
int priority = Thread.currentThread().getPriority() - 1;
this.asyncExecutor = Executors.newCachedThreadPool(new NamePriorityThreadFactory(priority, "Spigot_Async-Executor").setDaemon(true));
this.files = new TaskQueueWorker(asyncExecutor);
this.heads = new TaskQueueWorker(asyncExecutor);
this.chat = new TaskQueueWorker(asyncExecutor);
}
public void queueFileTask(Runnable runnable) {
files.queueTask(runnable);
}
public void queueHeadLoading(Runnable runnable) {
heads.queueTask(runnable);
}
public void queueChat(Runnable runnable) {
chat.queueTask(runnable);
}
public TaskQueueWorker getFilesWorker() {
return files;
}
public void execute(Runnable runnable) {
asyncExecutor.execute(runnable);
}
public Future<?> submit(Runnable runnable) {
return asyncExecutor.submit(runnable);
}
public ExecutorService getExecutor() {
return asyncExecutor;
}
}
@@ -0,0 +1,79 @@
package dev.azurite.spigot.async.threads;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import dev.azurite.spigot.configs.AzuriteConfig;
import dev.azurite.spigot.optimizations.ObjectMapList;
import dev.azurite.spigot.utils.SpinCountDownLatch;
import net.minecraft.server.EntityPlayer;
import net.minecraft.server.EntityTrackerEntry;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.PacketPlayOutEntityDestroy;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class TrackerExecutorThread {
private final int trackerThreads;
private final ExecutorService trackerExecutor;
public TrackerExecutorThread() {
ThreadFactory trackerFactory = new ThreadFactoryBuilder().setNameFormat("entity-tracker-%d").build();
this.trackerThreads = 4;
this.trackerExecutor = Executors.newFixedThreadPool(trackerThreads - 1, trackerFactory);
}
public void updatePlayers(ObjectMapList<EntityTrackerEntry> c) {
boolean parallelizeUpdate = false;
if (AzuriteConfig.dynamicParalellisedTracking.getValue()) {
for (int index = 0; index < c.count; index++) {
EntityTrackerEntry entry = c.elements[index];
if (entry.trackedPlayers.size() >= AzuriteConfig.playersNeededParalellisedTracking.getValue()) {
parallelizeUpdate = true;
break;
}
}
}
if (!parallelizeUpdate) {
for (int index = 0; index < c.count; index++) {
EntityTrackerEntry entry = c.elements[index];
entry.update(3);
}
} else {
int offset = 0;
final SpinCountDownLatch latch = new SpinCountDownLatch(trackerThreads);
for (int i = 1; i <= trackerThreads; i++) {
final int localOffset = offset++;
int finalTrackerThread = i;
Runnable runnable = () -> {
for (int i1 = localOffset; i1 < c.size(); i1 += trackerThreads) {
c.get(i1).update(finalTrackerThread - 1);
}
latch.countDown();
};
if (i < trackerThreads) {
trackerExecutor.execute(runnable);
} else runnable.run();
}
try {
latch.await();
} catch (Exception e) {
MinecraftServer.LOGGER.error(e);
}
}
}
}
@@ -0,0 +1,51 @@
package dev.azurite.spigot.async.worker;
import org.apache.logging.log4j.LogManager;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
public class TaskQueueWorker implements Runnable {
private final ConcurrentLinkedDeque<Runnable> taskQueue = new ConcurrentLinkedDeque<>();
private final ExecutorService service;
private volatile boolean isActive = false;
public TaskQueueWorker(ExecutorService service) {
this.service = service;
}
@Override
public void run() {
Runnable task;
while (isActive = (task = taskQueue.pollFirst()) != null) {
try {
task.run();
} catch (Exception e) {
LogManager.getLogger().error("Thread {} encountered an exception: {}", Thread.currentThread().getName(), e.getMessage(), e);
}
}
}
public void queueTask(Runnable runnable) {
// Azurite - run sync if service is terminated
if (service.isTerminated()) {
runnable.run();
} else {
taskQueue.addLast(runnable);
if (!isActive) {
isActive = true;
service.execute(this);
}
}
}
public boolean isActive() {
if (!isActive && !taskQueue.isEmpty()) {
isActive = true;
service.execute(this);
}
return isActive;
}
}
@@ -0,0 +1,184 @@
package dev.azurite.spigot.autosave;
import dev.azurite.spigot.configs.AzuriteConfig;
import net.minecraft.server.*;
import org.bukkit.event.world.WorldSaveEvent;
import java.util.ArrayDeque;
import java.util.Queue;
public class AutoSave {
private AutoSaveStep step;
private final Queue<WorldServer> levelAndMapsQueue;
private final Queue<WorldServer> saveChunksQueue;
private final Queue<WorldServer> unloadChunksQueue;
private final Queue<WorldServer> eventQueue;
private long fileioStart;
private long fileioEnd;
private int chunkQueuedCount;
public AutoSave() {
this.levelAndMapsQueue = new ArrayDeque<>();
this.saveChunksQueue = new ArrayDeque<>();
this.unloadChunksQueue = new ArrayDeque<>();
this.eventQueue = new ArrayDeque<>();
this.reset();
}
public void queueWorld(WorldServer worldserver) {
this.levelAndMapsQueue.add(worldserver);
this.saveChunksQueue.add(worldserver);
this.unloadChunksQueue.add(worldserver);
this.eventQueue.add(worldserver);
}
public void reset() {
this.levelAndMapsQueue.clear();
this.saveChunksQueue.clear();
this.unloadChunksQueue.clear();
this.eventQueue.clear();
this.step = AutoSaveStep.IDLE;
this.chunkQueuedCount = 0;
}
private void moveToNextStep() {
this.step = AutoSaveStep.nextStep(this.step);
}
public boolean execute() throws ExceptionWorldConflict {
WorldServer worldServer;
switch (this.step) {
case IDLE:
break;
case START:
if (AzuriteConfig.autoSaveMessages.getValue()) {
MinecraftServer.LOGGER.info("[Autosave] Started ..");
}
for (WorldServer world : this.saveChunksQueue) {
world.getAutoSaveWorldData().setLastAutosaveTimeStamp();
}
this.moveToNextStep();
return this.execute();
case SAVE_PLAYERS:
MinecraftServer.getServer().getPlayerList().savePlayers();
this.moveToNextStep();
break;
case SAVE_LEVEL_AND_MAPS:
worldServer = this.levelAndMapsQueue.poll();
if (worldServer != null) {
worldServer.saveOnlyLevel(null);
}
if (this.levelAndMapsQueue.isEmpty()) {
this.moveToNextStep();
}
break;
case SAVE_CHUNKS:
worldServer = this.saveChunksQueue.peek();
if (worldServer != null) {
if (worldServer.saveOnlyChunks(false, null)) {
this.chunkQueuedCount += worldServer.getAutoSaveWorldData().getAutoSaveChunkCount();
this.saveChunksQueue.poll();
}
}
if (this.saveChunksQueue.isEmpty()) {
this.moveToNextStep();
}
break;
case UNLOAD_CHUNKS:
worldServer = this.unloadChunksQueue.poll();
if (worldServer != null) {
worldServer.unloadOnlyUnusedChunks();
}
if (this.unloadChunksQueue.isEmpty()) {
this.moveToNextStep();
}
break;
case WRITE_FILES_START:
FileIOThread.a().setNoDelay(true);
this.fileioStart = System.nanoTime();
this.moveToNextStep();
break;
case WRITE_FILES_WAIT:
if (FileIOThread.a().isDone()) {
this.fileioEnd = System.nanoTime();
FileIOThread.a().setNoDelay(false);
this.moveToNextStep();
}
break;
case FIRE_WORLDSAVEEVENT:
if (AzuriteConfig.autoSaveClearRegionFileCache.getValue()) {
RegionFileCache.a();
}
if (AzuriteConfig.autoSaveFireWorldSaveEvent.getValue()) {
for (WorldServer worldserver : this.eventQueue) {
WorldSaveEvent event = new WorldSaveEvent(worldserver.getWorld());
MinecraftServer.getServer().server.getPluginManager().callEvent(event);
}
}
this.moveToNextStep();
break;
case FINISHED:
if (AzuriteConfig.autoSaveMessages.getValue()) {
MinecraftServer.LOGGER.info("[Autosave] Done. Queued {} chunks for saving. Took {} seconds to write them.", this.chunkQueuedCount, formatLongTime(this.fileioEnd - this.fileioStart));
}
this.reset();
return true;
}
return false;
}
private static String formatLongTime(long duration) {
return String.format("%.2f", ((double) (duration / 1000000L)) / 1000.0D);
}
public boolean isActive() {
return this.step.isActiveState();
}
public void start() {
this.step = AutoSaveStep.START;
}
public enum AutoSaveStep {
IDLE(false),
START(),
SAVE_PLAYERS(),
SAVE_LEVEL_AND_MAPS(),
SAVE_CHUNKS(),
UNLOAD_CHUNKS(),
WRITE_FILES_START(),
WRITE_FILES_WAIT(),
FIRE_WORLDSAVEEVENT(),
FINISHED();
private final boolean activeState;
AutoSaveStep() {
this(true);
}
AutoSaveStep(boolean activeState) {
this.activeState = activeState;
}
public static AutoSaveStep nextStep(AutoSaveStep current) {
AutoSaveStep[] values = AutoSaveStep.values();
if (current.ordinal() + 1 < values.length) {
return values[current.ordinal() + 1];
}
return current;
}
public boolean isActiveState() {
return this.activeState;
}
}
}
@@ -0,0 +1,32 @@
package dev.azurite.spigot.autosave;
import net.minecraft.server.World;
public class AutoSaveWorldData {
private long lastAutoSaveTimeStamp;
private int autoSaveChunkCount;
private final World world;
public AutoSaveWorldData(World world) {
this.world = world;
this.setLastAutosaveTimeStamp();
}
public void setLastAutosaveTimeStamp() {
this.lastAutoSaveTimeStamp = this.world.worldData.getTime();
this.autoSaveChunkCount = 0;
}
public long getLastAutosaveTimeStamp() {
return this.lastAutoSaveTimeStamp;
}
public void addAutoSaveChunkCount(int count) {
this.autoSaveChunkCount += count;
}
public int getAutoSaveChunkCount() {
return this.autoSaveChunkCount;
}
}
@@ -0,0 +1,181 @@
package dev.azurite.spigot.betterslowdown;
import com.eatthepath.uuid.FastUUID;
import dev.azurite.spigot.betterslowdown.data.PlayerData;
import dev.azurite.spigot.betterslowdown.data.PlayerDataManager;
import dev.azurite.spigot.configs.AzuriteConfig;
import net.minecraft.server.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
public class BetterSlowdown {
private static final UUID SPRINT_MODIFIER_UUID = FastUUID.parseUUID("662A6B8D-DA3E-4C1C-8813-96EA6097278D");
private static final AttributeModifier SPRINT_MODIFIER = (new AttributeModifier(SPRINT_MODIFIER_UUID, "Sprinting speed boost",
0.30000001192092896D, 2)).a(false);
private final PlayerDataManager manager;
public BetterSlowdown() {
this.manager = new PlayerDataManager();
}
public void disconnect(UUID uuid) {
this.manager.remove(uuid);
}
public void startSprint(UUID uuid) {
PlayerData data = manager.get(uuid);
data.setClientSprintingState(true);
}
public void stopSprint(UUID uuid) {
PlayerData data = manager.get(uuid);
data.setClientSprintingState(false);
}
public void respawn(UUID uuid) {
manager.get(uuid).reset();
}
// This can be called from tracker thread so player data manager needs to be threadsafe
// Method returns whether the update is needed
public boolean handleEntityMetadata(UUID uuid, PacketPlayOutEntityMetadata wrapper) {
if (!AzuriteConfig.betterSlowdownEnabled.getValue()) return true;
Iterator<DataWatcher.WatchableObject> iterator = wrapper.getData().iterator();
while (iterator.hasNext()) {
DataWatcher.WatchableObject entityData = iterator.next();
// Check if the entity metadata bitmask is in this packet
if (entityData.a() == MetadataValues.BITMASK_INDEX) {
byte packetBitmask = (byte) entityData.b();
byte usefulBitmask = packetBitmask;
// Calculate the useful bitmask
usefulBitmask &= ~MetadataValues.FLAG_CROUCHING; // Remove crouching
usefulBitmask &= ~MetadataValues.FLAG_SPRINTING; // Remove sprinting
usefulBitmask &= ~MetadataValues.FLAG_USING; // Remove using
// Check if the "useful" bitmask has changed, which means either the client is on fire or invisible
PlayerData data = manager.get(uuid);
byte lastUsefulBitmask = data.getLastUsefulBitmask();
if (lastUsefulBitmask != usefulBitmask) {
data.setLastUsefulBitmask(usefulBitmask);
// Get the fallback mode as we are 100% sending the bitmask
FallbackMode mode;
try {
mode = Enum.valueOf(FallbackMode.class, AzuriteConfig.betterSlowdownFallbackMode.getValue().toUpperCase());
} catch (Exception ex) {
mode = FallbackMode.CLIENT;
}
// We don't have to worry about overwriting sprint or no sprint for self player, (tbh this might change ground particles for other players)
if (mode != FallbackMode.SERVER) {
if (mode == FallbackMode.SPRINT
|| (mode == FallbackMode.CLIENT && data.isClientSprintingState())) {
// Rewrite with sprinting = true
packetBitmask |= MetadataValues.FLAG_SPRINTING;
entityData.a(packetBitmask);
} else if (mode == FallbackMode.NO_SPRINT
|| (mode == FallbackMode.CLIENT && !data.isClientSprintingState())) {
// Rewrite with sprinting = false
packetBitmask &= ~MetadataValues.FLAG_SPRINTING;
entityData.a(packetBitmask);
}
}
} else {
// The bitmask update wasn't useful, either remove this part if there's more metadata or cancel the packet
if (wrapper.b.size() != 1) {
iterator.remove();
} else {
return false;
}
}
}
}
return true;
}
public boolean handleAttributes(UUID uuid, PacketPlayOutUpdateAttributes wrapper) {
if (!AzuriteConfig.betterSlowdownEnabled.getValue()) return true;
Iterator<PacketPlayOutUpdateAttributes.AttributeSnapshot> iterator = wrapper.b.iterator();
while (iterator.hasNext()) {
PacketPlayOutUpdateAttributes.AttributeSnapshot snapshot = iterator.next();
if (snapshot.a().equals("generic.movementSpeed")) {
// Calculate the movement speed without sprint
boolean exists = snapshot.c().removeIf(modifier -> modifier.a().equals(SPRINT_MODIFIER_UUID));
double speed = calculateSpeed(snapshot);
PlayerData data = manager.get(uuid);
double lastSpeed = data.getLastSpeed();
if (lastSpeed != speed) {
// Update the speed
data.setLastSpeed(speed);
if (exists) {
// Re-add the modifier if packetevents is on default re-encode
snapshot.c().add(SPRINT_MODIFIER);
} else if (AzuriteConfig.betterSlowdownAlwaysAddSprint.getValue() && data.isClientSprintingState()) {
// Add sprint modifier is the client claimed he was sprinting and always add sprint is enabled
snapshot.c().add(SPRINT_MODIFIER);
}
} else {
// Cancel this attribute packet as it only changes the sprint attribute
if (wrapper.b.size() != 1) {
iterator.remove();
} else {
return false;
}
}
}
}
return true;
}
private double calculateSpeed(PacketPlayOutUpdateAttributes.AttributeSnapshot snapshot) {
double value = snapshot.b();
for (AttributeModifier modifier : snapshot.c()) {
if (modifier.c() == 0) {
value += modifier.d();
}
}
double newValue = value;
for (AttributeModifier modifier : snapshot.c()) {
if (modifier.c() == 1) {
newValue += value * modifier.d();
}
}
for (AttributeModifier modifier : snapshot.c()) {
if (modifier.c() == 2) {
newValue *= 1.0D + modifier.d();
}
}
if (newValue < 0.0D) {
newValue = 0.0D;
}
if (newValue > Double.MAX_VALUE) {
newValue = Double.MAX_VALUE;
}
return newValue;
}
}
@@ -0,0 +1,8 @@
package dev.azurite.spigot.betterslowdown;
public enum FallbackMode {
SERVER,
SPRINT,
NO_SPRINT,
CLIENT
}
@@ -0,0 +1,11 @@
package dev.azurite.spigot.betterslowdown;
/**
* https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Entity_metadata
*/
public class MetadataValues {
public static final int BITMASK_INDEX = 0;
public static final byte FLAG_CROUCHING = 0x02;
public static final byte FLAG_SPRINTING = 0x08;
public static final byte FLAG_USING = 0x10;
}
@@ -0,0 +1,41 @@
package dev.azurite.spigot.betterslowdown.data;
public class PlayerData {
private byte lastUsefulBitmask;
private double lastSpeed;
private boolean clientSprintingState;
public PlayerData() {
this.reset();
}
public void reset() {
this.lastUsefulBitmask = (byte) -1;
this.lastSpeed = -1.0D;
this.clientSprintingState = false;
}
public double getLastSpeed() {
return lastSpeed;
}
public byte getLastUsefulBitmask() {
return lastUsefulBitmask;
}
public boolean isClientSprintingState() {
return clientSprintingState;
}
public void setLastUsefulBitmask(byte lastUsefulBitmask) {
this.lastUsefulBitmask = lastUsefulBitmask;
}
public void setLastSpeed(double lastSpeed) {
this.lastSpeed = lastSpeed;
}
public void setClientSprintingState(boolean clientSprintingState) {
this.clientSprintingState = clientSprintingState;
}
}
@@ -0,0 +1,28 @@
package dev.azurite.spigot.betterslowdown.data;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerDataManager {
private final Map<UUID, PlayerData> userMap = new ConcurrentHashMap<>();
public void cache(UUID user, PlayerData data) {
userMap.put(user, data);
}
public void remove(UUID user) {
userMap.remove(user);
}
public PlayerData get(UUID user) {
PlayerData data = userMap.get(user);
if (data == null) {
data = new PlayerData();
userMap.put(user, data);
}
return data;
}
}
@@ -0,0 +1,78 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import dev.azurite.spigot.menu.MainAzuriteMenu;
import net.minecraft.server.PlayerConnection;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class AzuriteSpigotCommand extends Command {
public AzuriteSpigotCommand() {
super("azuritespigot");
this.setPermission("azuritespigot.config");
this.setAliases(Arrays.asList("spigotconfig", "config"));
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 2 && args[0].equals("teleportqueue")) {
Player player = Bukkit.getPlayer(args[1]);
if (player != null) {
PlayerConnection playerConnection = ((CraftPlayer) player).getHandle().playerConnection;
sender.sendMessage(player.getName() + " has " + (playerConnection.getTeleportQueueSize()) + " teleports queued!");
sender.sendMessage("Check movement: " + playerConnection.isCheckMovement());
} else {
sender.sendMessage("Could not find that player");
}
return;
}
if (args.length == 0 || !args[0].equalsIgnoreCase("reload")) {
if (!(sender instanceof Player)) {
sendMessage(sender, LanguageConfig.onlyPlayer.getValue());
return;
}
Player player = (Player) sender;
new MainAzuriteMenu(player).open();
return;
}
long now = System.currentTimeMillis();
Azurite.getInstance().reload();
long after = System.currentTimeMillis() - now;
sendMessage(sender, LanguageConfig.configReloaded.getValue()
.replace("%ms%", String.valueOf(after))
);
}
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
if (args.length == 1) {
String string = args[args.length - 1];
return Stream.of("reload")
.filter(s -> s.regionMatches(true, 0, string, 0, string.length()))
.collect(Collectors.toList());
}
return super.tabComplete(sender, args);
}
}
@@ -0,0 +1,40 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import net.minecraft.server.*;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class ClearLagCommand extends Command {
public ClearLagCommand() {
super("clearlag");
this.setPermission("azuritespigot.clearlag");
this.setAliases(Arrays.asList("killentities", "clearentities"));
}
@Override
public void execute(CommandSender sender, String[] args) {
int entities = 0;
for (World world : MinecraftServer.getServer().worlds) {
for (Entity entity : world.entityList) {
if (entity instanceof EntityItemFrame) continue; // Azurite
if (entity instanceof EntityPlayer || entity.dead || entity.hasCustomName()) continue;
entity.dead = true;
entities++;
}
}
sendMessage(sender, LanguageConfig.clearedLag.getValue()
.replace("%entities%", String.valueOf(entities))
);
}
}
@@ -0,0 +1,493 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.api.knockback.IKnockback;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.framework.commands.Command;
import dev.azurite.spigot.knockback.Knockback;
import dev.azurite.spigot.knockback.KnockbackManager;
import dev.azurite.spigot.knockback.KnockbackType;
import dev.azurite.spigot.knockback.extra.KnockbackEdit;
import dev.azurite.spigot.menu.ConfigEditMenu;
import dev.azurite.spigot.utils.fanciful.FancyMessage;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.List;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class KnockbackCommand extends Command {
public KnockbackCommand() {
super("knockback");
this.setPermission("azuritespigot.knockback");
this.setAliases(Arrays.asList("kb", "kbprofiles"));
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sendUsage(sender);
return;
}
KnockbackManager manager = Azurite.getInstance().getKnockbackManager();
switch (args[0].toLowerCase()) {
case "create":
if (args.length < 2) {
sendMessage(sender, LanguageConfig.createUsage.getValue());
return;
}
String create = args[1];
if (manager.getByName(create) != null) {
sendMessage(sender, LanguageConfig.createExists.getValue()
.replace("%name%", create)
);
return;
}
IKnockback knockback = manager.createProfile(create);
sendMessage(sender, LanguageConfig.createProfile.getValue()
.replace("%name%", knockback.getName())
);
return;
case "delete":
if (args.length < 2) {
sendMessage(sender, LanguageConfig.deleteUsage.getValue());
return;
}
String delete = args[1];
if (manager.getByName(delete) == null) {
sendMessage(sender, LanguageConfig.profileNotFound.getValue()
.replace("%name%", delete)
);
return;
}
if (manager.getActiveProfile().getName().equalsIgnoreCase(delete)) {
sendMessage(sender, LanguageConfig.deleteActive.getValue()
.replace("%name%", delete)
);
return;
}
manager.deleteProfile(delete);
sendMessage(sender, LanguageConfig.deleteProfile.getValue()
.replace("%name%", delete)
);
return;
case "list":
for (String s : LanguageConfig.listMessage.getValue()) {
if (!s.equalsIgnoreCase("%profiles%")) {
sendMessage(sender, s);
continue;
}
for (IKnockback profile : manager.getProfiles()) {
String name = (profile.isActive() ? LanguageConfig.listNameActive.getValue() : LanguageConfig.listName.getValue());
new FancyMessage(name.replace("%name%", profile.getName()).replace("%type%", profile.getType()))
.tooltip(LanguageConfig.listNameHover.getValue().replace("%name%", profile.getName()))
.command("/knockback view " + profile.getName())
.send(sender);
}
}
return;
case "settype":
if (args.length < 2) {
sendMessage(sender, LanguageConfig.setTypeUsage.getValue());
return;
}
Knockback changingType = (Knockback) manager.getByName(args[1]);
KnockbackType type;
if (changingType == null) {
sendMessage(sender, LanguageConfig.profileNotFound.getValue()
.replace("%name%", args[1])
);
return;
}
if (args.length == 2) {
new FancyMessage(LanguageConfig.setTypePrefix.getValue())
.then(LanguageConfig.setTypeSimple.getValue())
.tooltip(LanguageConfig.setTypeSimpleHover.getValue())
.command("/knockback settype " + changingType.getName() + " SIMPLE")
.then(" ")
.then(LanguageConfig.setTypeAdvanced.getValue())
.tooltip(LanguageConfig.setTypeAdvancedHover.getValue())
.command("/knockback settype " + changingType.getName() + " ADVANCED")
.send(sender);
return;
}
try {
type = KnockbackType.valueOf(args[2]);
} catch (IllegalArgumentException e) {
sendMessage(sender, LanguageConfig.setTypeNotFound.getValue());
return;
}
if (changingType.getKnockbackType() == type) {
sendMessage(sender, LanguageConfig.setTypeAlready.getValue()
.replace("%name%", changingType.getName())
.replace("%type%", type.getDisplayName())
);
return;
}
changingType.knockbackType.set(type.name(), true);
sendMessage(sender, LanguageConfig.setType.getValue()
.replace("%name%", changingType.getName())
.replace("%type%", type.getDisplayName())
);
return;
case "setactive":
if (args.length < 2) {
sendMessage(sender, LanguageConfig.setActiveUsage.getValue());
return;
}
IKnockback active = manager.getByName(args[1]);
if (active == null) {
sendMessage(sender, LanguageConfig.profileNotFound.getValue()
.replace("%name%", args[1])
);
return;
}
if (manager.getActiveProfile().getName().equalsIgnoreCase(active.getName())) {
sendMessage(sender, LanguageConfig.setActiveAlready.getValue()
.replace("%name%", active.getName())
);
return;
}
manager.setActiveProfile(active);
sendMessage(sender, LanguageConfig.setActive.getValue()
.replace("%name%", active.getName())
);
return;
case "view":
if (args.length < 2) {
sendMessage(sender, LanguageConfig.viewUsage.getValue());
return;
}
IKnockback view = manager.getByName(args[1]);
if (view == null) {
sendMessage(sender, LanguageConfig.profileNotFound.getValue()
.replace("%name%", args[1])
);
return;
}
for (String s : LanguageConfig.viewMessage.getValue()) {
if (s.equalsIgnoreCase("%values%")) {
for (ConfigSetting<?> setting : ((Knockback) view).getActiveSettings()) {
UnaryOperator<String> replacer = string -> string
.replace("%setting%", setting.getName())
.replace("%type%", view.getType())
.replace("%value%", setting.getValue().toString());
new FancyMessage(replacer.apply(LanguageConfig.viewSetting.getValue()))
.tooltip(replacer.apply(LanguageConfig.viewSettingHover.getValue()))
.command("/knockback edit " + view.getName() + " " + setting.getName())
.send(sender);
}
continue;
}
if (s.equalsIgnoreCase("%clickables%")) {
UnaryOperator<String> replacer = string -> string.replace("%name%", view.getName());
new FancyMessage(LanguageConfig.viewSetActiveClick.getValue())
.tooltip(replacer.apply(LanguageConfig.viewSetActiveClickHover.getValue()))
.command("/knockback setactive " + view.getName())
.then(" ")
.then(LanguageConfig.viewDeleteClick.getValue())
.tooltip(replacer.apply(LanguageConfig.viewDeleteClickHover.getValue()))
.command("/knockback delete " + view.getName())
.then(" ")
.then(LanguageConfig.viewEditClick.getValue())
.tooltip(replacer.apply(LanguageConfig.viewEditHover.getValue()))
.command("/knockback editmenu " + view.getName())
.send(sender);
continue;
}
if (s.equalsIgnoreCase("%settype%")) {
UnaryOperator<String> replacer = string -> string.replace("%name%", view.getName());
new FancyMessage(LanguageConfig.viewSetTypeClick.getValue())
.tooltip(replacer.apply(LanguageConfig.viewSetTypeHover.getValue()))
.command("/knockback settype " + view.getName())
.send(sender);
continue;
}
sendMessage(sender, s
.replace("%name%", view.getName())
.replace("%type%", view.getType())
);
}
return;
case "edit":
if (args.length < 3) {
sendMessage(sender, LanguageConfig.editUsage.getValue());
return;
}
Knockback editing = (Knockback) manager.getByName(args[1]);
if (editing == null) {
sendMessage(sender, LanguageConfig.profileNotFound.getValue()
.replace("%name%", args[1])
);
return;
}
ConfigSetting<?> configSetting = editing.getActiveSetting(args[2]);
if (configSetting == null) {
sendMessage(sender, LanguageConfig.editSettingNotFound.getValue()
.replace("%setting%", args[2])
);
return;
}
if (args.length == 4) {
Object value = configSetting.parseValue(args[3]);
if (value == null) {
sendMessage(sender, LanguageConfig.notValidType.getValue()
.replace("%value%", args[3])
.replace("%type%", configSetting.getValue().getClass().getSimpleName())
);
return;
}
configSetting.set(value, true);
sendMessage(sender, LanguageConfig.editSettingValue.getValue()
.replace("%setting%", configSetting.getName())
.replace("%value%", args[3])
.replace("%profile%", editing.getName())
);
return;
}
if (!(sender instanceof Player)) {
sendMessage(sender, LanguageConfig.onlyPlayer.getValue());
return;
}
Player player = (Player) sender;
manager.getEditing().put(player.getUniqueId(), new KnockbackEdit(editing.getName(), configSetting));
sendMessage(sender, LanguageConfig.editTypeNewValue.getValue()
.replace("%setting%", configSetting.getName())
.replace("%current%", configSetting.getValue().toString())
.replace("%profile%", editing.getName())
);
return;
case "editmenu":
if (args.length < 2) {
sendMessage(sender, LanguageConfig.editMenuUsage.getValue());
return;
}
if (!(sender instanceof Player)) {
sendMessage(sender, LanguageConfig.onlyPlayer.getValue());
return;
}
Player opening = (Player) sender;
Knockback editMenu = (Knockback) manager.getByName(args[1]);
if (editMenu == null) {
sendMessage(sender, LanguageConfig.profileNotFound.getValue()
.replace("%name%", args[1])
);
return;
}
new ConfigEditMenu(opening, editMenu, null, editMenu.getActiveSettings()).open();
return;
case "set":
if (args.length < 3) {
sendMessage(sender, LanguageConfig.setUsage.getValue());
return;
}
IKnockback setting = manager.getByName(args[1]);
Player settingPlayer = Bukkit.getPlayer(args[2]);
if (setting == null) {
sendMessage(sender, LanguageConfig.profileNotFound.getValue()
.replace("%name%", args[1])
);
return;
}
if (settingPlayer == null) {
sendMessage(sender, LanguageConfig.playerNotFound.getValue()
.replace("%player%", args[2])
);
return;
}
settingPlayer.setKnockbackProfile(setting);
sendMessage(sender, LanguageConfig.setProfile.getValue()
.replace("%profile%", setting.getName())
.replace("%player%", settingPlayer.getName())
);
return;
case "clear":
if (args.length < 2) {
sendMessage(sender, LanguageConfig.clearUsage.getValue());
return;
}
Player clearingPlayer = Bukkit.getPlayer(args[1]);
if (clearingPlayer == null) {
sendMessage(sender, LanguageConfig.playerNotFound.getValue()
.replace("%player%", args[1])
);
return;
}
clearingPlayer.setKnockbackProfile(null);
sendMessage(sender, LanguageConfig.clearProfile.getValue()
.replace("%player%", clearingPlayer.getName())
);
return;
}
sendUsage(sender);
}
private void sendUsage(CommandSender sender) {
for (String s : LanguageConfig.knockbackUsage.getValue()) {
if (!s.equalsIgnoreCase("%commands%")) {
sendMessage(sender, s);
continue;
}
Arrays.asList(
new FancyMessage(LanguageConfig.createUsage.getValue())
.tooltip(LanguageConfig.createHover.getValue())
.suggest("/knockback create "),
new FancyMessage(LanguageConfig.deleteUsage.getValue())
.tooltip(LanguageConfig.deleteHover.getValue())
.suggest("/knockback delete "),
new FancyMessage(LanguageConfig.viewUsage.getValue())
.tooltip(LanguageConfig.viewHover.getValue())
.suggest("/knockback view "),
new FancyMessage(LanguageConfig.editUsage.getValue())
.tooltip(LanguageConfig.editHover.getValue())
.suggest("/knockback edit "),
new FancyMessage(LanguageConfig.editMenuUsage.getValue())
.tooltip(LanguageConfig.editMenuHover.getValue())
.suggest("/knockback editmenu "),
new FancyMessage(LanguageConfig.setUsage.getValue())
.tooltip(LanguageConfig.setHover.getValue())
.suggest("/knockback set "),
new FancyMessage(LanguageConfig.clearUsage.getValue())
.tooltip(LanguageConfig.clearHover.getValue())
.suggest("/knockback clear "),
new FancyMessage(LanguageConfig.setTypeUsage.getValue())
.tooltip(LanguageConfig.setTypeHover.getValue())
.suggest("/knockback settype "),
new FancyMessage(LanguageConfig.setActiveUsage.getValue())
.tooltip(LanguageConfig.setActiveHover.getValue())
.suggest("/knockback setactive "),
new FancyMessage(LanguageConfig.listUsage.getValue())
.tooltip(LanguageConfig.listHover.getValue())
.command("/knockback list")
).forEach(message -> message.send(sender));
}
}
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
if (args[0].equalsIgnoreCase("create")) {
return null;
}
if (args[0].equalsIgnoreCase("clear")) {
return super.tabComplete(sender, args); // Return player list
}
if (args[0].equalsIgnoreCase("settype") && args.length == 3) {
String string = args[args.length - 1];
return Arrays.stream(KnockbackType.values())
.map(KnockbackType::name)
.filter(s -> s.regionMatches(true, 0, string, 0, string.length()))
.collect(Collectors.toList());
}
if (args[0].equalsIgnoreCase("edit") && args.length == 3) {
IKnockback knockback = Azurite.getInstance().getKnockbackManager().getByName(args[1]);
if (knockback != null) {
String string = args[args.length - 1];
return knockback.getValues().keySet().stream()
.filter(s -> s.regionMatches(true, 0, string, 0, string.length()))
.collect(Collectors.toList());
}
}
if (args.length == 1) {
String string = args[args.length - 1];
return Stream.of("delete", "create", "setactive", "list", "edit", "editmenu", "set", "view", "clear")
.filter(s -> s.regionMatches(true, 0, string, 0, string.length()))
.collect(Collectors.toList());
}
if (args.length == 2) {
String string = args[args.length - 1];
return Azurite.getInstance().getKnockbackManager().getProfiles().stream()
.map(IKnockback::getName)
.filter(s -> s.regionMatches(true, 0, string, 0, string.length()))
.collect(Collectors.toList());
}
return super.tabComplete(sender, args);
}
}
@@ -0,0 +1,45 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
/**
* Copyright (c) 2025. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class NoTrackCommand extends Command {
public NoTrackCommand() {
super("notrack");
this.setPermission("azuritespigot.notrack");
this.setAliases(Arrays.asList("hiderange", "hideplayers"));
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sendMessage(sender, LanguageConfig.noTrackUsage.getValue());
return;
}
Integer amount = getInt(args[0]);
if (amount == null) {
sendMessage(sender, LanguageConfig.notValidType.getValue()
.replace("%value%", args[0])
.replace("%type%", Integer.class.getSimpleName())
);
return;
}
Azurite.getInstance().setNoTrackRange(amount);
sendMessage(sender, LanguageConfig.noTrackSet.getValue()
.replace("%range%", String.valueOf(amount))
);
}
}
@@ -0,0 +1,53 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.Player;
import java.util.Arrays;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class PingCommand extends Command {
public PingCommand() {
super("ping");
this.setAliases(Arrays.asList("latency", "myping"));
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
if (!(sender instanceof Player)) {
sendMessage(sender, LanguageConfig.onlyPlayer.getValue());
return;
}
Player player = (Player) sender;
sendMessage(sender, LanguageConfig.playerPing.getValue()
.replace("%ping%", String.valueOf(((CraftPlayer) player).getHandle().getPing()))
);
return;
}
Player target = Bukkit.getPlayer(args[0]);
if (target == null) {
sendMessage(sender, LanguageConfig.playerNotFound.getValue()
.replace("%player%", args[0])
);
return;
}
sendMessage(sender, LanguageConfig.otherPlayerPing.getValue()
.replace("%player%", target.getName())
.replace("%ping%", String.valueOf(((CraftPlayer) target).getHandle().getPing()))
);
}
}
@@ -0,0 +1,45 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import net.minecraft.server.MinecraftServer;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class SetMaxPlayersCommand extends Command {
public SetMaxPlayersCommand() {
super("setmaxplayers");
this.setPermission("azuritespigot.setmaxplayers");
this.setAliases(Arrays.asList("setslots", "setmaxonline"));
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sendMessage(sender, LanguageConfig.setMaxPlayersUsage.getValue());
return;
}
Integer amount = getInt(args[0]);
if (amount == null) {
sendMessage(sender, LanguageConfig.notValidType.getValue()
.replace("%value%", args[0])
.replace("%type%", Integer.class.getSimpleName())
);
return;
}
MinecraftServer.getServer().getPlayerList().maxPlayers = amount;
sendMessage(sender, LanguageConfig.setMaxPlayers.getValue()
.replace("%amount%", amount.toString())
);
}
}
@@ -0,0 +1,98 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.WorldServer;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class TPSCommand extends Command {
private static final long STARTUP_TIME = System.currentTimeMillis();
public TPSCommand() {
super("tps");
this.setPermission("azuritespigot.tps");
this.setAliases(Arrays.asList("tickspersecond", "stps", "servertps"));
}
@Override
public void execute(CommandSender sender, String[] args) {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
double[] tps = MinecraftServer.getServer().recentTps;
long totalMemory = Runtime.getRuntime().totalMemory() / 1048576L;
long freeMemory = Runtime.getRuntime().freeMemory() / 1048576L;
long aliveThreads = threads.stream().filter(Thread::isAlive).count();
long interruptedThreads = threads.stream().filter(Thread::isInterrupted).count();
long daemonThreads = threads.stream().filter(Thread::isDaemon).count();
int chunks = 0;
int entities = 0;
int tiles = 0;
for (WorldServer world : MinecraftServer.getServer().worlds) {
entities += world.entityList.size();
tiles += world.tileEntityList.size();
chunks += world.chunkProviderServer.chunks.size();
}
for (String string : LanguageConfig.tpsMessage.getValue()) {
sendMessage(sender, string
.replace("%server_tps%", Arrays.stream(tps).mapToObj(this::format).collect(Collectors.joining(", ")))
.replace("%uptime%", formatTime(System.currentTimeMillis() - STARTUP_TIME).trim())
.replace("%players%", String.valueOf(MinecraftServer.getServer().getPlayerList().players.size()))
.replace("%max_players%", String.valueOf(MinecraftServer.getServer().getPlayerList().maxPlayers))
.replace("%threads%", String.valueOf(threads.size()))
.replace("%alive%", String.valueOf(aliveThreads))
.replace("%interrupted%", String.valueOf(interruptedThreads))
.replace("%daemon%", String.valueOf(daemonThreads))
.replace("%entities%", Integer.toString(entities))
.replace("%tiles%", Integer.toString(tiles))
.replace("%chunks%", Integer.toString(chunks))
.replace("%free_memory%", Long.toString(freeMemory))
.replace("%max_memory%", Long.toString(totalMemory))
);
}
}
private String formatTime(long millis) {
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
if (days > 0L)
sb.append(days).append("d ");
if (hours > 0L)
sb.append(hours).append("h ");
if (minutes > 0L)
sb.append(minutes).append("m ");
if (seconds > 0L)
sb.append(seconds).append("s ");
return sb.toString();
}
private String format(double tps) {
return ((tps > 18.0) ? ChatColor.GREEN : (tps > 16.0) ? ChatColor.YELLOW : ChatColor.RED)
+ ((tps > 20.0) ? "*" : "") + Math.min(Math.round(tps * 100.0) / 100.0, 20.0);
}
}
@@ -0,0 +1,46 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.event.world.ChunkUnloadEvent;
import java.util.Arrays;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class UnloadChunksCommand extends Command {
public UnloadChunksCommand() {
super("unloadchunks");
this.setPermission("azuritespigot.unloadchunks");
this.setAliases(Arrays.asList("chunkunload", "chunksunload"));
}
@Override
public void execute(CommandSender sender, String[] args) {
int chunks = 0;
for (World world : Bukkit.getServer().getWorlds()) {
for (Chunk chunk : world.getLoadedChunks()) {
if (world.isChunkInUse(chunk.getX(), chunk.getZ())) continue;
if (chunk.unload(true)) {
ChunkUnloadEvent event = new ChunkUnloadEvent(chunk); // Azurite - Call chunk unload if the chunk was unloaded.
Bukkit.getPluginManager().callEvent(event);
chunks++;
}
}
}
sendMessage(sender, LanguageConfig.unloadedChunks.getValue()
.replace("%amount%", String.valueOf(chunks))
);
}
}
@@ -0,0 +1,119 @@
package dev.azurite.spigot.command;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.framework.commands.Command;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class VersionCommand extends Command {
public VersionCommand() {
super("version");
this.setAliases(Arrays.asList("ver", "about", "icanhasbukkit"));
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length > 0 && sender.hasPermission("bukkit.command.version")) {
StringBuilder name = new StringBuilder();
for (String arg : args) {
if (name.length() > 0) name.append(' ');
name.append(arg);
}
String pluginName = name.toString();
Plugin exactPlugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (exactPlugin != null) {
describeToSender(exactPlugin, sender);
return;
}
boolean found = false;
pluginName = pluginName.toLowerCase();
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (plugin.getName().toLowerCase().contains(pluginName)) {
describeToSender(plugin, sender);
found = true;
}
}
if (!found) {
sender.sendMessage("This server is not running any plugin by that name.");
sender.sendMessage("Use /plugins to get a list of plugins.");
}
return;
}
for (String string : LanguageConfig.versionMessage.getValue()) {
sendMessage(sender, string);
}
}
private void describeToSender(Plugin plugin, CommandSender sender) {
PluginDescriptionFile desc = plugin.getDescription();
sender.sendMessage(ChatColor.GREEN + desc.getName() + ChatColor.WHITE + " version " + ChatColor.GREEN + desc.getVersion());
if (desc.getDescription() != null) {
sender.sendMessage(desc.getDescription());
}
if (desc.getWebsite() != null) {
sender.sendMessage("Website: " + ChatColor.GREEN + desc.getWebsite());
}
if (!desc.getAuthors().isEmpty()) {
if (desc.getAuthors().size() == 1) {
sender.sendMessage("Author: " + getAuthors(desc));
} else {
sender.sendMessage("Authors: " + getAuthors(desc));
}
}
}
private String getAuthors(final PluginDescriptionFile desc) {
StringBuilder result = new StringBuilder();
List<String> authors = desc.getAuthors();
for (int i = 0; i < authors.size(); i++) {
if (result.length() > 0) {
result.append(ChatColor.WHITE);
if (i < authors.size() - 1) {
result.append(", ");
} else {
result.append(" and ");
}
}
result.append(ChatColor.GREEN);
result.append(authors.get(i));
}
return result.toString();
}
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
if (args.length == 1 && sender.hasPermission("bukkit.command.version")) {
List<String> completions = new ArrayList<>();
String toComplete = args[0].toLowerCase();
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (StringUtil.startsWithIgnoreCase(plugin.getName(), toComplete)) {
completions.add(plugin.getName());
}
}
return completions;
}
return super.tabComplete(sender, args);
}
}
@@ -0,0 +1,314 @@
package dev.azurite.spigot.configs;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.utils.CC;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class AzuriteConfig extends Config {
// License
public static final ConfigSetting<String> serverBranding = new ConfigSetting<>("AzuriteSpigot", "", "Used for commands and server ping data", false);
// Worlds ticking
public static final ConfigSetting<Boolean> disableBlockLighting = new ConfigSetting<>(false, "worlds.ticking");
public static final ConfigSetting<Boolean> tickBlocks = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickTileEntities = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickBeacons = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickBrewingStands = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickHoppers = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickVillages = new ConfigSetting<>(false, "worlds.ticking");
public static final ConfigSetting<Boolean> tickFurnaces = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickChunks = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickBiomeCache = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> tickWeather = new ConfigSetting<>(true, "worlds.ticking");
public static final ConfigSetting<Boolean> processPacketsInBetweenTicks = new ConfigSetting<>(true, "worlds.ticking", "Should we process packets between ticks, it is heavily recommended to keep this option toggled on");
public static final ConfigSetting<Boolean> flushWorldChangesInBetweenTicks = new ConfigSetting<>(true, "worlds.ticking", "Should we flush world changes in between ticks");
// Async Data Saving
public static final ConfigSetting<Boolean> asyncWorldDataSave = new ConfigSetting<>(true, "worlds.async-saving");
public static final ConfigSetting<Boolean> asyncNBTFileSave = new ConfigSetting<>(true, "worlds.async-saving");
public static final ConfigSetting<Boolean> asyncUserCacheSave = new ConfigSetting<>(true, "worlds.async-saving");
public static final ConfigSetting<Boolean> asyncPlayerDataSave = new ConfigSetting<>(true, "worlds.async-saving");
public static final ConfigSetting<Boolean> asyncPlayerStatsSave = new ConfigSetting<>(true, "worlds.async-saving");
// Auto Save
public static final ConfigSetting<Boolean> autoSaveMessages = new ConfigSetting<>(true, "worlds.autosave");
public static final ConfigSetting<Boolean> autoSaveInIncrements = new ConfigSetting<>(true, "worlds.autosave");
public static final ConfigSetting<Integer> autoSaveChunksPerTick = new ConfigSetting<>(200, "worlds.autosave");
public static final ConfigSetting<Boolean> autoSaveFireWorldSaveEvent = new ConfigSetting<>(false, "worlds.autosave");
public static final ConfigSetting<Boolean> autoSaveClearRegionFileCache = new ConfigSetting<>(false, "worlds.autosave");
// Commands
public static final ConfigSetting<Boolean> enableSpigotConfigCommand = new ConfigSetting<>(true, "worlds.commands");
public static final ConfigSetting<Boolean> enablePingCommand = new ConfigSetting<>(true, "worlds.commands");
public static final ConfigSetting<Boolean> enableTPSCommand = new ConfigSetting<>(true, "worlds.commands");
public static final ConfigSetting<Boolean> enableChunkUnloadCommand = new ConfigSetting<>(true, "worlds.commands");
public static final ConfigSetting<Boolean> enableClearLagCommand = new ConfigSetting<>(true, "worlds.commands");
public static final ConfigSetting<Boolean> enableSetMaxPlayersCommand = new ConfigSetting<>(true, "worlds.commands");
public static final ConfigSetting<Boolean> enableNoTrackCommand = new ConfigSetting<>(true, "worlds.commands");
// Chunks
public static final ConfigSetting<Boolean> cacheChunkMaps = new ConfigSetting<>(true, "worlds.chunks", "IMPORTANT! This patch is from paper and we highly suggest using. However if you get chunk corruption bugs turn this off. We have fixed a major issue with it.");
public static final ConfigSetting<Boolean> nullifyEmptySections = new ConfigSetting<>(false, "worlds.chunks", "This optimizes memory usage by making chunk sections null if they don't have any blocks at startup. This might break light levels and other things. This option is experimental, use at your own risk.");
public static final ConfigSetting<Integer> chunkLoadingThreads = new ConfigSetting<>(3, "worlds.chunks", false);
public static final ConfigSetting<Integer> playersPerThread = new ConfigSetting<>(100, "worlds.chunks");
public static final ConfigSetting<Boolean> chunkUnloading = new ConfigSetting<>(true, "worlds.chunks");
public static final ConfigSetting<Integer> unloadPerTick = new ConfigSetting<>(300, "worlds.chunks");
public static final ConfigSetting<Boolean> sendEmptyChunkSections = new ConfigSetting<>(false, "worlds.chunks", "Blossom patch which sends empty chunk sections to reduce skylight lag spike");
public static final ConfigSetting<Boolean> preloadChunksOnDimensionChange = new ConfigSetting<>(true, "worlds.chunks", "This option will make dimension changes take a bit longer to use as it will preload chunks asynchronously");
public static final ConfigSetting<Boolean> forceVoidChunks = new ConfigSetting<>(false, "worlds.chunks", "Generates all new chunks as void");
// Patchsearch
public static final ConfigSetting<Boolean> enableAsyncPathSearch = new ConfigSetting<>(true, "worlds.async-pathsearch");
public static final ConfigSetting<Integer> pathSearchThreads = new ConfigSetting<>(3, "worlds.async-pathsearch", false);
public static final ConfigSetting<Double> minimumDistanceToTarget = new ConfigSetting<>(0.0D, "worlds.async-pathsearch", false);
public static final ConfigSetting<List<String>> entitiesPathSearchOffload = new ConfigSetting<>(Arrays.asList("BAT", "BLAZE", "CHICKEN", "COW", "CREEPER", "ENDERMAN", "HORSE", "IRON_GOLEM", "MAGMA_CUBE", "MUSHROOM_COW", "PIG", "PIG_ZOMBIE", "RABBIT", "SHEEP", "SKELETON", "SILVERFISH", "SLIME", "SNOWMAN", "SQUID", "WITCH", "ZOMBIE"), "worlds.async-pathsearch", false);
// Projectiles
public static final ConfigSetting<Boolean> arrowCriticalDamage = new ConfigSetting<>(true, "worlds.projectiles", "Should critical arrow damage be enabled");
public static final ConfigSetting<Boolean> arrowCriticalDamageMedian = new ConfigSetting<>(true, "worlds.projectiles", "If arrowCriticalDamage is turned off, should we use the median for critical damage");
public static final ConfigSetting<Integer> minimumPotionTicksForSelfSplash = new ConfigSetting<>(5, "worlds.projectiles", "Defines the minimum amount of ticks the potion should have existed before it can collide with the shooter");
public static final ConfigSetting<Boolean> rodTrackedToCenterOfHooked = new ConfigSetting<>(true, "worlds.projectiles", "Should rod be constantly tracked to the center of the hooked entity");
public static final ConfigSetting<Boolean> checkStartOfRay = new ConfigSetting<>(true, "worlds.projectiles", "Should projectiles check the hitbox at start of ray, this fixes some of the projectiles going through players issues");
public static final ConfigSetting<Boolean> disableStuckArrows = new ConfigSetting<>(false, "worlds.projectiles", "Should stuck arrows in players be disabled");
public static final ConfigSetting<Float> arrowTrajectoryRandomness = new ConfigSetting<>(0.0F, "worlds.projectiles");
public static final ConfigSetting<Float> rodTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles");
public static final ConfigSetting<Float> snowballTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles");
public static final ConfigSetting<Float> eggTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles");
public static final ConfigSetting<Float> pearlTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles");
public static final ConfigSetting<Float> potionTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles");
// Sounds
public static final ConfigSetting<Boolean> itemFizzSounds = new ConfigSetting<>(true, "worlds.sounds");
public static final ConfigSetting<Boolean> fluidFizzSounds = new ConfigSetting<>(true, "worlds.sounds");
public static final ConfigSetting<Boolean> mobRandomSounds = new ConfigSetting<>(true, "worlds.sounds");
public static final ConfigSetting<Boolean> explosionSounds = new ConfigSetting<>(true, "worlds.sounds");
public static final ConfigSetting<Boolean> footstepSounds = new ConfigSetting<>(false, "worlds.sounds");
// Particles
public static final ConfigSetting<Boolean> dispenserEffects = new ConfigSetting<>(true, "worlds.particles");
public static final ConfigSetting<Boolean> spawnerParticles = new ConfigSetting<>(true, "worlds.particles");
public static final ConfigSetting<Boolean> explosionParticles = new ConfigSetting<>(true, "worlds.particles");
public static final ConfigSetting<Boolean> tntParticles = new ConfigSetting<>(true, "worlds.particles");
public static final ConfigSetting<Boolean> footstepParticles = new ConfigSetting<>(false, "worlds.particles");
public static final ConfigSetting<Boolean> selfPotionParticles = new ConfigSetting<>(true, "worlds.particles", "Should the player see his own potion particles");
public static final ConfigSetting<Boolean> drinkablePotionsNoParticles = new ConfigSetting<>(false, "worlds.particles", "Should drinkable potions not show particles");
// Modifiers
public static final ConfigSetting<Double> furnaceModifier = new ConfigSetting<>(1.0, "worlds.modifiers");
public static final ConfigSetting<Double> brewingModifier = new ConfigSetting<>(1.0, "worlds.modifiers");
public static final ConfigSetting<Double> fallDamageModifier = new ConfigSetting<>(1.0, "worlds.modifiers");
public static final ConfigSetting<Double> critDamageModifier = new ConfigSetting<>(1.5, "worlds.modifiers");
// Events
public static final ConfigSetting<Boolean> firePlayerMoveEvent = new ConfigSetting<>(true, "worlds.events");
public static final ConfigSetting<Boolean> fireBlockPhysicsEvent = new ConfigSetting<>(true, "worlds.events");
public static final ConfigSetting<Boolean> fireHopperMoveItemEvent = new ConfigSetting<>(true, "worlds.events");
public static final ConfigSetting<Boolean> fireSandBlockChangeEvent = new ConfigSetting<>(true, "worlds.events");
public static final ConfigSetting<Boolean> fireSandPhysicsEvent = new ConfigSetting<>(true, "worlds.events");
public static final ConfigSetting<Boolean> fireRedstonePhysicsEvent = new ConfigSetting<>(true, "worlds.events");
public static final ConfigSetting<Boolean> fireTNTDispenseEvent = new ConfigSetting<>(true, "worlds.events");
// Blocks
public static final ConfigSetting<String> redstoneOptimization = new ConfigSetting<>("EIGENCRAFT", "worlds.blocks", "Redstone implementation. Choose EIGENCRAFT/PANDAWIRE/DEFAULT", false);
public static final ConfigSetting<Double> tntYVelocityMultiplier = new ConfigSetting<>(1.0D, "worlds.blocks");
public static final ConfigSetting<Boolean> optimizeHoppers = new ConfigSetting<>(true, "worlds.blocks", "Use an experimental system to optimize hoppers");
public static final ConfigSetting<Boolean> gravelFall = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> grassSpread = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> grassSpreadLight = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> leafDecaying = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> dropFloatingPlants = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> dropExplosionBlocks = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> dispenserRandomness = new ConfigSetting<>(true, "worlds.blocks", "Optimizes cannons");
public static final ConfigSetting<Boolean> pistonPushEntities = new ConfigSetting<>(true, "worlds.blocks", "Push entities with piston");
public static final ConfigSetting<Integer> pistonMaxBlockPush = new ConfigSetting<>(12, "worlds.blocks", "Maximum blocks pushed by pistons");
public static final ConfigSetting<Boolean> infiniteWaterSources = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> waterDestroyRedstone = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> waterDestroysWeb = new ConfigSetting<>(true, "worlds.blocks");
public static final ConfigSetting<Boolean> oldEnchantingSystem = new ConfigSetting<>(false, "worlds.blocks", "Toggle for 1.7 enchanting system");
public static final ConfigSetting<Boolean> oldAnvilSystem = new ConfigSetting<>(false, "worlds.blocks", "Toggle for 1.7 anvil system");
public static final ConfigSetting<Boolean> removeAnvilUses = new ConfigSetting<>(false, "worlds.blocks", "Should we disable the increasing anvil cost (every time you use an anvil the XP requirement goes up)");
public static final ConfigSetting<Boolean> structureBookNerf = new ConfigSetting<>(false, "worlds.blocks", "Remove infinity and flame books from structure loot");
public static final ConfigSetting<Boolean> cobbleGenerating = new ConfigSetting<>(true, "worlds.blocks.generating", "Cobble generation from lava and water");
public static final ConfigSetting<Boolean> stoneGenerating = new ConfigSetting<>(true, "worlds.blocks.generating", "Stone generation from lava and water");
public static final ConfigSetting<Boolean> obsidianGenerating = new ConfigSetting<>(true, "worlds.blocks.generating", "Obsidian generation from lava and water");
public static final ConfigSetting<Integer> spongeRadius = new ConfigSetting<>(4, "worlds.blocks.sponges", "Sponge activation radius, 0 to disable");
public static final ConfigSetting<Boolean> spongePreventWaterFlow = new ConfigSetting<>(false, "worlds.blocks.sponges");
public static final ConfigSetting<Boolean> spongeInstantBreak = new ConfigSetting<>(false, "worlds.blocks.sponges", false);
// Spawners
public static final ConfigSetting<Integer> chunkMobLimit = new ConfigSetting<>(0, "worlds.spawners", "Number of mobs in a chunk to prevent spawning. 0 - to disable requirement");
public static final ConfigSetting<Integer> minimumSpawnDelay = new ConfigSetting<>(200, "worlds.spawners");
public static final ConfigSetting<Integer> maximumSpawnDelay = new ConfigSetting<>(800, "worlds.spawners");
public static final ConfigSetting<Integer> spawnCount = new ConfigSetting<>(4, "worlds.spawners");
public static final ConfigSetting<Double> spawnRange = new ConfigSetting<>(4.0, "worlds.spawners", "Spawn range for entities around the spawner");
public static final ConfigSetting<Double> playerSpawnRange = new ConfigSetting<>(16.0, "worlds.spawners", "Radius for players around to spawn");
public static final ConfigSetting<Integer> maximumNearbyEntities = new ConfigSetting<>(0, "worlds.spawners", "Amount of entities around the spawner to prevent spawning. 0 - to disable requirement");
public static final ConfigSetting<Boolean> lightLevelCheck = new ConfigSetting<>(true, "worlds.spawners");
// Players
public static final ConfigSetting<Boolean> trackPlayerStatistics = new ConfigSetting<>(true, "worlds.players");
public static final ConfigSetting<Boolean> prePlayerInfos = new ConfigSetting<>(true, "worlds.players", "Should player infos be send before join event, this fixes entity tracker desyncs if you get teleported on join");
public static final ConfigSetting<Boolean> horseHealthUpdates = new ConfigSetting<>(false, "worlds.players", "Should players receive health updates for horses, use this when you don't want horse health / healing to desync.");
public static final ConfigSetting<Boolean> savePlayerData = new ConfigSetting<>(true, "worlds.players", "Should player data be saved");
public static final ConfigSetting<Boolean> allowOnFireOnDeadBush = new ConfigSetting<>(true, "worlds.players", "Allows fire on dead bush");
public static final ConfigSetting<Boolean> oldExpLeveling = new ConfigSetting<>(false, "worlds.players", "Enable 1.7 leveling system");
public static final ConfigSetting<Boolean> oldBoats = new ConfigSetting<>(false, "worlds.players", "Enable 1.7 boat system");
public static final ConfigSetting<Boolean> alternativeRepair = new ConfigSetting<>(false, "worlds.blocks", "Directly combine durability when repairing items");
public static final ConfigSetting<Boolean> kohiVelocityPatch = new ConfigSetting<>(true, "worlds.players", "When velocity is set through bukkit for players it'll be applied instantly, this means the velocity won't go through friction but will be send immediately.");
public static final ConfigSetting<Boolean> serverSideHitDetection = new ConfigSetting<>(false, "worlds.players", "Toggle off if you have an anticheat. This will make hit detection better but could allow more cheats.");
public static final ConfigSetting<Boolean> useSystemTimeForNoDamageTicks = new ConfigSetting<>(false, "worlds.players", "Uses system time for no damage ticks, this makes hit delay more accurate in combination with processPacketsInBetweenTicks");
public static final ConfigSetting<Boolean> playerTeleportTracker = new ConfigSetting<>(true, "worlds.players", "Queues teleports to have more accuracy reducing ghost blocks by tracking player onGround properly");
public static final ConfigSetting<Boolean> playerBorderDamage = new ConfigSetting<>(false, "worlds.players");
public static final ConfigSetting<Boolean> playerMovedTooQuicklyCheck = new ConfigSetting<>(true, "worlds.players", "Toggle spigots moved too quickly check.");
public static final ConfigSetting<Boolean> checkPlayerSleep = new ConfigSetting<>(true, "worlds.players");
public static final ConfigSetting<Boolean> playerIdleTimer = new ConfigSetting<>(false, "worlds.players");
public static final ConfigSetting<Boolean> playerPingInterpolation = new ConfigSetting<>(true, "worlds.players", "Should the player's ping be 'interpolated' (this is default mc and prevents spikes from showing up heavily)");
public static final ConfigSetting<Double> playerPhaseLeniency = new ConfigSetting<>(1E-7D, "worlds.players", "Defines the length a player can go inside a block, if you experience issues with server setting back due to phase, we recommend setting it to 0.0625");
public static final ConfigSetting<Integer> invulnerableTicks = new ConfigSetting<>(60, "worlds.players", "How many ticks should the player be invulnerable when they join");
public static final ConfigSetting<Integer> trackerTicks = new ConfigSetting<>(2, "worlds.players", "How often (in ticks) should the player position be updated");
public static final ConfigSetting<Boolean> playerPhaseChestsAndAnvils = new ConfigSetting<>(false, "worlds.players", "Toggles chests & anvil bounding boxes, it is only recommended enabling this if you want to have protection against people glitching through chests & anvils");
public static final ConfigSetting<Integer> trackerDeltaAccuracy = new ConfigSetting<>(4, "worlds.players", "How much movement should a player have until his delta is broadcasted. Choose between 1 and 4. (1 = 0.03125, 4 is default spigot)");
public static final ConfigSetting<Boolean> dynamicParalellisedTracking = new ConfigSetting<>(true, "worlds.players", "Async player tracking. Server will decide when it should be used");
public static final ConfigSetting<Integer> playersNeededParalellisedTracking = new ConfigSetting<>(100, "worlds.players", "How many players should be tracked for us to run paralellised");
public static final ConfigSetting<Boolean> hideEntitiesThrownHidden = new ConfigSetting<>(false, "worlds.players", "Toggle hiding entities thrown by hidden players");
public static final ConfigSetting<Boolean> itemBreakSoundSelf = new ConfigSetting<>(true, "worlds.players", "Should players hear their own item break sound");
public static final ConfigSetting<Boolean> randomizeItemPickup = new ConfigSetting<>(false, "worlds.players", "Should item pickup be more randomized (this delays the pickup by a single tick to select a random player)");
public static final ConfigSetting<Boolean> protRandomness = new ConfigSetting<>(true, "worlds.players", "Toggle protection randomness (HCF server toggle off and check below)");
public static final ConfigSetting<Boolean> protRandomnessIfDisabledUseMedian = new ConfigSetting<>(false, "worlds.players", "Uses the median if prot randomness is disabled");
public static final ConfigSetting<Double> protectionModifier = new ConfigSetting<>(25.0, "worlds.players", "Protection damage modifier. If prot randomness is disabled make sure to change this to 20-23. Lower for more damage and higher for less damage");
public static final ConfigSetting<Double> armorDamageDivision = new ConfigSetting<>(4.0, "worlds.players", "Armor damage modifier (HCF should be 12)");
public static final ConfigSetting<Float> armorDurabilityRandomness = new ConfigSetting<>(0.6F, "worlds.players", "Armor durability random modifier (lower is less chance item takes damage)");
public static final ConfigSetting<Boolean> optimizePlayerPrinter = new ConfigSetting<>(false, "worlds.players", "Remove block place delay");
public static final ConfigSetting<Boolean> autoRespawnPlayer = new ConfigSetting<>(false, "worlds.players");
public static final ConfigSetting<Boolean> autoRemovePotionAfterDrink = new ConfigSetting<>(false, "worlds.players", "Should the potion bottle automatically remove itself after a player drank it");
public static final ConfigSetting<Boolean> milkOnlyRemovesBadEffects = new ConfigSetting<>(false, "worlds.players", "Toggle this to make milk only remove bad effects from the player (this is useful for custom encahnts HCF maps)");
public static final ConfigSetting<Double> expandArrowBoundingBox = new ConfigSetting<>(0.0D, "worlds.players", "Suggested: 0.1-0.5. Expands the bounding box of an arrow (only for hitting players) to make it more likely to hit. HCF Plugins can apply a 'noBoxExpand' metadata value (type: UUID of entity collection) to prevent the expanded arrow box size to work on teammates.");
public static final ConfigSetting<Integer> maxChatLength = new ConfigSetting<>(100, "worlds.players", "What should the max chat message length, increase this together with LunarClient Apollo to allow players to have longer chat messages on LunarClient");
public static final ConfigSetting<List<String>> potionLaunchOnClick = new ConfigSetting<>(Arrays.asList("HOPPER", "CHEST", "ENDER_CHEST"), "worlds.players");
// Compensation ticks
public static final ConfigSetting<Boolean> compensatedEating = new ConfigSetting<>(true, "worlds.players.compensated-ticks", "Should the server simulate ticks to compensate food, milk and potions for latency.");
public static final ConfigSetting<Boolean> compensatedPotions = new ConfigSetting<>(false, "worlds.players.compensated-ticks", "Should the server allow splashing potions on the shooter faster to compensate for latency.");
// Projectile Interpolation
public static final ConfigSetting<Boolean> arrowInterpolationRegistration = new ConfigSetting<>(true, "worlds.interpolation", "Should arrow hit registration be improved by accounting for interpolation");
public static final ConfigSetting<Boolean> arrowInterpolationRegistrationOnly = new ConfigSetting<>(false, "worlds.interpolation", "Only use the interpolation box for arrow hit registration");
public static final ConfigSetting<Boolean> rodInterpolationRegistration = new ConfigSetting<>(true, "worlds.interpolation", "Should rod hit registration be improved by accounting for interpolation");
public static final ConfigSetting<Boolean> rodInterpolationRegistrationOnly = new ConfigSetting<>(false, "worlds.interpolation", "Only use the interpolation box for rod hit registration");
public static final ConfigSetting<Boolean> projectileInterpolationRegistration = new ConfigSetting<>(true, "worlds.interpolation", "Should generic projectiles hit registration be improved by accounting for interpolation");
public static final ConfigSetting<Boolean> projectileInterpolationRegistrationOnly = new ConfigSetting<>(false, "worlds.interpolation", "Only use the interpolation box for generic projectiles hit registration");
// Networking
public static final ConfigSetting<Boolean> ipConsoleLog = new ConfigSetting<>(false, "worlds.players.networking");
public static final ConfigSetting<Boolean> ioUring = new ConfigSetting<>(false, "worlds.players.networking", "Use IO Uring if available (compression won't be enabled when this option is turned on)");
public static final ConfigSetting<Boolean> adaptiveAllocator = new ConfigSetting<>(false, "worlds.players.networking", "Use adaptive allocator");
public static final ConfigSetting<Boolean> networkBlockingJoin = new ConfigSetting<>(true, "worlds.players.networking", "PaperSpigot patch for preventing blocking while ticking. Toggle off if you have issues with your anticheat on join.", false);
public static final ConfigSetting<Boolean> tickPlayerLatency = new ConfigSetting<>(true, "worlds.players.networking", "Tick player latency on tablist");
public static final ConfigSetting<Integer> parentNettyThreads = new ConfigSetting<>(1, "worlds.players.networking", "1 Is sufficient as it is just responsible for accepting connections and offloading to child group", false);
public static final ConfigSetting<Integer> childNettyThreads = new ConfigSetting<>(0, "worlds.players.networking", "Default is 4, 0 is recommended which uses all processors available but will increase cpu usage.", false);
public static final ConfigSetting<Boolean> fastKeepAlive = new ConfigSetting<>(false, "worlds.players.networking", "Should we sent out a keepalive on player join and after they ticked once");
public static final ConfigSetting<Long> keepAliveUpdateFrequency = new ConfigSetting<>(40L, "worlds.players.networking", "How often (in ticks) should we send keepalive packets");
public static final ConfigSetting<Boolean> calculatePacketSize = new ConfigSetting<>(false, "worlds.players.networking", "Should we calculate the packet size before allocating the buffer the packet will be written to, this reduces direct memory by using more CPU to calculate expected bytes written.");
public static final ConfigSetting<Boolean> nettyWatchdog = new ConfigSetting<>(false, "worlds.players.networking", "Should we check for netty thread lagouts, this allows you to find potential crash exploits that people are abusing, or a plugin which is extremely slow");
// Better Slowdown
public static final ConfigSetting<Boolean> betterSlowdownEnabled = new ConfigSetting<>(true, "worlds.players.betterslowdown", "Should we run the Spigot implementation of BetterSlowdown https://github.com/Beaness/BetterSlowdown, this has better anticheat compatibility");
public static final ConfigSetting<String> betterSlowdownFallbackMode = new ConfigSetting<>("CLIENT", "worlds.players.betterslowdown", "What fallback mode should we use (read github for config for info)");
public static final ConfigSetting<Boolean> betterSlowdownAlwaysAddSprint = new ConfigSetting<>(true, "worlds.players.betterslowdown", "Should BetterSlowdown always add sprint when a player's speed is modified, this is definitely recommended for HCF servers so Bard speed effect doesn't break");
// Cps cap
public static final ConfigSetting<Boolean> cpsCapEnabled = new ConfigSetting<>(false, "worlds.players.cps-cap", "Should the cps penalty cap be enabled");
public static final ConfigSetting<Boolean> cpsCapSwordOnly = new ConfigSetting<>(false, "worlds.players.cps-cap", "Should only the cps of swinging your sword be counted");
public static final ConfigSetting<Integer> cpsCap = new ConfigSetting<>(15, "worlds.players.cps-cap", "What is the maximum cps the player can achieve (inclusive)");
public static final ConfigSetting<Integer> cpsCapPenaltyTicks = new ConfigSetting<>(30, "worlds.players.cps-cap", "How long should the player not be able to hit while being penalized (20 ticks = 1 second)");
public static final ConfigSetting<Boolean> cpsCapSendMessage = new ConfigSetting<>(true, "worlds.players.cps-cap");
public static final ConfigSetting<String> cpsCapMessage = new ConfigSetting<>("&cYou are clicking over %cps% CPS. Click below this to make sure your hits dont cancel.", "worlds.players.cps-cap", false);
// Knockback
public static final ConfigSetting<String> globalActiveKnockback = new ConfigSetting<>("Default", "worlds.players.knockback", "Which profile should we use as the default", false);
public static final ConfigSetting<Boolean> overrideDefaultKnockback = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback");
public static final ConfigSetting<Boolean> nonPlayerEntitiesOverrideDefaultKnockback = new ConfigSetting<>(false, "worlds.players.knockback", "Should non player entities use the custom kb system");
public static final ConfigSetting<Boolean> overrideRodKnockback = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback for rod knockback");
public static final ConfigSetting<Boolean> overrideArrowKnockback = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback for arrow knockback");
public static final ConfigSetting<Boolean> overrideOnlyHealthPotion = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback for only health potions");
// Player patches
public static final ConfigSetting<Boolean> patchArrowBounceBug = new ConfigSetting<>(true, "worlds.players.patches", "Toggles the arrow hit delay in knockback profiles.");
public static final ConfigSetting<Boolean> patchDoubleHitBug = new ConfigSetting<>(false, "worlds.players.patches", "Toggles the double hit bug fix");
public static final ConfigSetting<Boolean> patchDropEatRunBug = new ConfigSetting<>(false, "worlds.players.patches", "Prevents the player from exploiting a drop bug to run after dropping food while eating, not compatible with the other patches");
public static final ConfigSetting<Boolean> patchDropEatBug = new ConfigSetting<>(true, "worlds.players.patches", "Releases player's item if they drop & eat at the same time");
public static final ConfigSetting<Boolean> patchRunEatBug = new ConfigSetting<>(true, "worlds.players.patches", "Prevents the player from running & eating in all situations");
public static final ConfigSetting<Boolean> patchItemDesyncBug = new ConfigSetting<>(true, "worlds.players.patches", "Minecraft client can sometimes desync the use of an item due to set slot updates to items, by enabling this patch it will reduce this desync because it will no longer send durability updates to the holding item. Other causes like plugins updating the inventory can still desync it.");
public static final ConfigSetting<Boolean> patchHealthRendering = new ConfigSetting<>(true, "worlds.players.patches", "The minecraft client ceils the health value sent by the server which means 19.001 health becomes full HP, this patch fixes this issue by rounding the health before sending it to the client");
public static final ConfigSetting<Boolean> patchGhostBuckets = new ConfigSetting<>(true, "worlds.players.patches", "This makes sure the server uses the correct location for placing liquids by waiting for the client tick packet");
public static final ConfigSetting<Boolean> patchProjectileMisdirection = new ConfigSetting<>(true, "worlds.players.patches", "This makes the server use the correct yaw & pitch for projectiles (does not include bows)");
public static final ConfigSetting<Boolean> patchBowMisdirection = new ConfigSetting<>(true, "worlds.players.patches", "This makes the server use the correct yaw & pitch for bows");
public static final ConfigSetting<Boolean> patchProjectileOffset = new ConfigSetting<>(false, "worlds.players.patches", "This removes the projectile offset (to the right)");
public static final ConfigSetting<Boolean> patchHCFRegenBug = new ConfigSetting<>(true, "worlds.players.patches", "This makes regeneration weaker as players in teamfights are often invincible with regular regen.");
public static final ConfigSetting<Boolean> obfuscateEntityEquipment = new ConfigSetting<>(true, "worlds.players.patches", "Obfuscates equipment to deny a few cheats");
// Menus
public static final ConfigSetting<Boolean> fillerEnabled = new ConfigSetting<>(true, "worlds.players.menus", false);
public static final ConfigSetting<String> fillerType = new ConfigSetting<>("STAINED_GLASS_PANE", "worlds.players.menus", false);
public static final ConfigSetting<Integer> fillerData = new ConfigSetting<>(7, "worlds.players.menus", false);
public static final ConfigSetting<String> pageType = new ConfigSetting<>("CARPET", "worlds.players.menus", false);
public static final ConfigSetting<Integer> pageData = new ConfigSetting<>(2, "worlds.players.menus", false);
public static final ConfigSetting<String> pageBackDisplay = new ConfigSetting<>("&dPrevious Page", "worlds.players.menus", false);
public static final ConfigSetting<List<String>> pageBackLore = new ConfigSetting<>(Collections.singletonList("&e(Current Page: &2%page%/%max-pages%&e)"), "worlds.players.menus", false);
public static final ConfigSetting<String> pageForwardDisplay = new ConfigSetting<>("&dNext Page", "worlds.players.menus", false);
public static final ConfigSetting<List<String>> pageForwardLore = new ConfigSetting<>(Collections.singletonList("&e(Current Page: &2%page%/%max-pages%&e)"), "worlds.players.menus", false);
public static final ConfigSetting<String> backButtonType = new ConfigSetting<>("BED", "worlds.players.menus", false);
public static final ConfigSetting<Integer> backButtonData = new ConfigSetting<>(0, "worlds.players.menus", false);
public static final ConfigSetting<String> backButtonDisplay = new ConfigSetting<>("&cBack", "worlds.players.menus", false);
// Mobs
public static final ConfigSetting<Boolean> mobAI = new ConfigSetting<>(true, "worlds.mobs", "Toggle this option to disable mobAI");
public static final ConfigSetting<Boolean> mobAISpawners = new ConfigSetting<>(true, "worlds.mobs", "Toggle this option to so mob AI works for entities that spawn from spawners (overrides mobAI)");
public static final ConfigSetting<Boolean> mobAIHorses = new ConfigSetting<>(true, "worlds.mobs", "Toggle this option to make it so mob AI works for horses (overrides mobAI)");
public static final ConfigSetting<Boolean> naturalMobSpawn = new ConfigSetting<>(true, "worlds.mobs");
public static final ConfigSetting<Boolean> ironGolemFallDamage = new ConfigSetting<>(true, "worlds.mobs");
public static final ConfigSetting<Boolean> snowGolemFallDamage = new ConfigSetting<>(true, "worlds.mobs");
public static final ConfigSetting<Boolean> babyZombieSpawning = new ConfigSetting<>(true, "worlds.mobs");
public static final ConfigSetting<Boolean> zombieOnChickenSpawning = new ConfigSetting<>(true, "worlds.mobs");
public static final ConfigSetting<Boolean> villagerZombieSpawning = new ConfigSetting<>(true, "worlds.mobs");
public static final ConfigSetting<Boolean> skeletonOnSpiderSpawning = new ConfigSetting<>(true, "worlds.mobs");
public static final ConfigSetting<Boolean> entityCollisions = new ConfigSetting<>(true, "worlds.mobs", "Toggle this off if you want the best performance");
public static final ConfigSetting<Boolean> playerCollisions = new ConfigSetting<>(false, "worlds.mobs", "Should collision be ran on player entities, this affects their kb when you are close to someone. Enable this for vanilla behaivour.");
public static final ConfigSetting<Integer> entityCollisionsDelay = new ConfigSetting<>(1, "worlds.mobs", "A delay of 4 is recommended");
// Factions
public static final ConfigSetting<Boolean> fixFreecamCegging = new ConfigSetting<>(false, "factions", "Only enable if it is an issue! May cause performance issues");
public static final ConfigSetting<Boolean> sandMerging = new ConfigSetting<>(false, "factions");
public static final ConfigSetting<Boolean> tntMerging = new ConfigSetting<>(false, "factions");
public static final ConfigSetting<Boolean> hidePistonAnimations = new ConfigSetting<>(false, "factions");
public static final ConfigSetting<Boolean> hideTntEntity = new ConfigSetting<>(false, "factions");
public static final ConfigSetting<Boolean> hideSandEntity = new ConfigSetting<>(false, "factions");
public static final ConfigSetting<Boolean> fixSandChunkUnloading = new ConfigSetting<>(true, "factions");
public static final ConfigSetting<Boolean> optimizeTNTMovement = new ConfigSetting<>(false, "factions");
public static final ConfigSetting<Boolean> optimizeSandMovement = new ConfigSetting<>(false, "factions");
public static final ConfigSetting<Boolean> fixEastWestCannon = new ConfigSetting<>(true, "factions");
// Durability checker
public static final ConfigSetting<Boolean> explosionDestroyer = new ConfigSetting<>(false, "factions.durability");
public static final ConfigSetting<Double> explosionBlockPower = new ConfigSetting<>(1.12D, "factions.durability", "Adjust explosion block power");
public static final ConfigSetting<Double> explosionEntityPower = new ConfigSetting<>(2.0D, "factions.durability", "Adjust explosion entity power");
public static final ConfigSetting<String> durabilityItemChecker = new ConfigSetting<>("potato", "factions.durability", false);
public static final ConfigSetting<Boolean> damageOnlyByTNT = new ConfigSetting<>(false, "factions.durability");
public static final ConfigSetting<List<String>> blockDurabilities = new ConfigSetting<>(Arrays.asList("obsidian:3", "bedrock:5", "end_stone:5"), "factions.durability", false);
public static final ConfigSetting<List<String>> blockResistances = new ConfigSetting<>(Arrays.asList("obsidian:35.0", "bedrock:60.0", "end_stone:45.0", "anvil:2000.0"), "factions.durability", false);
public AzuriteConfig(Azurite instance) {
super(instance, "azurite", CC.getConfigHeader("Azurite configuration", "You will find all the main mechanics here"));
}
}
@@ -0,0 +1,44 @@
package dev.azurite.spigot.configs;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.utils.CC;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class EnchantConfig extends Config {
public static ConfigSetting<Integer> unbreaking = new ConfigSetting<>(3, "enchant-limits");
public static ConfigSetting<Integer> protectionAll = new ConfigSetting<>(4, "enchant-limits.armor");
public static ConfigSetting<Integer> protectionFire = new ConfigSetting<>(4, "enchant-limits.armor");
public static ConfigSetting<Integer> protectionFall = new ConfigSetting<>(4, "enchant-limits.armor");
public static ConfigSetting<Integer> protectionExplosion = new ConfigSetting<>(4, "enchant-limits.armor");
public static ConfigSetting<Integer> protectionProjectile = new ConfigSetting<>(4, "enchant-limits.armor");
public static ConfigSetting<Integer> thorns = new ConfigSetting<>(3, "enchant-limits.armor");
public static ConfigSetting<Integer> aquaAffinity = new ConfigSetting<>(1, "enchant-limits.armor");
public static ConfigSetting<Integer> waterBreathing = new ConfigSetting<>(3, "enchant-limits.armor");
public static ConfigSetting<Integer> depthStrider = new ConfigSetting<>(3, "enchant-limits.armor");
public static ConfigSetting<Integer> efficiency = new ConfigSetting<>(5, "enchant-limits.tools");
public static ConfigSetting<Integer> silkTouch = new ConfigSetting<>(1, "enchant-limits.tools");
public static ConfigSetting<Integer> fortune = new ConfigSetting<>(3, "enchant-limits.tools");
public static ConfigSetting<Integer> sharpness = new ConfigSetting<>(5, "enchant-limits.swords");
public static ConfigSetting<Integer> baneOfArthropods = new ConfigSetting<>(5, "enchant-limits.swords");
public static ConfigSetting<Integer> smite = new ConfigSetting<>(5, "enchant-limits.swords");
public static ConfigSetting<Integer> fireAspect = new ConfigSetting<>(2, "enchant-limits.swords");
public static ConfigSetting<Integer> knockback = new ConfigSetting<>(2, "enchant-limits.swords");
public static ConfigSetting<Integer> looting = new ConfigSetting<>(3, "enchant-limits.swords");
public static ConfigSetting<Integer> power = new ConfigSetting<>(5, "enchant-limits.bows");
public static ConfigSetting<Integer> punch = new ConfigSetting<>(2, "enchant-limits.bows");
public static ConfigSetting<Integer> flame = new ConfigSetting<>(1, "enchant-limits.bows");
public static ConfigSetting<Integer> infinity = new ConfigSetting<>(1, "enchant-limits.bows");
public static ConfigSetting<Integer> lure = new ConfigSetting<>(3, "enchant-limits.rods");
public static ConfigSetting<Integer> luckOfTheSea = new ConfigSetting<>(3, "enchant-limits.rods");
public EnchantConfig(Azurite azurite) {
super(azurite, "enchants", CC.getConfigHeader("Enchantment limit configuration", "Increase or decrease the limit of any enchant"));
}
}
@@ -0,0 +1,162 @@
package dev.azurite.spigot.configs;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.utils.CC;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class LanguageConfig extends Config {
// Global
public static final ConfigSetting<String> insufficientPerm = new ConfigSetting<>("&dAzuriteSpigot &7┃ &cYou do not have access to this command.", "messages");
public static final ConfigSetting<String> onlyPlayer = new ConfigSetting<>("&dThis command can only be used by players.", "messages");
public static final ConfigSetting<String> playerNotFound = new ConfigSetting<>("&ePlayer &d%player% &ecould not be found.", "messages");
public static final ConfigSetting<String> notValidType = new ConfigSetting<>("&eValue &d%value% &eis not type &a%type%&e.", "messages");
// Player
public static final ConfigSetting<String> disconnectSpam = new ConfigSetting<>("disconnect.spam", "messages.player");
public static final ConfigSetting<String> loggedInAnotherLocation = new ConfigSetting<>("You logged in from another location", "messages.player");
public static final ConfigSetting<String> factionsDurabilityChecker = new ConfigSetting<>("&eDurability: &d%durability%", "messages.player");
// Commands
public static final ConfigSetting<String> playerPing = new ConfigSetting<>("&d[Ping] &eYour Ping: &d%ping%ms", "messages.command.ping-command");
public static final ConfigSetting<String> otherPlayerPing = new ConfigSetting<>("&d[Ping] &e%player%'s Ping: &d%ping%ms", "messages.command.ping-command");
public static final ConfigSetting<String> configReloaded = new ConfigSetting<>("&eConfigs have been reloaded in &d%ms%ms&e.", "messages.command.config-command");
public static final ConfigSetting<String> clearedLag = new ConfigSetting<>("&eYou have cleared &d%entities% &eentities.", "messages.command.clear-lag-command");
public static final ConfigSetting<String> setMaxPlayersUsage = new ConfigSetting<>("&cUsage: /setmaxplayers <amount>", "messages.command.set-max-players-command");
public static final ConfigSetting<String> setMaxPlayers = new ConfigSetting<>("&eSet max players to &d%amount% &eplayers.", "messages.command.set-max-players-command");
public static final ConfigSetting<String> unloadedChunks = new ConfigSetting<>("&eYou have unloaded &d%amount% &echunks.", "messages.command.unload-chunks-command");
public static final ConfigSetting<List<String>> versionMessage = new ConfigSetting<>(Collections.singletonList(
"&fThis server is running &dAzuriteSpigot &fversion 1.8.8-R0.1-SNAPSHOT."
), "messages.command.version-command");
public static final ConfigSetting<List<String>> tpsMessage = new ConfigSetting<>(Arrays.asList(
"&7&m-------------------------",
"&d[Server TPS]",
"&f(TPS from 1s, 5s, 15s: %server_tps%&f)",
"&f(Memory: &e%free_memory%&7/&e%max_memory% MB&f) &7- &f(Uptime: &6%uptime%&f)",
"&f(Threads: &b%threads%&f) &7- &f(Alive: &a%alive%&f, Interrupted: &c%interrupted%&f, Daemon: &9%daemon%&f)",
"&f(Chunks: &2%chunks%&f) &7- &f(Players: &c%players%&7/&c%max_players%&f)",
"&f(Entities: &3%entities%&f) &7- &f(Tile Entities: &e%tiles%&f)",
"&7&m-------------------------"
), "messages.command.tps-command");
// No track
public static final ConfigSetting<String> noTrackUsage = new ConfigSetting<>("&cUsage: /notrack <range>", "messages.no-track");
public static final ConfigSetting<String> noTrackSet = new ConfigSetting<>("&eUpdated no track range to &d%range%&e.", "messages.no-track");
// Knockback
public static final ConfigSetting<List<String>> knockbackUsage = new ConfigSetting<>(Arrays.asList(
"&7&m-------------------------",
"&d[Knockback Usage]",
"%commands%",
"&7&m-------------------------"
), "messages.knockback");
public static final ConfigSetting<String> profileNotFound = new ConfigSetting<>("&eProfile &d%name% &ecould not be found.", "messages.knockback");
// Create
public static final ConfigSetting<String> createUsage = new ConfigSetting<>("&d- &f/knockback create <name>", "messages.knockback.knockback-create");
public static final ConfigSetting<String> createHover = new ConfigSetting<>("&eClick to create a new profile.", "messages.knockback.knockback-create");
public static final ConfigSetting<String> createExists = new ConfigSetting<>("&eProfile &d%name% &ealready exists.", "messages.knockback.knockback-create");
public static final ConfigSetting<String> createProfile = new ConfigSetting<>("&eProfile &d%name% &ehas been created.", "messages.knockback.knockback-create");
// Delete
public static final ConfigSetting<String> deleteUsage = new ConfigSetting<>("&d- &f/knockback delete <name>", "messages.knockback.knockback-delete");
public static final ConfigSetting<String> deleteHover = new ConfigSetting<>("&eClick to delete a profile.", "messages.knockback.knockback-delete");
public static final ConfigSetting<String> deleteActive = new ConfigSetting<>("&eYou cannot delete &d%name% &eas it is a active profile.", "messages.knockback.knockback-delete");
public static final ConfigSetting<String> deleteProfile = new ConfigSetting<>("&eProfile &d%name% &ehas been deleted.", "messages.knockback.knockback-delete");
// List
public static final ConfigSetting<String> listUsage = new ConfigSetting<>("&d- &f/knockback list", "messages.knockback.knockback-list");
public static final ConfigSetting<String> listHover = new ConfigSetting<>("&eClick to list profiles.", "messages.knockback.knockback-list");
public static final ConfigSetting<String> listName = new ConfigSetting<>("&d- &f%name%", "messages.knockback.knockback-list");
public static final ConfigSetting<String> listNameActive = new ConfigSetting<>("&d- &2%name% &7(Active)", "messages.knockback.knockback-list");
public static final ConfigSetting<String> listNameHover = new ConfigSetting<>("&eClick to view &d%name%''s &evalues.", "messages.knockback.knockback-list");
public static final ConfigSetting<List<String>> listMessage = new ConfigSetting<>(Arrays.asList(
"&7&m-------------------------",
"&d[Knockback Profiles]",
"%profiles%",
"&7&m-------------------------"
), "messages.knockback.knockback-list");
// Set Type
public static final ConfigSetting<String> setTypeUsage = new ConfigSetting<>("&d- &f/knockback settype <name> <ADVANCED|SIMPLE|CONSTANT>", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypeHover = new ConfigSetting<>("&eClick to change a profiles type.", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypeAlready = new ConfigSetting<>("&eProfile &d%name% &eis already type &c%type%&e.", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypeNotFound = new ConfigSetting<>("&eProfile type needs to be: &dSimple/Advanced", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypePrefix = new ConfigSetting<>("&eClick new type: ", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypeSimple = new ConfigSetting<>("&b[Simple]", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypeAdvanced = new ConfigSetting<>("&4[Advanced]", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypeSimpleHover = new ConfigSetting<>("&eClick to change profile to &dSimple&e.", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setTypeAdvancedHover = new ConfigSetting<>("&eClick to change profile to &dAdvanced&e.", "messages.knockback.knockback-settype");
public static final ConfigSetting<String> setType = new ConfigSetting<>("&eProfile &d%name% &eis now type &c%type%&e.", "messages.knockback.knockback-settype");
// Set Active
public static final ConfigSetting<String> setActiveUsage = new ConfigSetting<>("&d- &f/knockback setactive <name>", "messages.knockback.knockback-setactive");
public static final ConfigSetting<String> setActiveHover = new ConfigSetting<>("&eClick to set an active profile.", "messages.knockback.knockback-setactive");
public static final ConfigSetting<String> setActiveAlready = new ConfigSetting<>("&eProfile &d%name% &eis already active.", "messages.knockback.knockback-setactive");
public static final ConfigSetting<String> setActive = new ConfigSetting<>("&eProfile &d%name% &eis now globally active.", "messages.knockback.knockback-setactive");
// View
public static final ConfigSetting<String> viewUsage = new ConfigSetting<>("&d- &f/knockback view <name>", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewHover = new ConfigSetting<>("&eClick to view a profile.", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewSetting = new ConfigSetting<>("&d- &f%setting%&7: &d%value%", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewSettingHover = new ConfigSetting<>("&eClick to set a new value for &d%setting%&e.", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewSetActiveClick = new ConfigSetting<>("&a[Set Active]", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewSetActiveClickHover = new ConfigSetting<>("&eClick to set profile &d%name% &eactive.", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewDeleteClick = new ConfigSetting<>("&c[Delete]", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewDeleteClickHover = new ConfigSetting<>("&eClick to delete &d%name%&e.", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewEditClick = new ConfigSetting<>("&6[Edit]", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewEditHover = new ConfigSetting<>("&eClick to edit &d%name%&e.", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewSetTypeClick = new ConfigSetting<>("&d[Change Knockback Type]", "messages.knockback.knockback-view");
public static final ConfigSetting<String> viewSetTypeHover = new ConfigSetting<>("&eClick to change knockback type for &d%name%&e.", "messages.knockback.knockback-view");
public static final ConfigSetting<List<String>> viewMessage = new ConfigSetting<>(Arrays.asList(
"&7&m-------------------------",
"&d[%name%] &7(%type%)",
"%values%",
"%clickables%",
"%settype%",
"&7&m-------------------------"
), "messages.knockback.knockback-view");
// Edit
public static final ConfigSetting<String> editUsage = new ConfigSetting<>("&d- &f/knockback edit <name> <setting> <value>", "messages.knockback.knockback-edit");
public static final ConfigSetting<String> editHover = new ConfigSetting<>("&eClick to edit a profiles values.", "messages.knockback.knockback-edit");
public static final ConfigSetting<String> editSettingNotFound = new ConfigSetting<>("&eSetting &d%setting% &ecould not be found.", "messages.knockback.knockback-edit");
public static final ConfigSetting<String> editTypeNewValue = new ConfigSetting<>("&eType a value for &d%setting% &e(Current: &2%current%&e) &eType &ccancel &eto cancel.", "messages.knockback.knockback-edit");
public static final ConfigSetting<String> editCancelled = new ConfigSetting<>("&eEditing for value &d%setting% &ehas been cancelled.", "messages.knockback.knockback-edit");
public static final ConfigSetting<String> editSettingValue = new ConfigSetting<>("&eSet the value of &d%setting% &eto &2%value% &efor profile &c%profile%&e.", "messages.knockback.knockback-edit");
// Edit menu
public static final ConfigSetting<String> editMenuUsage = new ConfigSetting<>("&d- &f/knockback editmenu <name>", "messages.knockback.knockback-editmenu");
public static final ConfigSetting<String> editMenuHover = new ConfigSetting<>("&eClick to edit a profile.", "messages.knockback.knockback-editmenu");
// Set
public static final ConfigSetting<String> setUsage = new ConfigSetting<>("&d- &f/knockback set <name> <player>", "messages.knockback.knockback-set");
public static final ConfigSetting<String> setHover = new ConfigSetting<>("&eClick to set a players profile.", "messages.knockback.knockback-set");
public static final ConfigSetting<String> setProfile = new ConfigSetting<>("&eSet profile &d%profile% &eto player &2%player%&e.", "messages.knockback.knockback-set");
// Clear
public static final ConfigSetting<String> clearUsage = new ConfigSetting<>("&d- &f/knockback clear <player>", "messages.knockback.knockback-clear");
public static final ConfigSetting<String> clearHover = new ConfigSetting<>("&eClick to clear a players profile.", "messages.knockback.knockback-clear");
public static final ConfigSetting<String> clearProfile = new ConfigSetting<>("&eReset &d%player%&e''s active profile.", "messages.knockback.knockback-clear");
// Config edits
public static final ConfigSetting<String> configEditNewValue = new ConfigSetting<>("&eType a value for &d%setting% &e(Current: &2%current%&e) &eType &ccancel &eto cancel.", "messages.config-editing");
public static final ConfigSetting<String> configEditCancelled = new ConfigSetting<>("&eEditing for value &d%setting% &ehas been cancelled.", "messages.config-editing");
public static final ConfigSetting<String> configEditSetValue = new ConfigSetting<>("&eSet the value of &d%setting% &eto &2%value%&e.", "messages.config-editing");
public LanguageConfig(Azurite azurite) {
super(azurite, "language", CC.getConfigHeader("Messages configuration", "You will find all the language here"));
}
}
@@ -0,0 +1,143 @@
package dev.azurite.spigot.configs;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.utils.CC;
import org.bukkit.Material;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class PearlConfig extends Config {
// Anti Glitch
public static final ConfigSetting<Boolean> fixBlockGlitch = new ConfigSetting<>(true, "antiGlitch");
public static final ConfigSetting<Boolean> fixFenceGlitch = new ConfigSetting<>(true, "antiGlitch");
public static final ConfigSetting<Boolean> refundSuffocation = new ConfigSetting<>(true, "antiGlitch");
public static final ConfigSetting<Boolean> refundRiskyPearl = new ConfigSetting<>(true, "antiGlitch");
public static final ConfigSetting<Boolean> refundOnCritblock = new ConfigSetting<>(false, "antiGlitch");
public static final ConfigSetting<Double> refundCloseDistance = new ConfigSetting<>(0.5, "antiGlitch");
public static final ConfigSetting<Boolean> glitchReturnPearl = new ConfigSetting<>(true, "antiGlitch");
public static final ConfigSetting<String> glitchReturnMessage = new ConfigSetting<>("", "antiGlitch", false);
public static final ConfigSetting<String> glitchReturnCommand = new ConfigSetting<>("timer remove %player% Enderpearl", "antiGlitch", false);
// Misc
public static final ConfigSetting<Boolean> practicePearls = new ConfigSetting<>(true, "teleport.misc", "Pearls used on ElevateMC, this changes the pearl hit detection");
public static final ConfigSetting<Boolean> instantlyTaliTeleport = new ConfigSetting<>(false, "teleport.misc");
public static final ConfigSetting<Boolean> entityTpHitDetection = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> entityTpGetOutOneByOne = new ConfigSetting<>(true, "teleport.misc", "Deny entity TP system if you are in a one by one");
public static final ConfigSetting<Boolean> spawnEndermite = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> pearlThruFence = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> pearlThruString = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> pearlThruWeb = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> pearlThruPlants = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> pearlHopperUnderFence = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> pearlChestUnderFence = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Boolean> pearlParticlesEnabled = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<Integer> pearlParticleCount = new ConfigSetting<>(32, "teleport.misc");
public static final ConfigSetting<Double> pearlDamage = new ConfigSetting<>(5.0, "teleport.misc");
public static final ConfigSetting<Double> crossPearlMoveHelper = new ConfigSetting<>(0.35, "teleport.misc", "How much should we move the player inside the block when cross-pearling");
public static final ConfigSetting<Boolean> hitBlockTeleport = new ConfigSetting<>(true, "teleport.misc", "Should we teleport them if they throw an enderpearl directly on the block");
public static final ConfigSetting<Boolean> beforeBlockTeleport = new ConfigSetting<>(true, "teleport.misc", "Should we teleport them if they throw an enderpearl just before the block (Like ViperMC)");
public static final ConfigSetting<Integer> maxTeleportBlocks = new ConfigSetting<>(3, "teleport.misc", "Maximum amount of blocks you can tali teleport through");
public static final ConfigSetting<Boolean> launchOnFenceClick = new ConfigSetting<>(true, "teleport.misc");
public static final ConfigSetting<List<String>> launchOnOtherClick = new ConfigSetting<>(Arrays.asList("FURNACE", "ANVIL", "SIGN", "SIGN_POST", "WALL_SIGN", "HOPPER", "CHEST", "ENDER_CHEST", "TRAPPED_CHEST", "WORKBENCH", "ENCHANTMENT_TABLE", "BEACON", "ANVIL"), "teleport.misc", false);
// Normal teleporting
public static final List<PearlConfigSetting> pearlSettings = Arrays.asList(
new PearlConfigSetting(BlockAliases.SLABS, "teleport.slabs"),
new PearlConfigSetting(BlockAliases.STAIRS, "teleport.stairs"),
new PearlConfigSetting(BlockAliases.CHESTS, "teleport.chests"),
new PearlConfigSetting(BlockAliases.BEDS, "teleport.beds"),
new PearlConfigSetting(BlockAliases.COBBLE_WALLS, "teleport.cobblewalls"),
new PearlConfigSetting(BlockAliases.PISTONS, "teleport.pistons"),
new PearlConfigSetting(BlockAliases.END_FRAMES, "teleport.end-frames"),
new PearlConfigSetting(BlockAliases.ENCHANT_TABLES, "teleport.enchant-tables"),
new PearlConfigSetting(BlockAliases.ANVILS, "teleport.anvils"),
new PearlConfigSetting(BlockAliases.DAYLIGHT_SENSORS, "teleport.daylight-sensors"),
new PearlConfigSetting(BlockAliases.TRAPDOORS, "teleport.trapdoors")
);
public PearlConfig(Azurite instance) {
super(instance, "pearls", CC.getConfigHeader("HCF Enderpearl Configuration", "All the options for enderpearl mechanics"));
}
public List<ConfigSetting<?>> fetchPearlConfigs() {
List<ConfigSetting<?>> pearlConfigs = new ArrayList<>();
try {
for (PearlConfigSetting pearlSetting : pearlSettings) {
for (Field field : pearlSetting.getClass().getDeclaredFields()) {
if (field.getType() != ConfigSetting.class) continue;
ConfigSetting<?> configSetting = (ConfigSetting<?>) field.get(pearlSetting);
configSetting.setConfig(this);
configSetting.setName(field.getName());
pearlConfigs.add(configSetting);
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return pearlConfigs;
}
public static class PearlConfigSetting {
public BlockAliases aliases;
public String path;
public ConfigSetting<Boolean> enabled;
public ConfigSetting<Boolean> crosspearl;
public ConfigSetting<Boolean> diagonal;
public ConfigSetting<Boolean> critblock;
public PearlConfigSetting(BlockAliases aliases, String path) {
this.aliases = aliases;
this.path = path;
this.enabled = new ConfigSetting<>(true, path);
this.crosspearl = new ConfigSetting<>(true, path);
this.diagonal = new ConfigSetting<>(true, path);
this.critblock = new ConfigSetting<>(true, path);
}
}
public enum BlockAliases {
FENCES(Material.FENCE, Material.NETHER_FENCE, Material.IRON_FENCE, Material.SPRUCE_FENCE, Material.BIRCH_FENCE, Material.JUNGLE_FENCE, Material.DARK_OAK_FENCE, Material.ACACIA_FENCE),
FENCE_GATES(Material.FENCE_GATE, Material.JUNGLE_FENCE_GATE, Material.SPRUCE_FENCE_GATE, Material.DARK_OAK_FENCE_GATE, Material.ACACIA_FENCE_GATE, Material.BIRCH_FENCE_GATE),
CHESTS(Material.CHEST, Material.ENDER_CHEST, Material.TRAPPED_CHEST),
SLABS(Material.STEP, Material.STONE_SLAB2, Material.WOOD_STEP),
COBBLE_WALLS(Material.COBBLE_WALL),
ENCHANT_TABLES(Material.ENCHANTMENT_TABLE),
PISTONS(Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE),
STAIRS(Material.RED_SANDSTONE_STAIRS, Material.BRICK_STAIRS, Material.DARK_OAK_STAIRS, Material.ACACIA_STAIRS, Material.QUARTZ_STAIRS, Material.JUNGLE_WOOD_STAIRS, Material.BIRCH_WOOD_STAIRS, Material.SPRUCE_WOOD_STAIRS, Material.SANDSTONE_STAIRS, Material.NETHER_BRICK_STAIRS, Material.WOOD_STAIRS, Material.COBBLESTONE_STAIRS, Material.BRICK_STAIRS, Material.SMOOTH_STAIRS),
BEDS(Material.BED_BLOCK, Material.BED),
END_FRAMES(Material.ENDER_PORTAL_FRAME),
ANVILS(Material.ANVIL),
DAYLIGHT_SENSORS(Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED),
SIGNS(Material.WALL_SIGN, Material.SIGN_POST),
BANNERS(Material.STANDING_BANNER, Material.WALL_BANNER),
SAPLINGS(Material.SAPLING),
TRAPDOORS(Material.TRAP_DOOR, Material.IRON_TRAPDOOR),
PLATES(Material.STONE_PLATE, Material.WOOD_PLATE, Material.GOLD_PLATE, Material.IRON_PLATE),
DOORS(Material.WOOD_DOOR, Material.IRON_DOOR, Material.IRON_DOOR_BLOCK, Material.WOODEN_DOOR, Material.ACACIA_DOOR, Material.BIRCH_DOOR, Material.SPRUCE_DOOR, Material.JUNGLE_DOOR, Material.DARK_OAK_DOOR),
BUTTONS(Material.STONE_BUTTON, Material.WOOD_BUTTON);
private final List<Material> ids;
BlockAliases(Material... materials) {
this.ids = Arrays.asList(materials);
}
public boolean isApplicable(Material material) {
return ids.contains(material);
}
}
}
@@ -0,0 +1,180 @@
package dev.azurite.spigot.configs.extra;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.PearlConfig;
import dev.azurite.spigot.knockback.Knockback;
import net.minecraft.server.MinecraftServer;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class Config {
private final List<ConfigSetting<?>> configSettings;
private final File file;
private final YamlConfiguration bukkitConfig;
private final ConfigCommenter configCommenter;
public Config(Azurite azurite, String name, List<String> header) {
this.configSettings = new ArrayList<>();
this.file = new File(ConfigFolder.AZURITE_DIRECTORY, name + (name.endsWith(".yml") ? "" : ".yml"));
this.bukkitConfig = YamlConfiguration.loadConfiguration(file);
this.configCommenter = new ConfigCommenter();
configCommenter.setHeader(String.join("\n", header));
azurite.getConfigs().add(this);
}
public String getName() {
return file.getName();
}
public List<ConfigSetting<?>> getSettings() {
return configSettings;
}
public void delete() {
if (file.exists()) {
file.delete();
}
}
public void save(boolean async) {
if (async) {
Azurite.getInstance().getThreadingManager().getAsyncExecutor().execute(() -> this.save(false));
return;
}
try {
for (ConfigSetting<?> setting : getSettings()) {
bukkitConfig.set(setting.getFullPath(), setting.getValue());
}
bukkitConfig.save(file);
configCommenter.saveComments(file);
} catch (IOException e) {
MinecraftServer.LOGGER.error(e);
}
}
public void reload() {
try {
bukkitConfig.load(file); // Read the file again
for (ConfigSetting<?> configSetting : configSettings) {
Object fetch = fetchValue(configSetting); // Fetch from config and set
if (fetch == null) fetch = configSetting.getValue();
configSetting.set(fetch, false);
}
} catch (IOException | InvalidConfigurationException e) {
throw new RuntimeException(e);
}
}
private static List<Field> getAllConfigFields(Class<?> type) {
List<Field> fields = new ArrayList<>();
while (type != null && Config.class.isAssignableFrom(type)) {
for (Field field : type.getDeclaredFields()) {
fields.add(field);
}
type = type.getSuperclass();
}
return fields;
}
public void load() {
try {
List<ConfigSetting<?>> loading = new ArrayList<>();
for (Field field : getAllConfigFields(getClass())) {
if (field.getType() == ConfigSetting.class) {
ConfigSetting<?> configSetting = (ConfigSetting<?>) field.get(this);
configSetting.setConfig(this);
configSetting.setName(field.getName());
loading.add(configSetting);
// This will keep the order of knockback values
if (configSetting.getName().equals("knockbackType") && this instanceof Knockback) {
Knockback knockback = (Knockback) this;
loading.addAll(knockback.getKnockbackSettings());
}
}
}
if (this instanceof PearlConfig) {
PearlConfig pearlConfig = (PearlConfig) this;
loading.addAll(pearlConfig.fetchPearlConfigs());
}
for (ConfigSetting<?> configSetting : loading) {
String path = configSetting.getFullPath();
Object fetch = fetchValue(configSetting);
if (fetch == null) fetch = configSetting.getValue();
if (configSetting.getCommentAbove() != null) {
configCommenter.addComment(path, configSetting.getCommentAbove());
}
if (configSetting.getComment() != null) {
configCommenter.addCommentNextTo(path, configSetting.getComment());
}
configSetting.set(fetch, false);
configSettings.add(configSetting);
}
this.save(false);
} catch (Exception e) {
MinecraftServer.LOGGER.error(e);
}
}
private Object fetchValue(ConfigSetting<?> setting) {
Object defaultValue = setting.getValue();
String path = setting.getFullPath();
if (defaultValue instanceof String) {
return bukkitConfig.getString(path);
} else if (defaultValue instanceof List) {
return bukkitConfig.getList(path);
} else if (bukkitConfig.contains(path)) {
if (defaultValue instanceof Boolean) {
return bukkitConfig.getBoolean(path);
} else if (defaultValue instanceof Number) {
Number number = (Number) bukkitConfig.get(path);
if (defaultValue instanceof Integer) {
return number.intValue();
} else if (defaultValue instanceof Float) {
return number.floatValue();
} else if (defaultValue instanceof Double) {
return number.doubleValue();
}
}
}
return null;
}
}
@@ -0,0 +1,89 @@
package dev.azurite.spigot.configs.extra;
import dev.azurite.spigot.utils.JavaUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ConfigCommenter {
private final Map<String, String> comments = new HashMap<>();
private final Map<String, String> commentsNextTo = new HashMap<>();
private String header = null;
public void addCommentNextTo(String path, String comment) {
commentsNextTo.put(path, comment);
}
/**
* Add comment to a config option.<br>
* Supports multiline comments!
*
* @param path Config path to add comment to
* @param comment Comment to add
*/
public void addComment(String path, String comment) {
comments.put(path, comment);
}
/**
* Set the header for this config file
*
* @param header Header to add
*/
public void setHeader(String header) {
this.header = header;
}
/**
* Saves comments to config file
*
* @param file File to save to
* @throws IOException io
*/
public void saveComments(File file) throws IOException {
ArrayList<String> lines = (ArrayList<String>) Files.readAllLines(file.toPath());
lines.removeIf(s -> s.trim().startsWith("#") || s.trim().length() <= 4);
if (header != null && !header.isEmpty()) lines.add(0, "# " + header.replace("\n", "\n# ") + "\n");
for (Map.Entry<String, String> comment : comments.entrySet()) {
int line = JavaUtils.findKey(lines, comment.getKey());
if (line == -1) {
throw new IllegalStateException(String.format("You are trying to add a comment to key \"%s\" which does not exist!", comment.getKey()));
}
if (line >= 0) {
String prefix = JavaUtils.repeat(" ", JavaUtils.getIndentation(lines.get(line))) + "# ";
boolean noNewline = JavaUtils.getIndentation(lines.get(line)) > JavaUtils.getIndentation(lines.get(line - 1));
lines.add(line, (noNewline ? "" : "\n") + prefix + comment.getValue().replace("\n", "\n" + prefix));
} else {
System.out.printf("Failed to find key %s in %s!", comment.getKey(), file);
}
}
for (Map.Entry<String, String> comment : commentsNextTo.entrySet()) {
int line = JavaUtils.findKey(lines, comment.getKey());
if (line == -1) {
throw new IllegalStateException(String.format("You are trying to add a comment to key \"%s\" which does not exist!", comment.getKey()));
}
if (line >= 0) {
lines.set(line, lines.get(line) + " # " + comment.getValue());
} else {
System.out.printf("Failed to find key %s in %s!", comment.getKey(), file);
}
}
String text = String.join("\n", lines);
FileWriter fw = new FileWriter(file);
fw.write(text);
fw.close();
}
}
@@ -0,0 +1,27 @@
package dev.azurite.spigot.configs.extra;
import dev.azurite.spigot.framework.menu.Menu;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class ConfigEdit {
private final ConfigSetting<?> setting;
private final Menu menu;
public ConfigEdit(ConfigSetting<?> setting, Menu menu) {
this.setting = setting;
this.menu = menu;
}
public ConfigSetting<?> getSetting() {
return setting;
}
public Menu getMenu() {
return menu;
}
}
@@ -0,0 +1,26 @@
package dev.azurite.spigot.configs.extra;
import org.jetbrains.annotations.NotNull;
import java.io.File;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class ConfigFolder extends File {
public static final File AZURITE_DIRECTORY = new File("azurite");
static {
if (!AZURITE_DIRECTORY.exists()) {
AZURITE_DIRECTORY.mkdir();
}
}
public ConfigFolder(@NotNull String pathname) {
super(AZURITE_DIRECTORY, pathname);
if (!this.exists()) this.mkdir();
}
}
@@ -0,0 +1,156 @@
package dev.azurite.spigot.configs.extra;
import java.util.Objects;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
@SuppressWarnings("unchecked")
public class ConfigSetting<T> {
private T value;
private Config config;
private String name;
private String path;
private String comment;
private String commentAbove;
private boolean editable;
public ConfigSetting(T value, String path, String comment, String commentAbove, boolean editable) {
this.value = value;
this.config = null;
this.name = "";
this.path = path;
this.comment = comment;
this.commentAbove = commentAbove;
this.editable = editable;
}
public ConfigSetting(T value, String path, String comment, String commentAbove) {
this(value, path, comment, commentAbove, true);
}
public ConfigSetting(T value, String path, String comment) {
this(value, path, comment, null);
}
public ConfigSetting(T value, String path, String comment, boolean editable) {
this(value, path, comment, null, editable);
}
public ConfigSetting(T value, String path) {
this(value, path, null, null);
}
public ConfigSetting(T value, String path, boolean editable) {
this(value, path, null, null, editable);
}
public String getFullPath() {
return (!path.isEmpty() ? path + "." : "") + name;
}
public T getValue() {
return value;
}
public Object parseValue(String string) {
try {
if (value instanceof String) {
return string;
} else if (value instanceof Integer) {
return Integer.parseInt(string);
} else if (value instanceof Double) {
return Double.parseDouble(string);
} else if (value instanceof Float) {
return Float.parseFloat(string);
} else if (value instanceof Boolean) {
boolean isBool = string.equalsIgnoreCase("false") || string.equalsIgnoreCase("true");
if (isBool) return Boolean.parseBoolean(string);
}
} catch (Exception e) {
return null;
}
return null;
}
public void set(Object value, boolean save) {
this.set(value, save, true);
}
public void set(Object value, boolean save, boolean saveAsync) {
this.value = (T) value;
if (save) {
config.save(saveAsync);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getCommentAbove() {
return commentAbove;
}
public void setCommentAbove(String commentAbove) {
this.commentAbove = commentAbove;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setConfig(Config config) {
this.config = config;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
ConfigSetting<?> that = (ConfigSetting<?>) o;
return Objects.equals(value, that.value) && Objects.equals(config, that.config) && Objects.equals(name, that.name) && Objects.equals(path, that.path);
}
@Override
public int hashCode() {
int result = Objects.hashCode(value);
result = 31 * result + Objects.hashCode(config);
result = 31 * result + Objects.hashCode(name);
result = 31 * result + Objects.hashCode(path);
return result;
}
}
@@ -0,0 +1,39 @@
package dev.azurite.spigot.console;
import net.minecraft.server.DedicatedServer;
import net.minecrell.terminalconsole.SimpleTerminalConsole;
import org.bukkit.craftbukkit.command.ConsoleCommandCompleter;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
public final class AzuriteConsole extends SimpleTerminalConsole {
private final DedicatedServer server;
public AzuriteConsole(DedicatedServer server) {
this.server = server;
}
@Override
protected LineReader buildReader(LineReaderBuilder builder) {
return super.buildReader(builder
.appName("Azurite")
.completer(new ConsoleCommandCompleter(this.server))
);
}
@Override
protected boolean isRunning() {
return !this.server.isStopped() && this.server.isRunning();
}
@Override
protected void runCommand(String command) {
this.server.issueCommand(command, this.server);
}
@Override
protected void shutdown() {
this.server.safeShutdown();
}
}
@@ -0,0 +1,13 @@
package dev.azurite.spigot.console;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.async.AsyncQueueFullPolicy;
import org.apache.logging.log4j.core.async.EventRoute;
public final class LogFullPolicy implements AsyncQueueFullPolicy {
@Override
public EventRoute getRoute(final long backgroundThreadId, final Level level) {
return EventRoute.ENQUEUE;
}
}
@@ -0,0 +1,16 @@
package dev.azurite.spigot.console;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.craftbukkit.command.CraftConsoleCommandSender;
public class TerminalConsoleCommandSender extends CraftConsoleCommandSender {
private static final Logger LOGGER = LogManager.getRootLogger();
@Override
public void sendRawMessage(String message) {
// TerminalConsoleAppender supports color codes directly in log messages
LOGGER.info(message);
}
}
@@ -0,0 +1,122 @@
package dev.azurite.spigot.framework.commands;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.utils.CC;
import dev.azurite.spigot.utils.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.BukkitCommand;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public abstract class Command {
protected final String name;
protected String permission;
protected List<String> aliases;
protected BukkitCommand bukkitCommand;
public Command(String name) {
this.name = name;
this.permission = null;
this.aliases = new ArrayList<>();
}
public abstract void execute(CommandSender sender, String[] args);
public List<String> tabComplete(CommandSender sender, String[] args) {
return Collections.emptyList();
}
public BukkitCommand asBukkitCommand() {
if (bukkitCommand != null) {
return bukkitCommand;
}
BukkitCommand command = new BukkitCommand(name) {
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (permission != null && !sender.hasPermission(permission)) {
sendMessage(sender, LanguageConfig.insufficientPerm.getValue());
return true;
}
Command.this.execute(sender, args);
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
if (permission != null && !sender.hasPermission(permission)) {
return super.tabComplete(sender, alias, args);
}
List<String> tabComplete = Command.this.tabComplete(sender, args);
return (tabComplete.isEmpty() ? super.tabComplete(sender, alias, args) : tabComplete);
}
};
if (!aliases.isEmpty()) {
command.setAliases(aliases);
}
this.bukkitCommand = command;
return command;
}
public void unregister() {
if (bukkitCommand != null) {
Utils.unregister(bukkitCommand);
}
}
public void sendMessage(CommandSender sender, String... strings) {
for (String string : strings) {
sender.sendMessage(CC.t(string));
}
}
public void setPermission(String permission) {
this.permission = permission;
}
public void setAliases(List<String> aliases) {
this.aliases = aliases;
}
public Integer getInt(String string) {
try {
return Integer.parseInt(string);
} catch (NumberFormatException e) {
return null;
}
}
public Double getDouble(String string) {
try {
return Double.parseDouble(string);
} catch (NumberFormatException e) {
return null;
}
}
public Float getFloat(String string) {
try {
return Float.parseFloat(string);
} catch (NumberFormatException e) {
return null;
}
}
}
@@ -0,0 +1,131 @@
package dev.azurite.spigot.framework.menu;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.framework.menu.button.Button;
import dev.azurite.spigot.utils.CC;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.Map;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public abstract class Menu {
protected Map<Integer, Button> buttons;
protected Player player;
protected Inventory inventory;
protected String title;
protected int size;
protected boolean update;
protected ItemStack filler;
protected boolean fillEnabled;
protected boolean allowInteract;
public Menu(Player player, String title, int size, boolean update) {
this.player = player;
this.title = CC.t(title);
this.size = size;
this.inventory = Bukkit.createInventory(null, size, this.title);
this.update = update;
this.fillEnabled = false;
this.allowInteract = false;
}
public Map<Integer, Button> getButtons() {
return buttons;
}
public void playClick() {
player.playSound(Sound.CLICK, 1.0F, 1.0F);
}
public void open() {
this.buttons = getButtons(player);
// Set the first items
for (Map.Entry<Integer, Button> entry : buttons.entrySet()) {
inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack());
}
// Fill null/air spots with our filler
if (fillEnabled) {
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack item = inventory.getItem(i);
if (item == null || item.getType() == Material.AIR) {
inventory.setItem(i, filler);
}
}
}
// Open and add to map
player.openInventory(inventory);
Azurite.getInstance().getMenuManager().getMenus().put(player.getUniqueId(), this);
}
public void update() {
if (!player.isOnline()) {
destroy(); // They aren't online so just destroy it.
return;
}
// "Re-Fetch" the buttons and cache them again
Map<Integer, Button> buttons = (this.buttons = getButtons(player));
// Update the items in our inventory
for (Map.Entry<Integer, Button> entry : buttons.entrySet()) {
inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack());
}
// Update filler
if (fillEnabled) {
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack item = inventory.getItem(i);
if (item == null || item.getType() == Material.AIR) {
inventory.setItem(i, filler);
}
}
}
}
public void destroy() {
// Lower ram usage
buttons.clear();
inventory.clear();
// Remove from map
Azurite.getInstance().getMenuManager().getMenus().remove(player.getUniqueId());
// Cancel updater
update = false;
}
public void onClick(InventoryClickEvent e) {
if (!allowInteract) {
e.setCancelled(true);
}
}
public void onClickOwn(InventoryClickEvent e) {
}
public void onClose() {
}
public boolean isAllowInteract() {
return allowInteract;
}
public abstract Map<Integer, Button> getButtons(Player player);
}
@@ -0,0 +1,39 @@
package dev.azurite.spigot.framework.menu;
import net.minecraft.server.MinecraftServer;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class MenuManager {
private final Map<UUID, Menu> menus;
public MenuManager() {
this.menus = new HashMap<>();
}
public Map<UUID, Menu> getMenus() {
return menus;
}
public void tick() {
if (menus.isEmpty()) return;
try {
if (MinecraftServer.currentTick % 500 == 0) {
for (Menu menu : menus.values()) {
if (menu.update) menu.update();
}
}
} catch (Exception e) {
MinecraftServer.LOGGER.info("Error updating azurite menus {}", e.getMessage());
}
}
}
@@ -0,0 +1,17 @@
package dev.azurite.spigot.framework.menu.button;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public abstract class Button {
public abstract void onClick(InventoryClickEvent e);
public abstract ItemStack getItemStack();
}
@@ -0,0 +1,290 @@
package dev.azurite.spigot.framework.menu.paginated;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.AzuriteConfig;
import dev.azurite.spigot.framework.menu.Menu;
import dev.azurite.spigot.framework.menu.button.Button;
import dev.azurite.spigot.utils.ItemBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class PaginatedMenu extends Menu {
protected Map<Integer, Map<Integer, Button>> pages;
protected Map<Integer, Button> defaultButtons;
protected Menu previousMenu;
protected int currentPage;
protected boolean surroundGlass;
public PaginatedMenu(Player player, String title, int size, boolean update) {
super(player, title, size, update);
this.surroundGlass = false;
this.pages = new HashMap<>();
this.defaultButtons = getDefaultButtons();
this.previousMenu = null;
this.currentPage = 1;
}
public PaginatedMenu(Player player, String title, int size, boolean update, boolean surroundGlass) {
super(player, title, size, update);
this.surroundGlass = surroundGlass;
this.pages = new HashMap<>();
this.defaultButtons = getDefaultButtons();
this.previousMenu = null;
this.currentPage = 1;
}
public PaginatedMenu(Player player, String title, Menu previousMenu, int size, boolean update, boolean surroundGlass) {
super(player, title, size, update);
this.pages = new HashMap<>();
this.previousMenu = previousMenu;
this.surroundGlass = surroundGlass;
this.defaultButtons = getDefaultButtons();
this.currentPage = 1;
}
@Override
public void open() {
// Calculate pages based on current buttons
this.calcPages(getButtons(player));
this.buttons = pages.get(currentPage);
this.inventory = Bukkit.createInventory(null, size, title);
for (Map.Entry<Integer, Button> entry : buttons.entrySet()) {
inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack());
}
// Open and add to map
player.openInventory(inventory);
Azurite.getInstance().getMenuManager().getMenus().put(player.getUniqueId(), this);
}
@Override
public void update() {
if (!player.isOnline()) {
destroy(); // They aren't online so just destroy it.
return;
}
// Clear
inventory.clear();
pages.clear();
// "Re-Fetch" the buttons and cache them again
this.calcPages(getButtons(player));
this.buttons = pages.get(currentPage);
// Update the items in our inventory
for (Map.Entry<Integer, Button> entry : buttons.entrySet()) {
inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack());
}
}
@Override
public void destroy() {
super.destroy();
pages.clear();
}
@Override
public Map<Integer, Button> getButtons(Player player) {
return null;
}
private void calcPages(Map<Integer, Button> buttons) {
if (buttons.isEmpty()) {
pages.computeIfAbsent(1, k -> new HashMap<>(defaultButtons));
return;
}
this.handleButtons(buttons);
}
private void handleButtons(Map<Integer, Button> buttons) {
Set<Integer> exceptions = new HashSet<>();
for (int i = 1; i <= 9; i++) {
exceptions.add(i); // First row
}
// Handle left / right
if (surroundGlass) {
for (int i = 10; i <= size; i++) {
if (i % 9 == 0 || (i - 1) % 9 == 0) exceptions.add(i);
}
}
int counter = 9;
int page = 1;
int bottomSize = surroundGlass ? size - 9 : size;
int maxPerPage = size - (exceptions.size() + (surroundGlass ? 9 : 0));
int totalPages = (buttons.size() < maxPerPage ? 1 : buttons.size() / maxPerPage);
for (int i = 1; i <= size * totalPages; i++) {
Button button = buttons.get(i);
if (button != null) {
if (counter >= bottomSize) {
counter = 9;
page++;
}
while (exceptions.contains(counter)) {
counter++;
if (counter >= bottomSize) {
counter = 9;
page++;
}
}
Map<Integer, Button> pageButtons = pages.computeIfAbsent(page, k -> new HashMap<>(defaultButtons));
pageButtons.put(counter++, button);
}
}
}
private Map<Integer, Button> getDefaultButtons() {
Map<Integer, Button> map = new HashMap<>();
if (AzuriteConfig.fillerEnabled.getValue()) {
for (int i = 2; i <= 8; i++) {
map.put(i, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.valueOf(AzuriteConfig.fillerType.getValue()))
.setName("&7")
.data(AzuriteConfig.fillerData.getValue())
.toItemStack();
}
});
}
if (surroundGlass) {
Button button = new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.valueOf(AzuriteConfig.fillerType.getValue()))
.setName("&7")
.data(AzuriteConfig.fillerData.getValue())
.toItemStack();
}
};
for (int i = 9; i <= size; i++) {
if (i >= (size - 9)) {
map.put(i, button);
continue;
}
if (i % 9 == 0) {
map.put(i, button);
map.put(i + 1, button);
}
}
}
}
map.put(1, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
// At first page no going back
if (currentPage > 1) {
currentPage--;
playClick();
update();
}
}
@Override
public ItemStack getItemStack() {
UnaryOperator<String> replacer = s -> s
.replace("%page%", String.valueOf(currentPage))
.replace("%max-pages%", String.valueOf(pages.size()))
.replace("%back-page%", (currentPage == 1 ? "None" : String.valueOf(currentPage - 1)));
return new ItemBuilder(Material.valueOf(AzuriteConfig.pageType.getValue()))
.setName(AzuriteConfig.pageBackDisplay.getValue())
.setLore(AzuriteConfig.pageBackLore.getValue().stream().map(replacer).collect(Collectors.toList()))
.data(AzuriteConfig.pageData.getValue())
.toItemStack();
}
});
if (previousMenu != null) {
map.put((surroundGlass ? size - 4 : 5), new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
playClick();
previousMenu.open();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.valueOf(AzuriteConfig.backButtonType.getValue()))
.setName(AzuriteConfig.backButtonDisplay.getValue())
.data(AzuriteConfig.backButtonData.getValue())
.toItemStack();
}
});
}
map.put(9, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
// Check if the next page exists
if (pages.containsKey(currentPage + 1)) {
currentPage++;
playClick();
update();
}
}
@Override
public ItemStack getItemStack() {
UnaryOperator<String> replacer = s -> s
.replace("%page%", String.valueOf(currentPage))
.replace("%max-pages%", String.valueOf(pages.size()))
.replace("%next-page%", (pages.size() == currentPage ? "None" : String.valueOf(currentPage + 1)));
return new ItemBuilder(Material.valueOf(AzuriteConfig.pageType.getValue()))
.setName(AzuriteConfig.pageForwardDisplay.getValue())
.setLore(AzuriteConfig.pageForwardLore.getValue().stream().map(replacer).collect(Collectors.toList()))
.data(AzuriteConfig.pageData.getValue())
.toItemStack();
}
});
return map;
}
}
@@ -0,0 +1,140 @@
package dev.azurite.spigot.framework.plugin;
import com.avaje.ebean.EbeanServer;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import java.io.File;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class AzuriteFakePlugin implements Plugin {
private final PluginDescriptionFile description;
private final AzuriteFakePluginLoader fakePluginLoader;
public AzuriteFakePlugin() {
this.description = new PluginDescriptionFile("AzuriteSpigotFakePlugin", "1.0", "");
this.fakePluginLoader = new AzuriteFakePluginLoader();
}
@Override
public File getDataFolder() {
return null;
}
@Override
public PluginDescriptionFile getDescription() {
return description;
}
@Override
public FileConfiguration getConfig() {
return null;
}
@Override
public InputStream getResource(String filename) {
return null;
}
@Override
public void saveConfig() {
}
@Override
public void saveDefaultConfig() {
}
@Override
public void saveResource(String resourcePath, boolean replace) {
}
@Override
public void reloadConfig() {
}
@Override
public PluginLoader getPluginLoader() {
return fakePluginLoader;
}
@Override
public Server getServer() {
return null;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public void onDisable() {
}
@Override
public void onLoad() {
}
@Override
public void onEnable() {
}
@Override
public boolean isNaggable() {
return false;
}
@Override
public void setNaggable(boolean canNag) {
}
@Override
public EbeanServer getDatabase() {
return null;
}
@Override
public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
return null;
}
@Override
public Logger getLogger() {
return null;
}
@Override
public String getName() {
return "";
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return Collections.emptyList();
}
}
@@ -0,0 +1,112 @@
package dev.azurite.spigot.framework.plugin;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.Warning;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.*;
import java.io.File;
import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Level;
import java.util.regex.Pattern;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class AzuriteFakePluginLoader implements PluginLoader {
@Override
public Plugin loadPlugin(File file) throws InvalidPluginException, UnknownDependencyException {
return null;
}
@Override
public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException {
return null;
}
@Override
public Pattern[] getPluginFileFilters() {
return new Pattern[0];
}
public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(Listener listener, final Plugin plugin) {
Validate.notNull(plugin, "Plugin can not be null");
Validate.notNull(listener, "Listener can not be null");
Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<>();
Set<Method> methods;
try {
Method[] publicMethods = listener.getClass().getMethods();
Method[] privateMethods = listener.getClass().getDeclaredMethods();
methods = new HashSet<>(publicMethods.length + privateMethods.length, 1.0f);
methods.addAll(Arrays.asList(publicMethods));
methods.addAll(Arrays.asList(privateMethods));
} catch (NoClassDefFoundError e) {
plugin.getLogger().severe("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist.");
return ret;
}
for (final Method method : methods) {
final EventHandler eh = method.getAnnotation(EventHandler.class);
if (eh == null) continue;
// Do not register bridge or synthetic methods to avoid event duplication
// Fixes SPIGOT-893
if (method.isBridge() || method.isSynthetic()) {
continue;
}
final Class<?> checkClass;
if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
plugin.getLogger().severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass());
continue;
}
final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
method.setAccessible(true);
Set<RegisteredListener> eventSet = ret.computeIfAbsent(eventClass, k -> new HashSet<>());
for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
// This loop checks for extending deprecated events
if (clazz.getAnnotation(Deprecated.class) != null) {
Warning warning = clazz.getAnnotation(Warning.class);
Warning.WarningState warningState = Bukkit.getServer().getWarningState();
if (!warningState.printFor(warning)) {
break;
}
plugin.getLogger().log(
Level.WARNING,
String.format(
"\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated." +
" \"%s\"; please notify the authors %s.",
plugin.getDescription().getFullName(),
clazz.getName(),
method.toGenericString(),
(warning != null && !warning.reason().isEmpty()) ? warning.reason() : "Server performance will be affected",
Arrays.toString(plugin.getDescription().getAuthors().toArray())),
warningState == Warning.WarningState.ON ? new AuthorNagException(null) : null);
break;
}
}
// Azurite start - ASM events backport
eventSet.add(new RegisteredListener(listener, EventExecutor.create(method, eventClass), eh.priority(), plugin, eh.ignoreCancelled()));
// Azurite end
}
return ret;
}
@Override
public void enablePlugin(Plugin plugin) {
}
@Override
public void disablePlugin(Plugin plugin) {
}
}
@@ -0,0 +1,87 @@
package dev.azurite.spigot.generator;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.utils.CC;
import java.io.File;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class Generator extends Config {
private final String name;
public final ConfigSetting<Boolean> generateOceans = new ConfigSetting<>(true, "world", "Generate any oceans");
public final ConfigSetting<Boolean> generateWaterLakes = new ConfigSetting<>(true, "world", "Generate any water lakes");
public final ConfigSetting<Boolean> generateLavaLakes = new ConfigSetting<>(true, "world", "Generate any lava lakes");
public final ConfigSetting<Boolean> flatBedrock = new ConfigSetting<>(false, "world", "Should worlds be generated with flat bedrock");
public final ConfigSetting<Double> cavesMultiplier = new ConfigSetting<>(1.0, "world", "Multiply the amount of cave generation");
public final ConfigSetting<Double> sugarCaneMultiplier = new ConfigSetting<>(1.0, "world", "Multiply the amount of cane generation");
public final ConfigSetting<Boolean> biomePlains = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeDesert = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeDesertHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeExtremeHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeExtremeHillsPlus = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeForest = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeForestHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeTaiga = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeTaigaHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeSwampland = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeIcePlains = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeIceMountains = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeMushroomIsland = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeJungle = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeJungleHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeBirchForest = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeBirchForestHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeRoofedForest = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeColdTaiga = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeColdTaigaHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeMegaTaiga = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeMegaTaigaHills = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeSavanna = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeSavannaPlateau = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeMesa = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeMesaPlateauF = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Boolean> biomeMesaPlateau = new ConfigSetting<>(true, "world.biomes");
public final ConfigSetting<Integer> spawnBiomeRadius = new ConfigSetting<>(0, "world.spawn", "Radius of spawn biome (0, 0 coords)");
public final ConfigSetting<String> spawnBiome = new ConfigSetting<>("Plains", "world.spawn", "Use custom biome to spawn within a certain radius", false);
public final ConfigSetting<Boolean> spawnBiomeRivers = new ConfigSetting<>(true, "world.spawn", "Generate rivers in spawn biome");
public final ConfigSetting<Boolean> spawnBiomeLakes = new ConfigSetting<>(true, "world.spawn", "Generate lakes in spawn biome");
public final ConfigSetting<Double> emeraldMultiplier = new ConfigSetting<>(1.0, "ores.emerald", "Multiply the amount of emerald generation");
public final ConfigSetting<Double> coalMultiplier = new ConfigSetting<>(1.0, "ores.coal", "Multiply the amount of coal generation");
public final ConfigSetting<Integer> coalSize = new ConfigSetting<>(17, "ores.coal", "Maximum amount of coal can be generated in 1 chunk");
public final ConfigSetting<Boolean> coalMustTouchAir = new ConfigSetting<>(false, "ores.coal", "Generate coal only in caves");
public final ConfigSetting<Double> ironMultiplier = new ConfigSetting<>(1.0, "ores.iron", "Multiply the amount of iron generation");
public final ConfigSetting<Integer> ironSize = new ConfigSetting<>(9, "ores.iron", "Maximum amount of iron can be generated in 1 chunk");
public final ConfigSetting<Boolean> ironMustTouchAir = new ConfigSetting<>(false, "ores.iron", "Generate iron only in caves");
public final ConfigSetting<Double> goldMultiplier = new ConfigSetting<>(1.0, "ores.gold", "Multiply the amount of gold generation");
public final ConfigSetting<Integer> goldSize = new ConfigSetting<>(9, "ores.gold", "Maximum amount of gold can be generated in 1 chunk");
public final ConfigSetting<Boolean> goldMustTouchAir = new ConfigSetting<>(false, "ores.gold", "Generate gold only in caves");
public final ConfigSetting<Double> redstoneMultiplier = new ConfigSetting<>(1.0, "ores.redstone", "Multiply the amount of redstone generation");
public final ConfigSetting<Integer> redstoneSize = new ConfigSetting<>(8, "ores.redstone", "Maximum amount of redstone can be generated in 1 chunk");
public final ConfigSetting<Boolean> redstoneMustTouchAir = new ConfigSetting<>(false, "ores.redstone", "Generate redstone only in caves");
public final ConfigSetting<Double> diamondMultiplier = new ConfigSetting<>(1.0, "ores.diamond", "Multiply the amount of diamond generation");
public final ConfigSetting<Integer> diamondSize = new ConfigSetting<>(8, "ores.diamond", "Maximum amount of diamonds can be generated in 1 chunk");
public final ConfigSetting<Boolean> diamondMustTouchAir = new ConfigSetting<>(false, "ores.diamond", "Generate diamonds only in caves");
public final ConfigSetting<Double> lapisMultiplier = new ConfigSetting<>(1.0, "ores.lapis", "Multiply the amount of lapis generation");
public final ConfigSetting<Integer> lapisSize = new ConfigSetting<>(7, "ores.lapis", "Maximum amount of lapis can be generated in 1 chunk");
public final ConfigSetting<Boolean> lapisMustTouchAir = new ConfigSetting<>(false, "ores.lapis", "Generate lapis only in caves");
public Generator(Azurite azurite, String name, File file) {
super(azurite, file.getName() + File.separator + name, CC.getConfigHeader(name + " (Generator)"));
this.name = name.replace(".yml", "");
}
public String getName() {
return name;
}
}
@@ -0,0 +1,70 @@
package dev.azurite.spigot.generator;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.extra.ConfigFolder;
import java.io.File;
import java.util.Map;
import java.util.TreeMap;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class GeneratorManager {
private final Map<String, Generator> generators;
private final ConfigFolder parentFile;
private Generator defaultConfig;
public GeneratorManager() {
this.generators = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
this.parentFile = new ConfigFolder("generator");
this.load();
}
private void load() {
File[] files = parentFile.listFiles();
if (files != null) {
for (File file : files) {
this.createGenerator(file.getName());
}
}
this.defaultConfig = this.getOrCreate("Default");
}
public void save(boolean async) {
for (Generator generator : generators.values()) {
generator.save(async);
}
}
private Generator createGenerator(String name) {
Generator generator = new Generator(Azurite.getInstance(), name, parentFile);
generator.load();
generator.save(false);
generators.put(generator.getName(), generator);
return generator;
}
public Generator getOrCreate(String name) {
Generator generator = generators.get(name);
if (generator == null) {
generator = createGenerator(name);
}
return generator;
}
public Generator getDefaultConfig() {
return defaultConfig;
}
public Map<String, Generator> getGenerators() {
return generators;
}
}
@@ -0,0 +1,40 @@
package dev.azurite.spigot.generator.layer;
import net.minecraft.server.GenLayer;
import net.minecraft.server.IntCache;
import net.minecraft.server.World;
public class GenLayerSpawnBiome extends GenLayer {
private final GenLayer parent;
private final int biomeSize;
private final World world;
public GenLayerSpawnBiome(GenLayer parent, int biomeSize, World world) {
super(1);
this.parent = parent;
this.biomeSize = biomeSize;
this.world = world;
}
@Override
public int[] a(int x, int z, int w, int h) {
int radiusSqrd = world.generatorConfig.spawnBiomeRadius.getValue() * world.generatorConfig.spawnBiomeRadius.getValue();
int[] in = parent.a(x, z, w, h);
int[] out = IntCache.a(w * h);
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
int index = j * w + i;
int worldX = (x + i) << 2 << biomeSize;
int worldZ = (z + j) << 2 << biomeSize;
if (worldX * worldX + worldZ * worldZ < radiusSqrd) {
out[index] = world.spawnBiome.id;
} else {
out[index] = in[index];
}
}
}
return out;
}
}
@@ -0,0 +1,51 @@
package dev.azurite.spigot.generator.layer;
import net.minecraft.server.BiomeBase;
import net.minecraft.server.GenLayer;
import net.minecraft.server.IntCache;
import net.minecraft.server.World;
public class GenLayerSpawnRiver extends GenLayer {
private final World world;
public GenLayerSpawnRiver(long var1, GenLayer var3, World world) {
super(var1);
super.a = var3;
this.world = world;
}
public int[] a(int var1, int var2, int var3, int var4) {
int radiusSqrd = world.generatorConfig.spawnBiomeRadius.getValue() * world.generatorConfig.spawnBiomeRadius.getValue();
int var5 = var1 - 1;
int var6 = var2 - 1;
int var7 = var3 + 2;
int var8 = var4 + 2;
int[] var9 = this.a.a(var5, var6, var7, var8);
int[] var10 = IntCache.a(var3 * var4);
for(int var11 = 0; var11 < var4; ++var11) {
for(int var12 = 0; var12 < var3; ++var12) {
int var13 = this.c(var9[var12 + (var11 + 1) * var7]);
int var14 = this.c(var9[var12 + 2 + (var11 + 1) * var7]);
int var15 = this.c(var9[var12 + 1 + (var11) * var7]);
int var16 = this.c(var9[var12 + 1 + (var11 + 2) * var7]);
int var17 = this.c(var9[var12 + 1 + (var11 + 1) * var7]);
int worldX = (var1 + var11) << 2;
int worldZ = (var2 + var12) << 2;
if ((var17 == var13 && var17 == var15 && var17 == var14 && var17 == var16) || (worldX * worldX + worldZ * worldZ < radiusSqrd)) {
var10[var12 + var11 * var3] = -1;
} else {
var10[var12 + var11 * var3] = BiomeBase.RIVER.id;
}
}
}
return var10;
}
private int c(int var1) {
return var1 >= 2 ? 2 + (var1 & 1) : var1;
}
}
@@ -0,0 +1,362 @@
package dev.azurite.spigot.knockback;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.api.knockback.IKnockback;
import dev.azurite.spigot.api.knockback.types.IAdvancedKnockback;
import dev.azurite.spigot.api.knockback.types.IConstantKnockback;
import dev.azurite.spigot.api.knockback.types.ISimpleKnockback;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.knockback.extra.KnockbackParent;
import dev.azurite.spigot.knockback.types.AdvancedKnockback;
import dev.azurite.spigot.knockback.types.ConstantKnockback;
import dev.azurite.spigot.knockback.types.SimpleKnockback;
import dev.azurite.spigot.utils.CC;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class Knockback extends Config implements IKnockback {
public final String name;
// Knockback Types
public List<KnockbackParent> knockbackTypes;
public SimpleKnockback simpleKnockback; // We save both simple and advanced in case the user switches between them
public AdvancedKnockback advancedKnockback;
public ConstantKnockback constantKnockback;
// Knockback Config
public final ConfigSetting<String> knockbackType = new ConfigSetting<>("SIMPLE", "type", "");
// Rod
public final ConfigSetting<Double> rodHorizontal = new ConfigSetting<>(1.1, "", "Horizontal fishing rod knockback");
public final ConfigSetting<Double> rodVertical = new ConfigSetting<>(1.0, "", "Vertical fishing rod knockback");
public final ConfigSetting<Double> rodSpeed = new ConfigSetting<>(1.0, "", "Multiplies the number given with the rod's vector magnitude");
// Bow
public final ConfigSetting<Boolean> bowBoostDirectional = new ConfigSetting<>(false, "", "Should bow boosting be enabled using the direction player is facing");
public final ConfigSetting<Boolean> bowBoostKbOnlyShooter = new ConfigSetting<>(false, "", "Should bow boosting direction only be enabled for shooter");
public final ConfigSetting<Double> bowHorizontal = new ConfigSetting<>(0.9, "", "Horizontal bow knockback");
public final ConfigSetting<Double> bowVertical = new ConfigSetting<>(0.9, "", "Vertical bow knockback");
public final ConfigSetting<Double> bowBoostHorizontal = new ConfigSetting<>(1.1, "", "Horizontal bow boost knockback");
public final ConfigSetting<Double> bowBoostVertical = new ConfigSetting<>(0.35, "", "Horizontal bow boost knockback");
public final ConfigSetting<Double> bowPunchMultiplier = new ConfigSetting<>(1.1, "", "Punch enchantment modifier: horizontal *= (punchLevel + 1) * bowPunchMultiplier");
// Potions
public final ConfigSetting<Float> potionFall = new ConfigSetting<>(0.05F, "", "Fall speed value");
public final ConfigSetting<Float> potionSpeed = new ConfigSetting<>(0.5F, "", "Throwing multiplier value");
public final ConfigSetting<Float> potionVerticalOffset = new ConfigSetting<>(-20.0F, "", "Vertical throwing angle offset value");
public final ConfigSetting<Double> potionYOffset = new ConfigSetting<>(0.0D, "", "Y offset value");
public final ConfigSetting<Boolean> potionFast = new ConfigSetting<>(true, "", "Make heal potions throwing smoother");
public final ConfigSetting<Boolean> potionBetterVisual = new ConfigSetting<>(true, "", "Make heal potions splash visually better when it hits the entity");
// Misc
public final ConfigSetting<Integer> cpsCapOverride = new ConfigSetting<>(-1, "", "Should the default CPS Cap be overridden (use -1 to disable)");
public final ConfigSetting<Integer> hitDelay = new ConfigSetting<>(20, "", "Delay between victim can get hit");
public final ConfigSetting<Integer> hitDelayArrow = new ConfigSetting<>(20, "", "Delay between victim can get hit by an arrow (Patches arrow bounce bug)");
// Combo
public final ConfigSetting<Boolean> comboMode = new ConfigSetting<>(false, "", "Enable combo mode");
public final ConfigSetting<Double> comboHeight = new ConfigSetting<>(2.3, "", "Maximum height of combo");
public final ConfigSetting<Integer> comboTicks = new ConfigSetting<>(10, "", "Maximum combo ticks");
public final ConfigSetting<Double> comboVelocity = new ConfigSetting<>(-0.05, "", "Vertical deduction on hit");
public Knockback(Azurite instance, String name, File parent) {
super(instance, parent.getName() + File.separator + name, CC.getConfigHeader(name + " (Knockback)"));
this.name = name.replace(".yml", "");
this.knockbackTypes = new ArrayList<>();
this.simpleKnockback = new SimpleKnockback(this);
this.advancedKnockback = new AdvancedKnockback(this);
this.constantKnockback = new ConstantKnockback(this);
}
public List<ConfigSetting<?>> getKnockbackSettings() {
List<ConfigSetting<?>> knockbackSettings = new ArrayList<>();
try {
for (KnockbackParent parent : knockbackTypes) {
for (Field field : parent.getClass().getDeclaredFields()) {
if (field.getType() != ConfigSetting.class) continue;
ConfigSetting<?> configSetting = (ConfigSetting<?>) field.get(parent);
configSetting.setConfig(this);
configSetting.setName(field.getName());
configSetting.setPath(parent.getType().getPath());
knockbackSettings.add(configSetting);
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return knockbackSettings;
}
public KnockbackType getKnockbackType() {
return KnockbackType.valueOf(knockbackType.getValue());
}
public ConfigSetting<?> getActiveSetting(String name) {
for (ConfigSetting<?> activeSetting : getActiveSettings()) {
if (activeSetting.getName().equalsIgnoreCase(name)) {
return activeSetting;
}
}
return null;
}
public List<ConfigSetting<?>> getActiveSettings() {
return getSettings().stream().filter(setting -> getKnockbackType().isApplicable(setting)).collect(Collectors.toList());
}
@Override
public String getName() {
return name;
}
@Override
public String getType() {
return getKnockbackType().getDisplayName();
}
@Override
public IAdvancedKnockback getAdvancedKnockback() {
return advancedKnockback;
}
@Override
public ISimpleKnockback getSimpleKnockback() {
return simpleKnockback;
}
@Override
public IConstantKnockback getConstantKnockback() {
return constantKnockback;
}
@Override
public boolean isActive() {
return Azurite.getInstance().getKnockbackManager().getActiveProfile().getName().equals(name);
}
@Override
public double getRodHorizontal() {
return rodHorizontal.getValue();
}
@Override
public void setRodHorizontal(double amount) {
rodHorizontal.set(amount, true);
}
@Override
public double getRodVertical() {
return rodVertical.getValue();
}
@Override
public void setRodVertical(double amount) {
rodVertical.set(amount, true);
}
@Override
public double getRodSpeed() {
return rodSpeed.getValue();
}
@Override
public void setRodSpeed(double amount) {
rodSpeed.set(amount, true);
}
@Override
public boolean getBowBoostDirectional() {
return bowBoostDirectional.getValue();
}
@Override
public void setBowBoostDirectional(boolean value) {
bowBoostDirectional.set(value, true);
}
@Override
public boolean isBowBoostOnlyShooter() {
return bowBoostKbOnlyShooter.getValue();
}
@Override
public void setBowBoostOnlyShooter(boolean value) {
bowBoostKbOnlyShooter.set(value, true);
}
@Override
public double getBowHorizontal() {
return bowHorizontal.getValue();
}
@Override
public void setBowHorizontal(double amount) {
bowHorizontal.set(amount, true);
}
@Override
public double getBowVertical() {
return bowVertical.getValue();
}
@Override
public void setBowVertical(double amount) {
bowVertical.set(amount, true);
}
@Override
public double getBowPunchMultiplier() {
return bowPunchMultiplier.getValue();
}
@Override
public void setBowPunchMultiplier(double amount) {
bowPunchMultiplier.set(amount, true);
}
@Override
public float getPotionFall() {
return potionFall.getValue();
}
@Override
public void setPotionFall(float amount) {
potionFall.set(amount, true);
}
@Override
public float getPotionSpeed() {
return potionSpeed.getValue();
}
@Override
public void setPotionSpeed(float amount) {
potionSpeed.set(amount, true);
}
@Override
public float getPotionOffset() {
return potionVerticalOffset.getValue();
}
@Override
public void setPotionOffset(float amount) {
potionVerticalOffset.set(amount, true);
}
@Override
public double getPotionYOffset() {
return potionYOffset.getValue();
}
@Override
public void setPotionYOffset(double amount) {
potionYOffset.set(amount, true);
}
@Override
public boolean isPotionFast() {
return potionFast.getValue();
}
@Override
public void setPotionFast(boolean value) {
potionFast.set(value, true);
}
@Override
public int getCpsCapOverride() {
return cpsCapOverride.getValue();
}
@Override
public void setCpsCapOverride(int cps) {
cpsCapOverride.set(cps, true);
}
@Override
public int getHitDelay() {
return hitDelay.getValue();
}
@Override
public void setHitDelay(int amount) {
hitDelay.set(amount, true);
}
@Override
public int getHitDelayArrow() {
return hitDelayArrow.getValue();
}
@Override
public void setHitDelayArrow(int amount) {
hitDelayArrow.set(amount, true);
}
@Override
public boolean isComboMode() {
return comboMode.getValue();
}
@Override
public void setComboMode(boolean value) {
comboMode.set(value, true);
}
@Override
public double getComboHeight() {
return comboHeight.getValue();
}
@Override
public void setComboHeight(double amount) {
comboHeight.set(amount, true);
}
@Override
public int getComboTicks() {
return comboTicks.getValue();
}
@Override
public void setComboTicks(int amount) {
comboTicks.set(amount, true);
}
@Override
public double getComboVelocity() {
return comboVelocity.getValue();
}
@Override
public void setComboVelocity(double amount) {
comboVelocity.set(amount, true);
}
@Override
public Map<String, Object> getValues() {
Map<String, Object> map = new LinkedHashMap<>();
for (ConfigSetting<?> setting : getActiveSettings()) {
map.put(setting.getName(), setting.getValue());
}
return map;
}
}
@@ -0,0 +1,105 @@
package dev.azurite.spigot.knockback;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.api.knockback.IKnockback;
import dev.azurite.spigot.api.knockback.IKnockbackManager;
import dev.azurite.spigot.configs.AzuriteConfig;
import dev.azurite.spigot.configs.extra.ConfigFolder;
import dev.azurite.spigot.knockback.extra.KnockbackEdit;
import java.io.File;
import java.util.*;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class KnockbackManager implements IKnockbackManager {
private final Map<String, Knockback> profiles;
private final Map<UUID, KnockbackEdit> editing;
private final ConfigFolder parent;
private Knockback activeProfile;
public KnockbackManager() {
this.profiles = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
this.editing = new HashMap<>();
this.parent = new ConfigFolder("knockback");
this.activeProfile = null;
this.load();
}
private void load() {
File[] files = parent.listFiles();
if (files != null) {
for (File file : files) {
Knockback knockback = (Knockback) createProfile(file.getName());
if (AzuriteConfig.globalActiveKnockback.getValue().equals(knockback.getName())) {
this.activeProfile = knockback;
}
}
}
if (activeProfile == null) {
AzuriteConfig.globalActiveKnockback.set("Default", true);
IKnockback defaultKnockback = getByName("Default");
this.activeProfile = (defaultKnockback != null ? (Knockback) defaultKnockback : (Knockback) createProfile("Default"));
}
}
public Map<UUID, KnockbackEdit> getEditing() {
return editing;
}
@Override
public List<IKnockback> getProfiles() {
return new ArrayList<>(profiles.values());
}
@Override
public IKnockback createProfile(String name) {
Knockback knockback = new Knockback(Azurite.getInstance(), name, parent);
knockback.load();
knockback.save(true);
profiles.put(knockback.getName(), knockback);
return knockback;
}
@Override
public IKnockback deleteProfile(String name) {
Knockback knockback = profiles.get(name);
if (knockback != null && !knockback.getName().equals(activeProfile.getName())) {
knockback.delete();
profiles.remove(name);
}
return knockback;
}
@Override
public IKnockback getByName(String name) {
return profiles.get(name);
}
@Override
public IKnockback getActiveProfile() {
return activeProfile;
}
@Override
public void setActiveProfile(IKnockback knockback) {
this.activeProfile = (Knockback) knockback;
AzuriteConfig.globalActiveKnockback.set(activeProfile.getName(), true);
}
@Override
public void save(boolean async) {
for (Knockback profile : profiles.values()) {
profile.save(async);
}
}
}
@@ -0,0 +1,35 @@
package dev.azurite.spigot.knockback;
import dev.azurite.spigot.configs.extra.ConfigSetting;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public enum KnockbackType {
SIMPLE("Simple", "knockback-simple"),
ADVANCED("Advanced", "knockback-advanced"),
CONSTANT("Constant", "knockback-constant");
private final String displayName;
private final String path;
KnockbackType(String displayName, String path) {
this.displayName = displayName;
this.path = path;
}
public boolean isApplicable(ConfigSetting<?> setting) {
return setting.getPath().isEmpty() || setting.getPath().equals(path);
}
public String getDisplayName() {
return displayName;
}
public String getPath() {
return path;
}
}
@@ -0,0 +1,42 @@
package dev.azurite.spigot.knockback.event;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public class ArrowBypassNoDamageTicksEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean isCancelled = false;
private final Entity damageSource;
public ArrowBypassNoDamageTicksEvent(Player player, Entity damageSource) {
super(player);
this.damageSource = damageSource;
}
public Entity getDamageSource() {
return damageSource;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.isCancelled;
}
@Override
public void setCancelled(boolean cancel) {
this.isCancelled = cancel;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
@@ -0,0 +1,27 @@
package dev.azurite.spigot.knockback.extra;
import dev.azurite.spigot.configs.extra.ConfigSetting;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class KnockbackEdit {
private final String profile;
private final ConfigSetting<?> setting;
public KnockbackEdit(String profile, ConfigSetting<?> setting) {
this.profile = profile;
this.setting = setting;
}
public ConfigSetting<?> getSetting() {
return setting;
}
public String getProfile() {
return profile;
}
}
@@ -0,0 +1,29 @@
package dev.azurite.spigot.knockback.extra;
import dev.azurite.spigot.knockback.Knockback;
import dev.azurite.spigot.knockback.KnockbackType;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class KnockbackParent {
private final Knockback knockback;
private final KnockbackType type;
public KnockbackParent(Knockback knockback, KnockbackType type) {
this.knockback = knockback;
this.type = type;
knockback.knockbackTypes.add(this);
}
public Knockback getKnockback() {
return knockback;
}
public KnockbackType getType() {
return type;
}
}
@@ -0,0 +1,220 @@
package dev.azurite.spigot.knockback.types;
import dev.azurite.spigot.api.knockback.types.IAdvancedKnockback;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.knockback.Knockback;
import dev.azurite.spigot.knockback.KnockbackType;
import dev.azurite.spigot.knockback.extra.KnockbackParent;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class AdvancedKnockback extends KnockbackParent implements IAdvancedKnockback {
public final ConfigSetting<Double> horizontal = new ConfigSetting<>(0.45, "", "Horizontal knockback: horizontal = value");
public final ConfigSetting<Double> horizontalOnGround = new ConfigSetting<>(1.1, "", "On ground horizontal kb modifier: horizontal *= multiplier");
public final ConfigSetting<Double> horizontalSprinting = new ConfigSetting<>(0.95, "", "Sprinting horizontal kb modifier: horizontal *= multiplier");
public final ConfigSetting<Boolean> horizontalInherit = new ConfigSetting<>(true, "", "Inherit victim motion");
public final ConfigSetting<Double> horizontalFriction = new ConfigSetting<>(0.35, "", "Horizontal friction: horizontal = (motion * frictionHorizontal) + victimYaw");
public final ConfigSetting<Double> horizontalKnockbackDeduction = new ConfigSetting<>(0.8, "", "Knockback enchantment modifier: horizontal *= ((enchLevel + 1) - kbDeductionValue)");
public final ConfigSetting<Double> vertical = new ConfigSetting<>(0.35, "", "Vertical knockback. vertical = value");
public final ConfigSetting<Double> verticalOnGround = new ConfigSetting<>(1.1, "", "On ground vertical kb modifier: vertical *= multiplier");
public final ConfigSetting<Double> verticalInAir = new ConfigSetting<>(0.85, "", "In air vertical kb modifier: vertical *= multiplier");
public final ConfigSetting<Double> verticalSprinting = new ConfigSetting<>(1.0, "", "Sprinting vertical kb modifier: vertical *= multiplier");
public final ConfigSetting<Boolean> verticalInherit = new ConfigSetting<>(false, "", "Inherit victim vertical motion");
public final ConfigSetting<Double> verticalFriction = new ConfigSetting<>(0.35, "", "Vertical friction: vertical += (motion * frictionHorizontal)");
public final ConfigSetting<Boolean> enableOnePointSeven = new ConfigSetting<>(true, "", "Help players with victim chasing");
public final ConfigSetting<Double> onePointSevenHorizontal = new ConfigSetting<>(0.37, "", "Horizontal knockback on back-hit: horizontal = value");
public final ConfigSetting<Boolean> enableVerticalLimit = new ConfigSetting<>(false, "", "Limit vertical if it exceeds yLimit");
public final ConfigSetting<Double> verticalLimit = new ConfigSetting<>(1.2, "", "Vertical limit: vertical = 0");
public final ConfigSetting<Double> slowdown = new ConfigSetting<>(0.6, "", "Slowdown player on hit");
public final ConfigSetting<Boolean> cancelSprint = new ConfigSetting<>(true, "", "Cancel sprint for player on hit");
public AdvancedKnockback(Knockback knockback) {
super(knockback, KnockbackType.ADVANCED);
}
@Override
public double getHorizontal() {
return horizontal.getValue();
}
@Override
public void setHorizontal(double amount) {
horizontal.set(amount, true);
}
@Override
public double getHorizontalOnGround() {
return horizontalOnGround.getValue();
}
@Override
public void setHorizontalOnGround(double amount) {
horizontalOnGround.set(amount, true);
}
@Override
public double getHorizontalSprinting() {
return horizontalSprinting.getValue();
}
@Override
public void setHorizontalSprinting(double amount) {
horizontalSprinting.set(amount, true);
}
@Override
public boolean isHorizontalInherit() {
return horizontalInherit.getValue();
}
@Override
public void setHorizontalInherit(boolean value) {
horizontalInherit.set(value, true);
}
@Override
public double getHorizontalFriction() {
return horizontalFriction.getValue();
}
@Override
public void setHorizontalFriction(double amount) {
horizontalFriction.set(amount, true);
}
@Override
public double getHorizontalKnockbackDeduction() {
return horizontalKnockbackDeduction.getValue();
}
@Override
public void setHorizontalKnockbackDeduction(double amount) {
horizontalKnockbackDeduction.set(amount, true);
}
@Override
public double getVertical() {
return vertical.getValue();
}
@Override
public void setVertical(double amount) {
vertical.set(amount, true);
}
@Override
public double getVerticalOnGround() {
return verticalOnGround.getValue();
}
@Override
public void setVerticalOnGround(double amount) {
verticalOnGround.set(amount, true);
}
@Override
public double getVerticalInAir() {
return verticalInAir.getValue();
}
@Override
public void setVerticalInAir(double amount) {
verticalInAir.set(amount, true);
}
@Override
public double getVerticalSprinting() {
return verticalSprinting.getValue();
}
@Override
public void setVerticalSprinting(double amount) {
verticalSprinting.set(amount, true);
}
@Override
public boolean isVerticalInherit() {
return verticalInherit.getValue();
}
@Override
public void setVerticalInherit(boolean value) {
verticalInherit.set(value, true);
}
@Override
public double getVerticalFriction() {
return verticalFriction.getValue();
}
@Override
public void setVerticalFriction(double amount) {
verticalFriction.set(amount, true);
}
@Override
public boolean isOnePointSevenEnabled() {
return enableOnePointSeven.getValue();
}
@Override
public void setOnePointSevenEnabled(boolean value) {
enableOnePointSeven.set(value, true);
}
@Override
public double getOnePointSevenHorizontal() {
return onePointSevenHorizontal.getValue();
}
@Override
public void setOnePointSevenHorizontal(double amount) {
onePointSevenHorizontal.set(amount, true);
}
@Override
public boolean isEnabledVerticalLimit() {
return enableVerticalLimit.getValue();
}
@Override
public void setEnableVerticalLimit(boolean value) {
enableVerticalLimit.set(value, true);
}
@Override
public double getVerticalLimit() {
return verticalLimit.getValue();
}
@Override
public void setVerticalLimit(double amount) {
verticalLimit.set(amount, true);
}
@Override
public double getSlowdown() {
return slowdown.getValue();
}
@Override
public void setSlowdown(double amount) {
slowdown.set(amount, true);
}
@Override
public boolean isCancelSprint() {
return cancelSprint.getValue();
}
@Override
public void setCancelSprint(boolean value) {
cancelSprint.set(value, true);
}
}
@@ -0,0 +1,69 @@
package dev.azurite.spigot.knockback.types;
import dev.azurite.spigot.api.knockback.types.IConstantKnockback;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.knockback.Knockback;
import dev.azurite.spigot.knockback.KnockbackType;
import dev.azurite.spigot.knockback.extra.KnockbackParent;
public class ConstantKnockback extends KnockbackParent implements IConstantKnockback {
public final ConfigSetting<Double> horizontal = new ConfigSetting<>(0.527375, "", "Horizontal knockback");
public final ConfigSetting<Double> vertical = new ConfigSetting<>(0.361375, "", "Vertical knockback");
public final ConfigSetting<Double> verticalLongAir = new ConfigSetting<>(0.1, "", "Vertical knockback when player is for 20 client ticks in the air");
public final ConfigSetting<Double> horizontalSprintReset = new ConfigSetting<>(0.8545, "", "Horizontal knockback after sprint reset");
public final ConfigSetting<Double> yawModifier = new ConfigSetting<>(0.0D, "", "How much extra knockback should be given based on the yaw");
public ConstantKnockback(Knockback knockback) {
super(knockback, KnockbackType.CONSTANT);
}
@Override
public void setHorizontal(double amount) {
horizontal.set(amount, true);
}
@Override
public double getHorizontal() {
return horizontal.getValue();
}
@Override
public void setVertical(double amount) {
vertical.set(amount, true);
}
@Override
public double getVertical() {
return vertical.getValue();
}
@Override
public void setVerticalLongAir(double amount) {
verticalLongAir.set(amount, true);
}
@Override
public double getVerticalLongAir() {
return verticalLongAir.getValue();
}
@Override
public void setHorizontalSprintReset(double amount) {
horizontalSprintReset.set(amount, true);
}
@Override
public double getHorizontalSprintReset() {
return horizontalSprintReset.getValue();
}
@Override
public void setYawModifier(double amount) {
yawModifier.set(amount, true);
}
@Override
public double getYawModifier() {
return yawModifier.getValue();
}
}
@@ -0,0 +1,120 @@
package dev.azurite.spigot.knockback.types;
import dev.azurite.spigot.api.knockback.types.ISimpleKnockback;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.knockback.Knockback;
import dev.azurite.spigot.knockback.KnockbackType;
import dev.azurite.spigot.knockback.extra.KnockbackParent;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class SimpleKnockback extends KnockbackParent implements ISimpleKnockback {
public final ConfigSetting<Double> friction = new ConfigSetting<>(2.5, "", "Friction knockback: friction = value");
public final ConfigSetting<Double> horizontal = new ConfigSetting<>(0.425, "", "Horizontal knockback: horizontal = value");
public final ConfigSetting<Double> vertical = new ConfigSetting<>(0.5, "", "Vertical knockback: vertical = value");
public final ConfigSetting<Double> verticalLimit = new ConfigSetting<>(0.38, "", "Limit of vertical knockback");
public final ConfigSetting<Double> extraHorizontal = new ConfigSetting<>(0.25, "", "Extra horizontal knockback");
public final ConfigSetting<Double> extraVertical = new ConfigSetting<>(0.01, "", "Extra vertical knockback");
public final ConfigSetting<Double> slowdown = new ConfigSetting<>(0.6, "", "Slowdown player on hit");
public final ConfigSetting<Boolean> enableOnePointSeven = new ConfigSetting<>(true, "", "Help players with victim chasing");
public final ConfigSetting<Double> onePointSevenMultiplier = new ConfigSetting<>(0.4, "", "Horizontal knockback multiplier for 1.7");
public SimpleKnockback(Knockback knockback) {
super(knockback, KnockbackType.SIMPLE);
}
@Override
public void setFriction(double amount) {
friction.set(amount, true);
}
@Override
public double getFriction() {
return friction.getValue();
}
@Override
public void setHorizontal(double amount) {
horizontal.set(amount, true);
}
@Override
public double getHorizontal() {
return horizontal.getValue();
}
@Override
public void setVertical(double amount) {
vertical.set(amount, true);
}
@Override
public double getVertical() {
return vertical.getValue();
}
@Override
public void setVerticalLimit(double amount) {
verticalLimit.set(amount, true);
}
@Override
public double getVerticalLimit() {
return verticalLimit.getValue();
}
@Override
public void setExtraHorizontal(double amount) {
extraHorizontal.set(amount, true);
}
@Override
public double getExtraHorizontal() {
return extraHorizontal.getValue();
}
@Override
public void setExtraVertical(double amount) {
extraVertical.set(amount, true);
}
@Override
public double getExtraVertical() {
return extraVertical.getValue();
}
@Override
public void setSlowdown(double amount) {
slowdown.set(amount, true);
}
@Override
public double getSlowdown() {
return slowdown.getValue();
}
@Override
public void setOnePointSevenEnabled(boolean value) {
enableOnePointSeven.set(value, true);
}
@Override
public boolean isOnePointSevenEnabled() {
return enableOnePointSeven.getValue();
}
@Override
public void setOnePointSevenMultiplier(double amount) {
onePointSevenMultiplier.set(amount, true);
}
@Override
public double getOnePointSevenMultiplier() {
return onePointSevenMultiplier.getValue();
}
}
@@ -0,0 +1,113 @@
package dev.azurite.spigot.listeners;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.api.knockback.IKnockback;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.configs.extra.ConfigEdit;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.framework.menu.Menu;
import dev.azurite.spigot.knockback.KnockbackManager;
import dev.azurite.spigot.knockback.extra.KnockbackEdit;
import dev.azurite.spigot.utils.CC;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class ChatListener implements Listener {
@EventHandler(priority = EventPriority.LOW)
public void onChatKnockback(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
KnockbackEdit edit = Azurite.getInstance().getKnockbackManager().getEditing().get(player.getUniqueId());
if (edit != null) {
KnockbackManager manager = Azurite.getInstance().getKnockbackManager();
String message = e.getMessage();
ConfigSetting<?> setting = edit.getSetting();
IKnockback knockback = manager.getByName(edit.getProfile());
e.setCancelled(true);
if (message.equalsIgnoreCase("cancel")) {
manager.getEditing().remove(player.getUniqueId());
CC.sendMessage(player, LanguageConfig.editCancelled.getValue()
.replace("%setting%", setting.getName())
);
return;
}
if (knockback == null) {
manager.getEditing().remove(player.getUniqueId());
CC.sendMessage(player, LanguageConfig.profileNotFound.getValue()
.replace("%name%", edit.getProfile())
);
return;
}
Object value = setting.parseValue(message);
if (value == null) {
CC.sendMessage(player, LanguageConfig.notValidType.getValue()
.replace("%value%", message)
.replace("%type%", setting.getValue().getClass().getSimpleName())
);
return;
}
manager.getEditing().remove(player.getUniqueId());
setting.set(value, true);
CC.sendMessage(player, LanguageConfig.editSettingValue.getValue()
.replace("%setting%", setting.getName())
.replace("%value%", value.toString())
.replace("%profile%", knockback.getName())
);
}
}
@EventHandler
public void onChatConfig(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
ConfigEdit edit = Azurite.getInstance().getConfigEdits().get(player.getUniqueId());
if (edit != null) {
String message = e.getMessage();
ConfigSetting<?> setting = edit.getSetting();
Menu menu = edit.getMenu();
e.setCancelled(true);
if (message.equalsIgnoreCase("cancel")) {
Azurite.getInstance().getConfigEdits().remove(player.getUniqueId());
CC.sendMessage(player, LanguageConfig.configEditCancelled.getValue()
.replace("%setting%", setting.getName())
);
return;
}
Object value = setting.parseValue(message);
if (value == null) {
CC.sendMessage(player, LanguageConfig.notValidType.getValue()
.replace("%value%", message)
.replace("%type%", setting.getValue().getClass().getSimpleName())
);
return;
}
Azurite.getInstance().getConfigEdits().remove(player.getUniqueId());
setting.set(value, true, false);
menu.open();
Azurite.getInstance().reload();
CC.sendMessage(player, LanguageConfig.configEditSetValue.getValue()
.replace("%setting%", setting.getName())
.replace("%value%", value.toString())
);
}
}
}
@@ -0,0 +1,65 @@
package dev.azurite.spigot.listeners;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.framework.menu.Menu;
import dev.azurite.spigot.framework.menu.button.Button;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerJoinEvent;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class MenuListener implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
Menu menu = Azurite.getInstance().getMenuManager().getMenus().get(player.getUniqueId());
if (menu != null) {
menu.onClose();
menu.destroy();
}
}
@EventHandler
public void onClick(InventoryClickEvent e) {
if (!(e.getWhoClicked() instanceof Player)) return;
if (e.getClickedInventory() == null) return;
Player player = (Player) e.getWhoClicked();
Menu menu = Azurite.getInstance().getMenuManager().getMenus().get(player.getUniqueId());
if (menu != null) {
if (!menu.isAllowInteract()) e.setCancelled(true);
menu.onClick(e);
if (e.getClickedInventory() != player.getInventory()) {
Button button = menu.getButtons().get(e.getSlot() + 1);
if (button != null) button.onClick(e);
}
if (e.getClickedInventory() == player.getInventory()) {
menu.onClickOwn(e);
}
}
}
@EventHandler
public void onClose(InventoryCloseEvent e) {
Player player = (Player) e.getPlayer();
Menu menu = Azurite.getInstance().getMenuManager().getMenus().remove(player.getUniqueId());
if (menu != null) {
menu.onClose();
menu.destroy();
}
}
}
@@ -0,0 +1,47 @@
package dev.azurite.spigot.listeners;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.api.pearls.PearlHandler;
import dev.azurite.spigot.configs.PearlConfig;
import dev.azurite.spigot.utils.Utils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.EnderPearl;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.material.Gate;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class PearlListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void handlePearl(PlayerInteractEvent e) {
if (e.getClickedBlock() == null) return;
if (e.getItem() == null || e.getItem().getType() != Material.ENDER_PEARL) return;
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
Player player = e.getPlayer();
Block block = e.getClickedBlock();
String material = block.getType().name();
boolean shouldPearl = (material.contains("FENCE_GATE") && ((Gate) block.getState().getData()).isOpen() &&
PearlConfig.launchOnFenceClick.getValue()) ||
PearlConfig.launchOnOtherClick.getValue().contains(material);
if (shouldPearl) {
for (PearlHandler pearlHandler : Azurite.getInstance().getPearlHandlers()) {
if (pearlHandler.hasCooldown(player)) return;
}
e.setCancelled(true);
player.launchProjectile(EnderPearl.class);
Utils.takeItemInHand(player, 1);
}
}
}
@@ -0,0 +1,136 @@
package dev.azurite.spigot.menu;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.LanguageConfig;
import dev.azurite.spigot.configs.extra.Config;
import dev.azurite.spigot.configs.extra.ConfigEdit;
import dev.azurite.spigot.configs.extra.ConfigSetting;
import dev.azurite.spigot.framework.menu.Menu;
import dev.azurite.spigot.framework.menu.button.Button;
import dev.azurite.spigot.framework.menu.paginated.PaginatedMenu;
import dev.azurite.spigot.utils.CC;
import dev.azurite.spigot.utils.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class ConfigEditMenu extends PaginatedMenu {
private final Config config;
private final List<ConfigSetting<?>> settings;
public ConfigEditMenu(Player player, Config config, Menu previousMenu, List<ConfigSetting<?>> settings) {
super(
player,
"&eEditing: &d" + config.getName(),
previousMenu,
45,
true,
true
);
this.config = config;
this.surroundGlass = true;
this.settings = settings;
// If we are editing the menu directly (no back button, add close button)
if (previousMenu == null) {
defaultButtons.put(size - 4, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
player.closeInventory();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.BED)
.setName("&cClose")
.toItemStack();
}
});
}
}
public ConfigEditMenu(Player player, Config config) {
this(player, config, new MainAzuriteMenu(player), config.getSettings());
}
@Override
public Map<Integer, Button> getButtons(Player player) {
Map<Integer, Button> map = new HashMap<>();
int i = 1;
for (ConfigSetting<?> setting : settings) {
if (!setting.isEditable()) continue;
Object value = setting.getValue();
map.put(i++, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
playClick();
if (value instanceof Boolean) {
setting.set(!(Boolean) value, true, false);
Azurite.getInstance().reload();
update();
} else if (value instanceof Number) {
ConfigEdit configEdit = new ConfigEdit(setting, new ConfigEditMenu(player, config, previousMenu, settings));
Azurite.getInstance().getConfigEdits().put(player.getUniqueId(), configEdit);
player.closeInventory();
player.sendMessage(CC.t(LanguageConfig.configEditNewValue.getValue())
.replace("%setting%", setting.getName())
.replace("%current%", setting.getValue().toString())
);
}
}
@Override
public ItemStack getItemStack() {
Material material = Material.BOOK;
String name = "&d" + setting.getName();
String loreLine = "";
int data = 0;
if (value instanceof Boolean) {
Boolean toggle = (Boolean) value;
material = (toggle ? Material.EMERALD_BLOCK : Material.REDSTONE_BLOCK);
name = name + " &6(Status: " + (toggle ? "&aEnabled" : "&cDisabled") + "&6)";
loreLine = "&eClick to &6toggle &ethis feature.";
//loreLine = "&eClick to " + (toggle ? "&cdisable" : "&aenable") + " &ethis feature.";
} else if (value instanceof Number) {
name = name + " &6(Count: &b" + value + "&6)";
loreLine = "&eClick to &6edit &ethis feature.";
}
List<String> lore = new ArrayList<>();
lore.add("&7&o(" + setting.getFullPath() + ")");
lore.add("");
lore.add(loreLine);
return new ItemBuilder(material)
.setName(name)
.data(data)
.setLore(lore)
.toItemStack();
}
});
}
return map;
}
}
@@ -0,0 +1,143 @@
package dev.azurite.spigot.menu;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.framework.menu.Menu;
import dev.azurite.spigot.framework.menu.button.Button;
import dev.azurite.spigot.menu.extra.ProfileType;
import dev.azurite.spigot.utils.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class MainAzuriteMenu extends Menu {
public MainAzuriteMenu(Player player) {
super(
player,
"&dSpigot Configurations",
45,
false
);
this.fillEnabled = true;
this.filler = new ItemBuilder(Material.STAINED_GLASS_PANE).setName("&7").data(7).toItemStack();
}
@Override
public Map<Integer, Button> getButtons(Player player) {
Map<Integer, Button> map = new HashMap<>();
Azurite instance = Azurite.getInstance();
map.put(11, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
new ProfileListMenu(player, ProfileType.KNOCKBACK).open();
playClick();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.DIAMOND_SWORD)
.setName("&4Knockback Profiles")
.setLore("&eClick to edit knockback profiles.")
.hideAttributes()
.toItemStack();
}
});
map.put(12, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
new ConfigEditMenu(player, instance.getPearlConfig()).open();
playClick();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.ENDER_PEARL)
.setName("&5Enderpearl Config")
.setLore("&eClick to edit enderpearl config.")
.toItemStack();
}
});
map.put(14, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
new ConfigEditMenu(player, instance.getAzuriteConfig()).open();
playClick();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.BOOK)
.setName("&dMain Azurite Config")
.setLore("&eClick to edit the main azurite config.")
.toItemStack();
}
});
map.put(16, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
new ConfigEditMenu(player, instance.getEnchantConfig()).open();
playClick();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.ENCHANTMENT_TABLE)
.setName("&bEnchant Limit Config")
.setLore("&eClick to edit the enchants limit config.")
.toItemStack();
}
});
map.put(17, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
new ProfileListMenu(player, ProfileType.GENERATOR).open();
playClick();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.GRASS)
.setName("&aWorld Generator Profiles")
.setLore("&eClick to edit world generator profiles.")
.toItemStack();
}
});
map.put(32, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
player.closeInventory();
playClick();
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.BED)
.setName("&cClose")
.toItemStack();
}
});
return map;
}
}
@@ -0,0 +1,67 @@
package dev.azurite.spigot.menu;
import dev.azurite.spigot.framework.menu.button.Button;
import dev.azurite.spigot.framework.menu.paginated.PaginatedMenu;
import dev.azurite.spigot.menu.extra.ProfileType;
import dev.azurite.spigot.utils.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class ProfileListMenu extends PaginatedMenu {
private final ProfileType profileType;
public ProfileListMenu(Player player, ProfileType profileType) {
super(
player,
profileType.getTitle(),
new MainAzuriteMenu(player),
18,
true,
false
);
this.profileType = profileType;
}
@Override
public Map<Integer, Button> getButtons(Player player) {
Map<Integer, Button> map = new HashMap<>();
List<String> profiles = new ArrayList<>();
int i = 1;
profileType.addProfiles(profiles);
for (String profile : profiles) {
map.put(i++, new Button() {
@Override
public void onClick(InventoryClickEvent e) {
e.setCancelled(true);
playClick();
profileType.openEdit(player, profile, new ProfileListMenu(player, profileType));
}
@Override
public ItemStack getItemStack() {
return new ItemBuilder(Material.BOOK)
.setName(profileType.getColor() + profile)
.setLore("&eClick to edit this profile.")
.toItemStack();
}
});
}
return map;
}
}
@@ -0,0 +1,71 @@
package dev.azurite.spigot.menu.extra;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.api.knockback.IKnockback;
import dev.azurite.spigot.framework.menu.Menu;
import dev.azurite.spigot.generator.Generator;
import dev.azurite.spigot.knockback.Knockback;
import dev.azurite.spigot.menu.ConfigEditMenu;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.stream.Collectors;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public enum ProfileType {
KNOCKBACK("&dKnockback Profiles", "&4"),
GENERATOR("&dGenerator Profiles", "&a");
private final String title;
private final String color;
ProfileType(String title, String color) {
this.title = title;
this.color = color;
}
public String getTitle() {
return title;
}
public String getColor() {
return color;
}
public void openEdit(Player player, String string, Menu previous) {
switch (this) {
case KNOCKBACK:
IKnockback knockback = Azurite.getInstance().getKnockbackManager().getByName(string);
new ConfigEditMenu(player, (Knockback) knockback, previous, ((Knockback) knockback).getActiveSettings()).open();
break;
case GENERATOR:
Generator generator = Azurite.getInstance().getGeneratorManager().getOrCreate(string);
new ConfigEditMenu(player, generator, previous, generator.getSettings()).open();
break;
}
}
public void addProfiles(List<String> list) {
switch (this) {
case GENERATOR:
list.addAll(Azurite.getInstance().getGeneratorManager().getGenerators().values()
.stream()
.map(Generator::getName)
.collect(Collectors.toList()));
break;
case KNOCKBACK:
list.addAll(Azurite.getInstance().getKnockbackManager().getProfiles()
.stream()
.map(IKnockback::getName)
.collect(Collectors.toList()));
break;
}
}
}
@@ -0,0 +1,94 @@
package dev.azurite.spigot.optimizations;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import net.minecraft.server.Chunk;
import java.util.Arrays;
/**
* chunk list with O(1) remove & contains + fast iteration possible
* Modified to fit the needs of chunk tick list (based on ObjectMapList)
*
* @author Spottedleaf
* @author Beanes
*/
public final class ChunkTickList {
private final Long2IntOpenHashMap objectToIndex;
private static final Chunk[] EMPTY_LIST = new Chunk[0];
private Chunk[] elements = EMPTY_LIST;
private int count;
public ChunkTickList() {
this(1024, 0.8f);
}
public ChunkTickList(int expectedSize, float loadFactor) {
this.objectToIndex = new Long2IntOpenHashMap(expectedSize, loadFactor);
this.objectToIndex.defaultReturnValue(Integer.MIN_VALUE);
}
public int size() {
return this.count;
}
public Chunk get(int index) {
return this.elements[index];
}
public boolean remove(Chunk chunk) {
return this.remove(chunk.chunkHashKey);
}
public boolean remove(long hash) {
final int index = this.objectToIndex.remove(hash);
if (index == Integer.MIN_VALUE) {
return false;
}
// move the obj at the end to this index
final int endIndex = --this.count;
final Chunk end = this.elements[endIndex];
if (index != endIndex) {
// not empty after this call
this.objectToIndex.put(end.chunkHashKey, index); // update index
}
this.elements[index] = end;
this.elements[endIndex] = null;
return true;
}
public boolean add(Chunk chunk) {
final int count = this.count;
final int currIndex = this.objectToIndex.putIfAbsent(chunk.chunkHashKey, count);
if (currIndex != Integer.MIN_VALUE) {
return false; // already in this list
}
Chunk[] list = this.elements;
if (list.length == count) {
// resize required
list = this.elements = Arrays.copyOf(list, (int) Math.max(4L, (long) count << 1)); // overflow results in negative
}
list[count] = chunk;
this.count = count + 1;
return true;
}
public boolean contains(Chunk chunk) {
return this.contains(chunk.chunkHashKey);
}
public boolean contains(long hashKey) {
return this.objectToIndex.containsKey(hashKey);
}
public void clear() {
this.objectToIndex.clear();
Arrays.fill(this.elements, 0, this.count, null);
this.count = 0;
}
}
@@ -0,0 +1,28 @@
package dev.azurite.spigot.optimizations;
import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
import net.minecraft.server.IBlockData;
import net.minecraft.server.RegistryID;
// Azurite - more efficient registry
public class ConstantRegistryID extends RegistryID<IBlockData> {
private final Reference2IntOpenHashMap<IBlockData> identityMap = new Reference2IntOpenHashMap<>(7806); // Azurite - more efficient registry
private final IBlockData[] objectList = new IBlockData[3164];
public void a(IBlockData key, int value) {
this.identityMap.put(key, value);
this.objectList[value] = key;
}
public int b(IBlockData key) {
return this.identityMap.getOrDefault(key, -1);
}
public IBlockData a(int value) {
return value >= 0 && value < 3164 ? this.objectList[value] : null;
}
public IBlockData[] getAllStates() {
return objectList;
}
}
@@ -0,0 +1,23 @@
package dev.azurite.spigot.optimizations;
import net.minecraft.server.NetworkManager;
import net.minecraft.server.Packet;
import java.util.LinkedList;
public class EntityTrackerLinkedList extends LinkedList<Packet<?>> {
public final NetworkManager networkManager;
public EntityTrackerLinkedList(NetworkManager networkManager) {
this.networkManager = networkManager;
}
@Override
public boolean add(Packet<?> o) {
if (!networkManager.shouldSend(o)) {
return false;
}
return super.add(o);
}
}
@@ -0,0 +1,45 @@
package dev.azurite.spigot.optimizations;
import net.minecraft.server.Entity;
import net.minecraft.server.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.World;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class FastActivationRange {
/**
* Find what entities are in range of the players in the world and set
* active if in range.
*
* @param world world to activate in
*/
public static void activateEntities(World world) {
final int miscActivationRange = world.spigotConfig.miscActivationRange;
final int animalActivationRange = world.spigotConfig.animalActivationRange;
final int monsterActivationRange = world.spigotConfig.monsterActivationRange;
// Azurite start - Full recode of activation range
for (Entity entity : world.entityList) {
// Entity is already activated.
if (MinecraftServer.currentTick < entity.activatedTick) continue;
// Entities that are always activated
if (entity.defaultActivationState || entity instanceof EntityPlayer) {
entity.activatedTick = MinecraftServer.currentTick;
continue;
}
int range = (entity.activationType == 1 ? monsterActivationRange : (entity.activationType == 2 ? animalActivationRange : miscActivationRange));
if (world.playerMap.shouldActivate(entity, range, true)) {
entity.activatedTick = MinecraftServer.currentTick;
}
}
// Azurite end
}
}
@@ -0,0 +1,327 @@
package dev.azurite.spigot.optimizations;
import it.unimi.dsi.fastutil.bytes.ByteOpenHashSet;
import it.unimi.dsi.fastutil.bytes.ByteSet;
import net.minecraft.server.*;
import org.spigotmc.SpigotWorldConfig;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static net.minecraft.server.Blocks.*;
// TacoSpigot end
public class FastAntiXray {
// Used to keep track of which blocks to obfuscate
public final boolean[] obfuscateBlocks = new boolean[Short.MAX_VALUE];
public final boolean[] occludingBlocks = new boolean[Short.MAX_VALUE];
// Used to select a random replacement ore
public final byte[] replacementOres;
// PaperSpigot start
public boolean queueUpdates = true;
public final List<BlockPosition> pendingUpdates = new ArrayList<>();
// PaperSpigot end
public FastAntiXray(SpigotWorldConfig config) {
// Set all listed blocks as true to be obfuscated
Set<Block> configuratedBlocks = new HashSet<>();
for (int id : (config.engineMode == 1) ? config.hiddenBlocks : config.replaceBlocks) {
configuratedBlocks.add(Block.getById(id));
}
// Beanes - convert obfuscate blocks to their corresponding block states (also 7806 is the magic value of max block states)
IBlockData[] registry = ((ConstantRegistryID) Block.d).getAllStates();
for (int i = 0; i < registry.length; i++) {
IBlockData blockData = registry[i];
if (blockData != null) {
Block block = blockData.getBlock();
occludingBlocks[i] = isSolidBlock(block);
if (configuratedBlocks.contains(block)) {
obfuscateBlocks[i] = true;
}
}
}
// For every block
ByteSet blocks = new ByteOpenHashSet();
for (Integer i : config.hiddenBlocks) {
Block block = Block.getById(i);
// Check it exists and is not a tile entity
if (block != null && !block.isTileEntity()) {
// Add it to the set of replacement blocks
blocks.add((byte) (int) i);
}
}
// Bake it to a flat array of replacements
replacementOres = blocks.toByteArray();
}
// Beanes - occluding api
public boolean isOccluding(char block) {
return occludingBlocks[block];
}
/**
* PaperSpigot - Flush queued block updates for world.
*/
public void flushUpdates(World world) {
if (world.spigotConfig.antiXray && !pendingUpdates.isEmpty()) {
queueUpdates = false;
for (BlockPosition position : pendingUpdates) {
updateNearbyBlocks(world, position);
}
pendingUpdates.clear();
queueUpdates = true;
}
}
/**
* Starts the timings handler, then updates all blocks within the set radius
* of the given coordinate, revealing them if they are hidden ores.
*/
public void updateNearbyBlocks(World world, BlockPosition position) {
if (world.spigotConfig.antiXray) {
// PaperSpigot start
if (queueUpdates) {
pendingUpdates.add(position);
return;
}
// PaperSpigot end
updateNearbyBlocks(world, position.getX(), position.getY(), position.getZ()); // 2 is the radius, we shouldn't change it as that would make it exponentially slower
}
}
private void updateNearbyBlocks(World world, int x, int y, int z) {
int startX = x - 2;
int endX = x + 2;
int startY = Math.max(0, y - 2);
int endY = Math.min(255, y + 2);
int startZ = z - 2;
int endZ = z + 2;
Chunk chunk = null; // Azurite - cache chunk
for (int x1 = startX; x1 <= endX; x1++) {
for (int y1 = startY; y1 <= endY; y1++) {
for (int z1 = startZ; z1 <= endZ; z1++) {
if (x1 == x & y1 == y & z1 == z)
continue;
Chunk updating;
int chunkX = x1 >> 4;
int chunkZ = z1 >> 4;
// Most of the time we'll be updating in the same chunk
if (chunk != null && chunk.locX == chunkX && chunk.locZ == chunkZ) {
updating = chunk;
} else {
// If we went outside the chunk fetch and cache
updating = world.getChunkIfLoaded(chunkX, chunkZ);
chunk = updating;
}
updateBlock(updating, world, x1, y1, z1);
}
}
}
}
private void updateBlock(Chunk chunk, World world, int x, int y, int z) {
// Beanes - make this use block state
if (chunk == null) return;
int sectionId = y >> 4;
if (sectionId < 0 || sectionId > 15) return;
ChunkSection section = chunk.getSections()[sectionId];
if (section == null) return;
int index = ((y & 0xF) << 8) | ((z & 0xF) << 4) | (x & 0xF);
if (obfuscateBlocks[section.getIdArray()[index]]) {
world.notify(x, y, z);
}
}
private static boolean isSolidBlock(Block block) {
// Mob spawners are treated as solid blocks as far as the
// game is concerned for lighting and other tasks but for
// rendering they can be seen through therefor we special
// case them so that the antixray doesn't show the fake
// blocks around them.
return block.isOccluding() && block != Blocks.MOB_SPAWNER && block != Blocks.BARRIER;
}
private static final char STONE_STATE = (char) Block.d.b(STONE.getBlockData());
private static final char NETHER_RACK_STATE = (char) Block.d.b(NETHERRACK.getBlockData());
private static final char END_STONE_STATE = (char) Block.d.b(END_STONE.getBlockData());
public char getReplaceId(org.bukkit.World.Environment environment) {
switch (environment) {
case NETHER:
return NETHER_RACK_STATE;
case THE_END:
return END_STONE_STATE;
}
return STONE_STATE;
}
public char getReplacedIdEngine1(Chunk chunk, ChunkSection section, ChunkSection[] sending, char blockId, int k, int bitmask, int i, int totalSections) {
World world = chunk.world;
int x = k & 15;
int y = k >> 8 & 15;
int z = k >> 4 & 15;
int posX = x + 1;
int negX = x - 1;
int posY = y + 1;
int negY = y - 1;
int posZ = z + 1;
int negZ = z - 1;
// Checks Y visibility
if (posY > 15 && i + 1 < totalSections) {
ChunkSection upperSection = sending[i + 1];
if (bitmask != '\uffff' || upperSection == null) {
return blockId;
}
int newIndex = (k & 0b000011111111); // Make Y 0 and keep X and Z
if (!isOccluding(upperSection.getBlockId(newIndex))) {
return blockId;
}
} else if (posY <= 15) {
int newIndex = (k & 0b000011111111) | (posY << 8);
if (!isOccluding(section.getBlockId(newIndex))) {
return blockId;
}
}
if (negY < 0 && i - 1 >= 0) {
ChunkSection upperSection = sending[i - 1];
if (bitmask != '\uffff' || upperSection == null) {
return blockId;
}
int newIndex = (k & 0b000011111111 | 0b111100000000); // Keep X and Z and make Y 15
if (!isOccluding(upperSection.getBlockId(newIndex))) {
return blockId;
}
} else if (negY >= 0) {
int newIndex = (k & 0b000011111111) | (negY << 8);
if (!isOccluding(section.getBlockId(newIndex))) {
return blockId;
}
}
// Checks X visibility
if (posX > 15) {
Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX + 1, chunk.locZ);
if (neighbourChunk == null) {
return blockId;
}
ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition());
if (neighbourSection == null) {
return blockId;
}
int newIndex = (k & 0b111111110000); // Make X 0 and keep Y and Z
if (!isOccluding(neighbourSection.getBlockId(newIndex))) {
return blockId;
}
} else {
int newIndex = (k & 0b111111110000) | posX;
if (!isOccluding(section.getBlockId(newIndex))) {
return blockId;
}
}
if (negX < 0) {
Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX - 1, chunk.locZ);
if (neighbourChunk == null) {
return blockId;
}
ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition());
if (neighbourSection == null) {
return blockId;
}
int newIndex = (k & 0b111111110000 | 0b000000001111); // Keep Y and Z and make X 15
if (!isOccluding(neighbourSection.getBlockId(newIndex))) {
return blockId;
}
} else {
int newIndex = (k & 0b111111110000) | negX;
if (!isOccluding(section.getBlockId(newIndex))) {
return blockId;
}
}
// Checks Z visibility
if (posZ > 15) {
Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX, chunk.locZ + 1);
if (neighbourChunk == null) {
return blockId;
}
ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition());
if (neighbourSection == null) {
return blockId;
}
int newIndex = (k & 0b111100001111); // Make Z 0 and keep X and Y
if (!isOccluding(neighbourSection.getBlockId(newIndex))) {
return blockId;
}
} else {
int newIndex = (k & 0b111100001111) | (posZ << 4);
if (!isOccluding(section.getBlockId(newIndex))) {
return blockId;
}
}
if (negZ < 0) {
Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX, chunk.locZ - 1);
if (neighbourChunk == null) {
return blockId;
}
ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition());
if (neighbourSection == null) {
return blockId;
}
int newIndex = (k & 0b111100001111 | 0b000011110000); // Keep Y and X and make X 15
if (!isOccluding(neighbourSection.getBlockId(newIndex))) {
return blockId;
}
} else {
int newIndex = (k & 0b111100001111) | (negZ << 4);
if (!isOccluding(section.getBlockId(newIndex))) {
return blockId;
}
}
return getReplaceId(world.getWorld().getEnvironment());
}
}
@@ -0,0 +1,14 @@
package dev.azurite.spigot.optimizations;
import net.minecraft.server.Packet;
import java.util.function.Supplier;
public class FastEnumProtocol {
public final Supplier<Packet<?>>[] suppliers;
public FastEnumProtocol(Supplier<Packet<?>>[] suppliers) {
this.suppliers = suppliers;
}
}
@@ -0,0 +1,70 @@
package dev.azurite.spigot.optimizations;
import dev.azurite.spigot.utils.NonWakeupNettyRunnable;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import net.minecraft.server.NetworkManager;
import net.minecraft.server.Packet;
import java.util.List;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
@SuppressWarnings("unchecked")
public class FastNetworkManager {
// Azurite start - Lazily write/queue entity tracker updates
public final EntityTrackerLinkedList[] trackerQueue = new EntityTrackerLinkedList[4];
public FastNetworkManager(NetworkManager networkManager) {
// Create queues when init
for (int i = 0; i < 4; i++) {
trackerQueue[i] = new EntityTrackerLinkedList(networkManager);
}
}
public void writePacketLazily(Channel channel, Packet<?> packet) {
if (channel != null && channel.isActive()) {
channel.eventLoop().execute(
new NonWakeupNettyRunnable(() -> channel.write(packet).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE))
);
}
}
public void flushAndWriteCurrentQueue(Channel channel) {
if (channel != null && channel.isActive()) {
// Tracker queue
List<Packet<?>>[] writingTrackerQueues = new List[4];
for (int i = 0; i < trackerQueue.length; i++) {
EntityTrackerLinkedList packets = trackerQueue[i];
writingTrackerQueues[i] = packets; // Copy list
trackerQueue[i] = new EntityTrackerLinkedList(packets.networkManager);
}
// Write cloned & flush
channel.eventLoop().execute(() -> {
// Tracker packets
for (List<Packet<?>> writingTrackerQueue : writingTrackerQueues) {
for (Packet<?> packet : writingTrackerQueue) {
ChannelFuture future = channel.write(packet);
future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
}
// Flush packets
channel.flush();
// No longer needed
for (int i = 0; i < writingTrackerQueues.length; i++) {
writingTrackerQueues[i].clear();
writingTrackerQueues[i] = null;
}
});
}
}
// Azurite end
}
@@ -0,0 +1,169 @@
package dev.azurite.spigot.optimizations;
import net.minecraft.server.*;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.inventory.Inventory;
public class ModernHopperOptimizations {
// Paper start - Optimize Hoppers
public static boolean skipPullModeEventFire = false;
public static boolean skipPushModeEventFire = false;
public static boolean skipHopperEvents = false;
public static boolean hopperPush(TileEntityHopper hopper, IInventory iinventory, EnumDirection enumdirection) {
skipPushModeEventFire = skipHopperEvents;
boolean foundItem = false;
for (int i = 0; i < hopper.getSize(); ++i) {
ItemStack item = hopper.getItem(i);
if (item != null && item.count > 0) {
foundItem = true;
ItemStack origItemStack = item;
ItemStack itemstack = origItemStack;
final int origCount = origItemStack.count;
final int moved = Math.min(hopper.getWorld().spigotConfig.hopperAmount, origCount);
origItemStack.count = (moved);
// We only need to fire the event once to give protection plugins a chance to cancel this event
// Because nothing uses getItem, every event call should end up the same result.
if (!skipPushModeEventFire) {
itemstack = callPushMoveEvent(hopper, iinventory, itemstack);
if (itemstack == null) { // cancelled
origItemStack.count = (origCount);
return false;
}
}
final ItemStack itemstack2 = TileEntityHopper.addItem(iinventory, itemstack, enumdirection);
final int remaining = itemstack2 == null ? 0 : itemstack2.count;
if (remaining != moved) {
origItemStack = origItemStack.cloneItemStack();
origItemStack.count = origCount - moved + remaining;
if (origItemStack.count <= 0) origItemStack = null;
hopper.setItem(i, origItemStack);
iinventory.update();
return true;
}
origItemStack.count = (origCount);
}
}
if (foundItem) {
hopper.d(hopper.getWorld().spigotConfig.hopperTransfer);
}
return false;
}
public static boolean hopperPull(IHopper ihopper, IInventory iinventory, ItemStack origItemStack, int i) {
ItemStack itemstack = origItemStack;
final int origCount = origItemStack == null ? 0 : origItemStack.count;
final World world = ihopper.getWorld();
final int moved = Math.min(world.spigotConfig.hopperAmount, origCount);
if (itemstack != null) {
itemstack.count = moved;
if (itemstack.count <= 0) itemstack = null;
}
if (!skipPullModeEventFire) {
itemstack = callPullMoveEvent(ihopper, iinventory, itemstack);
if (itemstack == null) { // cancelled
if (origItemStack != null) origItemStack.count = origCount;
// Drastically improve performance by returning true.
// No plugin could of relied on the behavior of false as the other call
// site for IMIE did not exhibit the same behavior
return true;
}
}
final ItemStack itemstack2 = TileEntityHopper.addItem(ihopper, itemstack, null);
final int remaining = itemstack2 == null ? 0 : itemstack2.count;
if (origItemStack != null && remaining != moved) {
origItemStack = origItemStack.cloneItemStack();
origItemStack.count = origCount;
if (origItemStack.count <= 0) origItemStack = null;
if (origItemStack != null) {
origItemStack.count = origCount - moved + remaining;
if (origItemStack.count <= 0) origItemStack = null;
}
TileEntityHopper.IGNORE_TILE_UPDATES = true;
iinventory.setItem(i, origItemStack);
TileEntityHopper.IGNORE_TILE_UPDATES = false;
iinventory.update();
return true;
}
if (origItemStack != null) {
origItemStack.count = origCount;
}
cooldownHopper(ihopper); // Cooldown when full
return false;
}
private static ItemStack callPushMoveEvent(TileEntityHopper hopper, IInventory iinventory, ItemStack itemstack) {
Inventory destinationInventory = getInventory(iinventory);
InventoryMoveItemEvent event = new InventoryMoveItemEvent(hopper.getOwner().getInventory(),
CraftItemStack.asCraftMirror(itemstack), destinationInventory, true);
boolean result = event.callEvent();
if (!event.calledGetItem && !event.calledSetItem) {
skipPushModeEventFire = true;
}
if (!result) {
cooldownHopper(hopper);
return null;
}
if (event.calledSetItem) {
return CraftItemStack.asNMSCopy(event.getItem());
} else {
return itemstack;
}
}
private static ItemStack callPullMoveEvent(IHopper hopper, IInventory iinventory, ItemStack itemstack) {
Inventory sourceInventory = getInventory(iinventory);
Inventory destination = getInventory(hopper);
InventoryMoveItemEvent event = new InventoryMoveItemEvent(sourceInventory,
// Mirror is safe as we no plugins ever use this item
CraftItemStack.asCraftMirror(itemstack), destination, false);
boolean result = event.callEvent();
if (!event.calledGetItem && !event.calledSetItem) {
skipPullModeEventFire = true;
}
if (!result) {
cooldownHopper(hopper);
return null;
}
if (event.calledSetItem) {
return CraftItemStack.asNMSCopy(event.getItem());
} else {
return itemstack;
}
}
public static Inventory getInventory(IInventory iinventory) {
if (iinventory instanceof InventoryLargeChest) {
return new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest((InventoryLargeChest) iinventory);
}
return iinventory.getOwner().getInventory();
}
private static void cooldownHopper(IHopper hopper) {
if (hopper instanceof TileEntityHopper) {
((TileEntityHopper) hopper).d(hopper.getWorld().spigotConfig.hopperTransfer);
} else if (hopper instanceof EntityMinecartHopper) {
((EntityMinecartHopper) hopper).m(hopper.getWorld().spigotConfig.hopperTransfer / 2);
}
}
// Paper end
}
@@ -0,0 +1,223 @@
package dev.azurite.spigot.optimizations;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.AbstractReferenceList;
import it.unimi.dsi.fastutil.objects.ObjectListIterator;
import it.unimi.dsi.fastutil.objects.ObjectSpliterator;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* list with O(1) remove & contains
*
* @author Spottedleaf
*/
@SuppressWarnings("unchecked")
public final class ObjectMapList<T> extends AbstractReferenceList<T> implements Set<T> {
private final Int2IntOpenHashMap objectToIndex;
public T[] elements;
public int count;
public ObjectMapList(Class<T> clazz) {
this(clazz, 2, 0.8f);
}
public ObjectMapList(Class<T> clazz, int expectedSize) {
this(clazz, expectedSize, 0.8f);
}
public ObjectMapList(Class<T> clazz, int expectedSize, float loadFactor) {
this.objectToIndex = new Int2IntOpenHashMap(expectedSize, loadFactor);
this.objectToIndex.defaultReturnValue(Integer.MIN_VALUE);
this.elements = (T[]) Array.newInstance(clazz, expectedSize);
}
@Override
public int size() {
return this.count;
}
@Override
public int indexOf(Object object) {
return this.objectToIndex.get(object.hashCode());
}
@Override
public int lastIndexOf(Object object) {
return super.indexOf(object);
}
@Override
public boolean remove(final Object object) {
final int index = this.objectToIndex.remove(object.hashCode());
if (index == Integer.MIN_VALUE) {
return false;
}
// move the obj at the end to this index
final int endIndex = --this.count;
final T end = this.elements[endIndex];
if (index != endIndex) {
// not empty after this call
this.objectToIndex.put(end.hashCode(), index); // update index
}
this.elements[index] = end;
this.elements[endIndex] = null;
return true;
}
@Override
public T remove(final int index) {
T obj = this.elements[index];
this.objectToIndex.remove(obj.hashCode());
// move the obj at the end to this index
final int endIndex = --this.count;
final T end = this.elements[endIndex];
if (index != endIndex) {
// not empty after this call
this.objectToIndex.put(end.hashCode(), index); // update index
}
this.elements[index] = end;
this.elements[endIndex] = null;
return obj;
}
@Override
public boolean add(final T object) {
final int count = this.count;
final int currIndex = this.objectToIndex.putIfAbsent(object.hashCode(), count);
if (currIndex != Integer.MIN_VALUE) {
return false; // already in this list
}
T[] list = this.elements;
if (list.length == count) {
// resize required
list = this.elements = Arrays.copyOf(list, (int) Math.max(4L, (long) count << 1)); // overflow results in negative
}
list[count] = object;
this.count = count + 1;
return true;
}
@Override
public void add(final int index, final T object) {
final int currIndex = this.objectToIndex.putIfAbsent(object.hashCode(), index);
if (currIndex != Integer.MIN_VALUE) {
return; // already in this list
}
int count = this.count;
T[] list = this.elements;
if (list.length == count) {
// resize required
list = this.elements = Arrays.copyOf(list, (int) Math.max(4L, (long) count << 1)); // overflow results in negative
}
System.arraycopy(list, index, list, index + 1, count - index);
list[index] = object;
this.count = count + 1;
}
@Override
public T get(int index) {
return this.elements[index];
}
@Override
public boolean isEmpty() {
return this.count == 0;
}
@Override
public void clear() {
this.objectToIndex.clear();
Arrays.fill(this.elements, 0, this.count, null);
this.count = 0;
}
@Override
public Object @NotNull [] toArray() {
return Arrays.copyOf(this.elements, this.count);
}
@Override
public @NotNull ObjectSpliterator<T> spliterator() {
return super.spliterator();
}
@Override
public @NotNull ObjectListIterator<T> iterator() {
return new Iterator(0);
}
private class Iterator implements ObjectListIterator<T> {
T lastRet;
int current;
Iterator(int index) {
current = index;
}
@Override
public int nextIndex() {
return this.current + 1;
}
@Override
public int previousIndex() {
return this.current - 1;
}
@Override
public boolean hasNext() {
return this.current < ObjectMapList.this.count;
}
@Override
public boolean hasPrevious() {
return this.current > 0;
}
@Override
public T next() {
if (this.current >= ObjectMapList.this.count) {
throw new NoSuchElementException();
}
return this.lastRet = ObjectMapList.this.elements[this.current++];
}
@Override
public T previous() {
if (this.current < 0) {
throw new NoSuchElementException();
}
return this.lastRet = ObjectMapList.this.elements[--this.current];
}
@Override
public void remove() {
final T lastRet = this.lastRet;
if (lastRet == null) {
throw new IllegalStateException();
}
this.lastRet = null;
ObjectMapList.this.remove(lastRet);
--this.current;
}
}
}
@@ -0,0 +1,135 @@
package dev.azurite.spigot.optimizations;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class OptimizedNonEmptyList<T> implements List<T> {
private boolean isEmpty = true;
@Override
public int size() {
return isEmpty ? 0 : 1;
}
@Override
public boolean isEmpty() {
return isEmpty;
}
@Override
public boolean contains(Object o) {
throw new IllegalStateException();
}
@NotNull
@Override
public Iterator<T> iterator() {
throw new IllegalStateException();
}
@NotNull
@Override
public Object @NotNull [] toArray() {
throw new IllegalStateException();
}
@Override
public boolean add(Object object) {
isEmpty = false;
return true;
}
@Override
public boolean remove(Object o) {
throw new IllegalStateException();
}
@Override
public boolean addAll(@NotNull Collection c) {
isEmpty = false;
return true;
}
@Override
public boolean addAll(int index, @NotNull Collection c) {
isEmpty = false;
return true;
}
@Override
public void clear() {
isEmpty = true;
}
@Override
public T get(int index) {
throw new IllegalStateException();
}
@Override
public T set(int index, Object element) {
throw new IllegalStateException();
}
@Override
public void add(int index, Object element) {
throw new IllegalStateException();
}
@Override
public T remove(int index) {
throw new IllegalStateException();
}
@Override
public int indexOf(Object o) {
throw new IllegalStateException();
}
@Override
public int lastIndexOf(Object o) {
throw new IllegalStateException();
}
@NotNull
@Override
public ListIterator<T> listIterator() {
throw new IllegalStateException();
}
@NotNull
@Override
public ListIterator<T> listIterator(int index) {
throw new IllegalStateException();
}
@NotNull
@Override
public List<T> subList(int fromIndex, int toIndex) {
throw new IllegalStateException();
}
@Override
public boolean retainAll(@NotNull Collection c) {
throw new IllegalStateException();
}
@Override
public boolean removeAll(@NotNull Collection c) {
throw new IllegalStateException();
}
@Override
public boolean containsAll(@NotNull Collection c) {
throw new IllegalStateException();
}
@NotNull
@Override
public Object[] toArray(@NotNull Object[] a) {
throw new IllegalStateException();
}
}
@@ -0,0 +1,291 @@
package dev.azurite.spigot.optimizations;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.server.*;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
public class PlayerMap {
public static final int CHUNK_BITS = 5;
public final Long2ObjectOpenHashMap<ObjectMapList<EntityPlayer>> map = new Long2ObjectOpenHashMap<>();
public static long xzToKey(long x, long z) {
return (x << 32) + z - Integer.MIN_VALUE;
}
public void add(EntityPlayer player) {
int x = MathHelper.floor(player.locX) >> CHUNK_BITS;
int z = MathHelper.floor(player.locZ) >> CHUNK_BITS;
long key = xzToKey(x, z);
ObjectMapList<EntityPlayer> list = map.get(key);
if (list == null) {
list = new ObjectMapList<>(EntityPlayer.class);
map.put(key, list);
}
list.add(player);
player.playerMapX = x;
player.playerMapZ = z;
}
public void move(EntityPlayer player) {
int x = MathHelper.floor(player.locX) >> CHUNK_BITS;
int z = MathHelper.floor(player.locZ) >> CHUNK_BITS;
// did we move?
if (x == player.playerMapX && z == player.playerMapZ) {
return;
}
// do remove
long key = xzToKey(player.playerMapX, player.playerMapZ);
ObjectMapList<EntityPlayer> list = map.get(key);
if (list != null) {
list.remove(player);
if (list.isEmpty()) {
map.remove(key);
}
}
// do add
key = xzToKey(x, z);
list = map.get(key);
if (list == null) {
list = new ObjectMapList<>(EntityPlayer.class);
map.put(key, list);
}
list.add(player);
player.playerMapX = x;
player.playerMapZ = z;
}
public void remove(EntityPlayer player) {
long key = xzToKey(player.playerMapX, player.playerMapZ);
List<EntityPlayer> list = map.get(key);
if (list == null) {
// player has not yet been added to this playermap, this happens when teleporting to another world during PlayerJoinEvent
return;
}
list.remove(player);
if (list.isEmpty()) {
map.remove(key);
}
}
public void forEachNearby(double x, double y, double z, double distance, boolean useRadius, Consumer<EntityPlayer> function) {
for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players != null) {
for (EntityPlayer player : players) {
if (!useRadius || player.e(x, y, z) < distance * distance) {
function.accept(player);
}
}
}
}
}
}
public EntityPlayer getNearestPlayer(double x, double y, double z, double distance) {
double bestDistanceSqrd = -1.0;
EntityPlayer bestPlayer = null;
for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players != null) {
for (EntityPlayer player : players) {
double playerDistSqrd = player.e(x, y, z);
if (playerDistSqrd < distance * distance && (bestDistanceSqrd == -1.0 || playerDistSqrd < bestDistanceSqrd)) {
bestDistanceSqrd = playerDistSqrd;
bestPlayer = player;
}
}
}
}
}
return bestPlayer;
}
public boolean isPlayerNearby(double x, double y, double z, double distance, boolean respectSpawningApi) {
for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players != null) {
for (EntityPlayer player : players) {
if (player != null && !player.dead && (!respectSpawningApi || player.affectsSpawning)) {
double playerDistSqrd = player.e(x, y, z);
if (playerDistSqrd < distance * distance) {
return true;
}
}
}
}
}
}
return false;
}
public EntityPlayer getNearbyPlayer(double x, double y, double z, double distance, boolean respectSpawningApi) {
return getNearbyPlayer(x, y, z, distance, respectSpawningApi, true);
}
public EntityPlayer getNearbyPlayer(double x, double y, double z, double distance, boolean respectSpawningApi, boolean best) {
double bestDistanceSqrd = -1.0;
EntityPlayer bestPlayer = null;
for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players != null) {
for (EntityPlayer player : players) {
if (player != null && !player.dead && (!respectSpawningApi || player.affectsSpawning)) {
double playerDistSqrd = player.e(x, y, z);
if (playerDistSqrd < distance * distance && (bestDistanceSqrd == -1.0 || playerDistSqrd < bestDistanceSqrd)) {
bestDistanceSqrd = playerDistSqrd;
if (!best) return player;
bestPlayer = player;
}
}
}
}
}
}
return bestPlayer;
}
public boolean shouldActivate(Entity entity, double distance, boolean respectSpawningApi) {
double entityX = entity.locX;
double entityY = entity.locY;
double entityZ = entity.locZ;
for (int chunkX = MathHelper.floor(entityX - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(entityX + distance) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(entityZ - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(entityZ + distance) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players == null) continue;
for (EntityPlayer player : players) {
if (player != null && !player.dead && (!respectSpawningApi || player.affectsSpawning)) {
double playerX1 = player.locX - distance;
double playerY1 = player.locY - distance;
double playerZ1 = player.locZ - distance;
double playerX2 = player.locX + distance;
double playerY2 = player.locY + distance;
double playerZ2 = player.locZ + distance;
// Bounding box
if (entityX >= playerX1 && entityY >= playerY1 && entityZ >= playerZ1 && entityX <= playerX2 && entityY <= playerY2 && entityZ <= playerZ2) {
return true;
}
}
}
}
}
return false;
}
public List<EntityPlayer> getNearbyPlayersIgnoreHeight(double x, double z, double distance) {
List<EntityPlayer> toReturn = null;
for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players != null) {
for (EntityPlayer player : players) {
if (player != null && !player.dead && Math.abs(player.locX - x) <= distance && Math.abs(player.locZ - z) <= distance) {
if (toReturn == null) {
toReturn = new ObjectMapList<>(EntityPlayer.class);
}
toReturn.add(player);
}
}
}
}
}
return toReturn == null ? Collections.emptyList() : toReturn;
}
public EntityPlayer getNearestAttackablePlayer(double x, double y, double z, double maxXZ, double maxY, Function<EntityHuman, Double> visibility) {
return getNearestAttackablePlayer(x, y, z, maxXZ, maxY, visibility, null);
}
public EntityPlayer getNearestAttackablePlayer(double x, double y, double z, double maxXZ, double maxY, Function<EntityHuman, Double> visibility, Predicate<EntityHuman> condition) {
double bestDistanceSqrd = -1.0;
EntityPlayer bestPlayer = null;
for (int chunkX = MathHelper.floor(x - maxXZ) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + maxXZ) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(z - maxXZ) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + maxXZ) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players != null) {
for (EntityPlayer player : players) {
if (!player.abilities.isInvulnerable && player.isAlive() && (condition == null || condition.apply(player))) {
double dx = player.locX - x;
double dz = player.locZ - z;
double playerDistSqrd = dx * dx + dz * dz;
double dy = Math.abs(player.locY - y);
double distForPlayer = maxXZ;
if (player.isSneaking()) {
distForPlayer *= 0.8;
}
if (visibility != null) {
Double v = visibility.apply(player);
if (v != null) {
distForPlayer *= v;
}
}
// mojang mistake squaring maxY?
if ((maxY < 0.0 || dy < maxY * maxY) && playerDistSqrd < distForPlayer * distForPlayer && (bestDistanceSqrd == -1.0 || playerDistSqrd < bestDistanceSqrd)) {
bestDistanceSqrd = playerDistSqrd;
bestPlayer = player;
}
}
}
}
}
}
return bestPlayer;
}
public void sendPacketNearby(EntityPlayer source, double x, double y, double z, double distance, Packet<?> packet) {
this.sendPacketNearby(source, x, y, z, distance, packet, false);
}
public void sendPacketNearby(EntityPlayer source, double x, double y, double z, double distance, Packet<?> packet, boolean self) {
for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) {
for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) {
List<EntityPlayer> players = map.get(xzToKey(chunkX, chunkZ));
if (players != null) {
for (EntityPlayer player : players) {
// don't send self
if (!self && player == source) {
continue;
}
// bukkit visibility api
if (source != null && !player.getBukkitEntity().canSee(source.getBukkitEntity())) {
continue;
}
double playerDistSqrd = player.e(x, y, z);
if (playerDistSqrd < distance * distance) {
player.playerConnection.sendPacket(packet);
}
}
}
}
}
}
}
@@ -0,0 +1,222 @@
// Original source: velocity
package dev.azurite.spigot.optimizations;
import dev.azurite.spigot.utils.CountingDataOutput;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.EncoderException;
import net.minecraft.server.*;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
public class ProtocolUtils {
private static final int MAXIMUM_VARINT_SIZE = 5;
private static final int[] VAR_INT_LENGTHS = new int[65];
static {
for (int i = 0; i <= 32; ++i) {
VAR_INT_LENGTHS[i] = (int) Math.ceil((31d - (i - 1)) / 7d);
}
VAR_INT_LENGTHS[32] = 1; // Special case for the number 0.
}
/**
* Reads a Minecraft-style VarInt from the specified {@code buf}.
*
* @param buf the buffer to read from
* @return the decoded VarInt
*/
public static int readVarInt(ByteBuf buf) {
int readable = buf.readableBytes();
if (readable == 0) {
// special case for empty buffer
throw new CorruptedFrameException("VarInt not readable");
}
// we can read at least one byte, and this should be a common case
int k = buf.readByte();
if ((k & 0x80) != 128) {
return k;
}
// in case decoding one byte was not enough, use a loop to decode up to the next 4 bytes
int maxRead = Math.min(MAXIMUM_VARINT_SIZE, readable);
int i = k & 0x7F;
for (int j = 1; j < maxRead; j++) {
k = buf.readByte();
i |= (k & 0x7F) << j * 7;
if ((k & 0x80) != 128) {
return i;
}
}
throw new CorruptedFrameException("VarInt is invalid");
}
/**
* Returns the exact byte size of {@code value} if it were encoded as a VarInt.
*
* @param value the value to encode
* @return the byte size of {@code value} if encoded as a VarInt
*/
public static int varIntBytes(int value) {
return VAR_INT_LENGTHS[Integer.numberOfLeadingZeros(value)];
}
/**
* Writes a Minecraft-style VarInt to the specified {@code buf}.
*
* @param buf the buffer to read from
* @param value the integer to write
*/
public static void writeVarInt(ByteBuf buf, int value) {
// Peel the one and two byte count cases explicitly as they are the most common VarInt sizes
// that the proxy will write, to improve inlining.
if ((value & (0xFFFFFFFF << 7)) == 0) {
buf.writeByte(value);
} else if ((value & (0xFFFFFFFF << 14)) == 0) {
int w = (value & 0x7F | 0x80) << 8 | (value >>> 7);
buf.writeShort(w);
} else {
writeVarIntFull(buf, value);
}
}
private static void writeVarIntFull(ByteBuf buf, int value) {
// See https://steinborn.me/posts/performance/how-fast-can-you-write-a-varint/
// This essentially is an unrolled version of the "traditional" VarInt encoding.
if ((value & (0xFFFFFFFF << 7)) == 0) {
buf.writeByte(value);
} else if ((value & (0xFFFFFFFF << 14)) == 0) {
int w = (value & 0x7F | 0x80) << 8 | (value >>> 7);
buf.writeShort(w);
} else if ((value & (0xFFFFFFFF << 21)) == 0) {
int w = (value & 0x7F | 0x80) << 16 | ((value >>> 7) & 0x7F | 0x80) << 8 | (value >>> 14);
buf.writeMedium(w);
} else if ((value & (0xFFFFFFFF << 28)) == 0) {
int w = (value & 0x7F | 0x80) << 24 | (((value >>> 7) & 0x7F | 0x80) << 16)
| ((value >>> 14) & 0x7F | 0x80) << 8 | (value >>> 21);
buf.writeInt(w);
} else {
int w = (value & 0x7F | 0x80) << 24 | ((value >>> 7) & 0x7F | 0x80) << 16
| ((value >>> 14) & 0x7F | 0x80) << 8 | ((value >>> 21) & 0x7F | 0x80);
buf.writeInt(w);
buf.writeByte(value >>> 28);
}
}
public static int getStringSize(String s) {
int utf8Bytes = io.netty.buffer.ByteBufUtil.utf8Bytes(s);
return ProtocolUtils.varIntBytes(utf8Bytes) + utf8Bytes;
}
public static int getItemSize(ItemStack itemStack) {
if (itemStack == null || itemStack.getItem() == null) { // CraftBukkit - NPE fix itemstack.getItem()
return 2;
} else {
int size = 2 + 1 + 2;
NBTTagCompound nbttagcompound = null;
if (itemStack.getItem().usesDurability() || itemStack.getItem().p()) {
// Spigot start - filter
itemStack = itemStack.cloneItemStack();
CraftItemStack.setItemMeta(itemStack, CraftItemStack.getItemMeta(itemStack));
// Spigot end
nbttagcompound = itemStack.getTag();
}
size += getNBTSize(nbttagcompound);
return size;
}
}
public static int getNBTSize(NBTTagCompound nbt) {
if (nbt == null) {
return 1;
} else {
CountingDataOutput output = new CountingDataOutput();
try {
NBTCompressedStreamTools.a(nbt, output);
} catch (Exception ioexception) { // CraftBukkit - IOException -> Exception
throw new EncoderException(ioexception);
}
return output.getByteCount();
}
}
public static int getDataWatcherSize(DataWatcher dataWatcher) {
return 1 + getDataWatcherObjectsSize(dataWatcher.dataValues.values());
}
public static int getDataWatcherListSize(Collection<DataWatcher.WatchableObject> watchableObjects) {
return 1 + getDataWatcherObjectsSize(watchableObjects);
}
private static int getDataWatcherObjectsSize(Collection<DataWatcher.WatchableObject> watchableObjects) {
int size = 0;
for (DataWatcher.WatchableObject watchableObject : watchableObjects) {
size += 1;
switch (watchableObject.c()) {
case 0:
size += 1;
break;
case 1:
size += 2;
break;
case 2:
size += 4;
break;
case 3:
size += 4;
break;
case 4:
size += ProtocolUtils.getStringSize((String) watchableObject.b());
break;
case 5:
size += ProtocolUtils.getItemSize((ItemStack) watchableObject.b());
break;
case 6:
case 7:
size += (4 + 4 + 4);
break;
}
}
return size;
}
public static int getChatComponentSize(IChatBaseComponent component) {
return getStringSize(IChatBaseComponent.ChatSerializer.a(component));
}
public static int getChatComponentSize(net.md_5.bungee.api.chat.BaseComponent[] component) {
return getStringSize(net.md_5.bungee.chat.ComponentSerializer.toString(component));
}
public static int getEnumSize(Enum<?> oenum) {
return varIntBytes(oenum.ordinal());
}
public static int getByteArraySize(byte[] arr) {
return varIntBytes(arr.length) + arr.length;
}
}
@@ -0,0 +1,24 @@
package dev.azurite.spigot.optimizations;
public class ReusableByteArray {
private final ThreadLocal<byte[]> arrays;
public ReusableByteArray(final int initialSize) {
arrays = ThreadLocal.withInitial(() -> new byte[initialSize]);
}
/**
* Returns a (thread local) byte array of at least minSize
* @param minSize Minimum size of returned array
* @return byte array
*/
public byte[] get(int minSize) {
byte[] array = arrays.get();
if (array.length < minSize) {
array = new byte[minSize];
arrays.set(array);
}
return array;
}
}
@@ -0,0 +1,72 @@
package dev.azurite.spigot.optimizations;
import it.unimi.dsi.fastutil.shorts.Short2IntOpenHashMap;
import java.util.Arrays;
// Based on Moonrise (SpottedLeaf) IntList but with short instead of int
public final class SectionTickList {
private final Short2IntOpenHashMap map = new Short2IntOpenHashMap(0);
{
this.map.defaultReturnValue(Integer.MIN_VALUE);
}
private static final short[] EMPTY_LIST = new short[0];
private short[] byIndex = EMPTY_LIST;
private int count;
public int size() {
return this.count;
}
public short getRaw(final int index) {
return this.byIndex[index];
}
public boolean add(final short value) {
final int count = this.count;
final int currIndex = this.map.putIfAbsent(value, count);
if (currIndex != Integer.MIN_VALUE) {
return false; // already in this list
}
short[] list = this.byIndex;
if (list.length == count) {
// resize required
list = this.byIndex = Arrays.copyOf(list, (int)Math.max(4L, count * 2L)); // overflow results in negative
}
list[count] = value;
this.count = count + 1;
return true;
}
public boolean remove(final short value) {
final int index = this.map.remove(value);
if (index == Integer.MIN_VALUE) {
return false;
}
// move the entry at the end to this index
final int endIndex = --this.count;
final short end = this.byIndex[endIndex];
if (index != endIndex) {
// not empty after this call
this.map.put(end, index);
}
this.byIndex[index] = end;
this.byIndex[endIndex] = 0;
return true;
}
public void clear() {
this.count = 0;
this.map.clear();
}
}
@@ -0,0 +1,53 @@
package dev.azurite.spigot.optimizations;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
// https://github.com/Tuinity/Moonrise/blob/89e9cd52e4c7818b595b686a1d8798ccb1287f69/src/main/java/ca/spottedleaf/moonrise/common/util/SimpleRandom.java#L8
// https://github.com/Tuinity/Moonrise/blob/89e9cd52e4c7818b595b686a1d8798ccb1287f69/LICENSE.md
public final class SimpleRandom extends Random {
private static final long MULTIPLIER = 25214903917L;
private static final long ADDEND = 11L;
private static final int BITS = 48;
private static final long MASK = (1L << BITS) - 1;
private long value;
public SimpleRandom() {
this(System.currentTimeMillis());
}
public SimpleRandom(final long seed) {
super(0L);
this.value = seed;
}
@Override
public void setSeed(final long seed) {
this.value = (seed ^ MULTIPLIER) & MASK;
}
private long advanceSeed() {
return this.value = ((this.value * MULTIPLIER) + ADDEND) & MASK;
}
@Override
public int next(final int bits) {
return (int)(this.advanceSeed() >>> (BITS - bits));
}
@Override
public int nextInt() {
final long seed = this.advanceSeed();
return (int)(seed >>> (BITS - Integer.SIZE));
}
@Override
public int nextInt(final int bound) {
// https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
final long value = this.advanceSeed() >>> (BITS - Integer.SIZE);
return (int)((value * (long)bound) >>> Integer.SIZE);
}
}
@@ -0,0 +1,215 @@
package dev.azurite.spigot.pathsearch;
import dev.azurite.spigot.Azurite;
import dev.azurite.spigot.configs.AzuriteConfig;
import dev.azurite.spigot.pathsearch.cache.SearchCacheEntry;
import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryEntity;
import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryPosition;
import net.minecraft.server.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
public class AzuriteNavigation extends Navigation {
private final Map<UUID, SearchCacheEntry> searchCache;
private final Map<PositionPathSearchType, SearchCacheEntryPosition> positionSearchCache;
private final Object jobLock = new Object();
private int cleanUpDelay = 0;
private PathSearchJob lastQueuedJob;
public AzuriteNavigation(EntityInsentient entityinsentient, World world) {
super(entityinsentient, world);
this.searchCache = new HashMap<>();
this.positionSearchCache = new HashMap<>();
}
private double getMinimumDistanceForOffloadingSquared() {
return AzuriteConfig.minimumDistanceToTarget.getValue();
}
private boolean hasAsyncSearchIssued() {
synchronized (this.jobLock) {
return this.lastQueuedJob != null;
}
}
private void queueSearch(PathSearchJob job) {
synchronized (this.jobLock) {
if (Azurite.getInstance().getThreadingManager().getPathSearchExecutor().queuePathSearch(job)) {
this.lastQueuedJob = job;
}
}
}
private void issueSearch(Entity target) {
this.queueSearch(new PathSearchJobEntity(this, target));
}
private void issueSearch(BlockPosition blockposition, PositionPathSearchType type) {
this.queueSearch(new PathSearchJobPosition(this, blockposition, type));
}
@Override
public void setSearchResult(PathSearchJobEntity pathSearch) {
synchronized (this.jobLock) {
if (this.lastQueuedJob == pathSearch) {
this.lastQueuedJob = null;
}
}
SearchCacheEntry entry = pathSearch.getCacheEntryValue();
if (entry != null && entry.didSearchSucceed()) {
synchronized (this.searchCache) {
UUID key = pathSearch.getCacheEntryKey();
this.searchCache.remove(key);
this.searchCache.put(key, entry);
}
}
}
@Override
public void setSearchResult(PathSearchJobPosition pathSearch) {
synchronized (this.jobLock) {
if (this.lastQueuedJob == pathSearch) {
this.lastQueuedJob = null;
}
}
SearchCacheEntryPosition entry = pathSearch.getCacheEntryValue();
if (entry != null && entry.didSearchSucceed()) {
synchronized (this.positionSearchCache) {
PositionPathSearchType key = pathSearch.getCacheEntryKey();
this.positionSearchCache.remove(key);
this.positionSearchCache.put(key, entry);
}
}
}
@Override
public PathEntity a(Entity entity) {
if (!this.offloadSearches() || this.b.h(entity) < getMinimumDistanceForOffloadingSquared()) {
return super.a(entity);
}
if (!this.b()) {
return null;
}
SearchCacheEntry entry = null;
UUID id = entity.getUniqueID();
synchronized (this.searchCache) {
if (this.searchCache.containsKey(id)) {
entry = this.searchCache.get(id);
}
}
PathEntity resultPath = null;
if (entry != null) {
resultPath = entry.getAdjustedPathEntity();
if (!entry.isStillValid()) {
this.issueSearch(entity);
}
}
if (entry == null && !this.hasAsyncSearchIssued()) {
resultPath = super.a(entity);
if (resultPath != null) {
entry = new SearchCacheEntryEntity(this.b, entity, resultPath);
synchronized (this.searchCache) {
SearchCacheEntry oldEntry = this.searchCache.put(id, entry);
if (oldEntry != null) {
oldEntry.cleanup();
}
}
}
}
return resultPath;
}
@Override
public PathEntity a(BlockPosition blockposition) {
return this.a(blockposition, PositionPathSearchType.ANOTHER);
}
public PathEntity a(BlockPosition blockposition, PositionPathSearchType type) {
if (!this.offloadSearches() || this.b.c(blockposition) < getMinimumDistanceForOffloadingSquared()) {
return super.a(blockposition);
}
if (!this.b()) {
return null;
}
SearchCacheEntryPosition entry = null;
synchronized (this.positionSearchCache) {
if (this.positionSearchCache.containsKey(type)) {
entry = this.positionSearchCache.get(type);
}
}
PathEntity resultPath = null;
if (entry != null) {
resultPath = entry.getAdjustedPathEntity();
if (!entry.isStillValid()) {
this.issueSearch(blockposition, type);
}
}
if (entry == null && !this.hasAsyncSearchIssued()) {
resultPath = super.a(blockposition);
if (resultPath != null) {
entry = new SearchCacheEntryPosition(this.b, blockposition, resultPath);
synchronized (this.positionSearchCache) {
SearchCacheEntry oldEntry = this.positionSearchCache.put(type, entry);
if (oldEntry != null) {
oldEntry.cleanup();
}
}
}
}
return resultPath;
}
@Override
public PathEntity a(double d0, double d1, double d2, PositionPathSearchType type) {
return this.a(new BlockPosition(MathHelper.floor(d0), (int) d1, MathHelper.floor(d2)), type);
}
@Override
public boolean a(double d0, double d1, double d2, double d3, PositionPathSearchType type) {
PathEntity pathentity = this.a(MathHelper.floor(d0), (int) d1, MathHelper.floor(d2), type);
return this.a(pathentity, d3);
}
public void cleanUpExpiredSearches() {
this.cleanUpDelay++;
if (this.cleanUpDelay > 100) {
this.cleanUpDelay = 0;
synchronized (this.searchCache) {
Iterator<Entry<UUID, SearchCacheEntry>> iterator = this.searchCache.entrySet().iterator();
while (iterator.hasNext()) {
SearchCacheEntry entry = iterator.next().getValue();
if (entry.hasExpired()) {
iterator.remove();
entry.cleanup();
} else {
break;
}
}
}
synchronized (this.positionSearchCache) {
Iterator<Entry<PositionPathSearchType, SearchCacheEntryPosition>> iterator = this.positionSearchCache.entrySet().iterator();
while (iterator.hasNext()) {
SearchCacheEntryPosition entry = iterator.next().getValue();
if (entry.hasExpired()) {
iterator.remove();
entry.cleanup();
} else {
break;
}
}
}
}
}
private boolean offloadSearches() {
return Azurite.getInstance().getThreadingManager().getPathSearchExecutor().isPathSearchOffloadedFor(this.b);
}
}
@@ -0,0 +1,50 @@
package dev.azurite.spigot.pathsearch;
import java.util.concurrent.Callable;
import dev.azurite.spigot.utils.WeakChunkCache;
import net.minecraft.server.NavigationAbstract;
import net.minecraft.server.PathEntity;
public abstract class PathSearchJob implements Callable<PathSearchJob> {
public NavigationAbstract navigation;
protected WeakChunkCache chunkCache;
protected boolean issued;
private final int hashCode;
protected PathEntity pathEntity;
public PathSearchJob(NavigationAbstract navigation) {
this.navigation = navigation;
this.hashCode = this.navigation.hashCode();
this.issued = false;
this.chunkCache = this.navigation.createChunkCache(this.isEntitySearch());
}
protected boolean isEntitySearch() {
return false;
}
public void cleanup() {
this.navigation = null;
this.chunkCache = null;
this.pathEntity = null;
}
@Override
public int hashCode() {
return this.hashCode;
}
public final int getSearchHash() {
return this.hashCode;
}
@Override
public boolean equals(Object o) {
if(!(o instanceof PathSearchJob)) {
return false;
}
return this.hashCode() == o.hashCode();
}
}
@@ -0,0 +1,52 @@
package dev.azurite.spigot.pathsearch;
import java.util.UUID;
import dev.azurite.spigot.pathsearch.cache.SearchCacheEntry;
import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryEntity;
import net.minecraft.server.Entity;
import net.minecraft.server.NavigationAbstract;
public class PathSearchJobEntity extends PathSearchJob {
public Entity target;
public PathSearchJobEntity(NavigationAbstract navigation, Entity target) {
super(navigation);
this.target = target;
}
@Override
public PathSearchJob call() throws Exception {
if(!this.issued) {
this.issued = true;
this.pathEntity = this.navigation.doPathSearch(this.chunkCache, this.target);
this.navigation.setSearchResult(this);
this.cleanup();
}
return this;
}
@Override
protected boolean isEntitySearch() {
return true;
}
@Override
public void cleanup() {
super.cleanup();
this.target = null;
}
public UUID getCacheEntryKey() {
return this.target.getUniqueID();
}
public SearchCacheEntry getCacheEntryValue() {
if(this.pathEntity != null) {
return new SearchCacheEntryEntity(this.navigation.getEntity(), this.target, this.pathEntity);
}
return null;
}
}
@@ -0,0 +1,59 @@
package dev.azurite.spigot.pathsearch;
import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryPosition;
import net.minecraft.server.BlockPosition;
import net.minecraft.server.NavigationAbstract;
public class PathSearchJobPosition extends PathSearchJob {
private final PositionPathSearchType type;
private BlockPosition blockposition;
public PathSearchJobPosition(NavigationAbstract navigation, BlockPosition blockposition, PositionPathSearchType type) {
super(navigation);
this.blockposition = blockposition;
this.type = type;
}
@Override
public PathSearchJob call() throws Exception {
if(!this.issued) {
this.issued = true;
this.pathEntity = this.navigation.doPathSearch(this.chunkCache, this.blockposition);
this.navigation.setSearchResult(this);
this.cleanup();
}
return this;
}
public PositionPathSearchType getCacheEntryKey() {
return this.type;
}
public SearchCacheEntryPosition getCacheEntryValue() {
if(this.pathEntity != null) {
return new SearchCacheEntryPosition(this.navigation.getEntity(), this.blockposition, this.pathEntity);
}
return null;
}
@Override
public int hashCode() {
return this.type.hashCode() ^ (super.hashCode() << 4);
}
@Override
public boolean equals(Object o) {
if(!(o instanceof PathSearchJobPosition)) {
return false;
}
PathSearchJobPosition other = (PathSearchJobPosition) o;
return this.type.equals(other.type) && this.hashCode() == other.hashCode();
}
@Override
public void cleanup() {
super.cleanup();
this.blockposition = null;
}
}
@@ -0,0 +1,117 @@
package dev.azurite.spigot.pathsearch;
import dev.azurite.spigot.async.factory.NamePriorityThreadFactory;
import dev.azurite.spigot.configs.AzuriteConfig;
import net.minecraft.server.EntityInsentient;
import org.bukkit.entity.EntityType;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.*;
public class PathSearchThrottlerThread extends ThreadPoolExecutor {
private int queueLimit;
private final LinkedHashMap<PathSearchJob, PathSearchJob> filter;
private final Set<Integer> activeSearchHashes;
private static PathSearchThrottlerThread instance;
private final Set<EntityType> entitiesWithOffloadedPathSearches = new HashSet<>();
public PathSearchThrottlerThread(int poolSize) {
super(poolSize, poolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), new NamePriorityThreadFactory(Thread.MIN_PRIORITY, "Azurite_PathFinder"));
instance = this;
adjustPoolSize(poolSize);
this.filter = new LinkedHashMap<>();
this.activeSearchHashes = new HashSet<>();
this.loadEntitiesWithOffloadedPathSearches();
}
public boolean queuePathSearch(PathSearchJob newJob) {
boolean jobHasBeenQueued = false;
if (newJob != null) {
synchronized (this.filter) {
if (this.filter.containsKey(newJob) || this.filter.size() < 1000) {
jobHasBeenQueued = true;
PathSearchJob previousJob = this.filter.put(newJob, newJob);
if (previousJob != null) {
previousJob.cleanup();
}
}
}
}
PathSearchJob jobToExecute;
synchronized (this.filter) {
Iterator<Entry<PathSearchJob, PathSearchJob>> iterator = this.filter.entrySet().iterator();
while (iterator.hasNext() && this.getQueue().size() < this.queueLimit) {
jobToExecute = iterator.next().getValue();
if (!this.activeSearchHashes.contains(jobToExecute.getSearchHash())) {
iterator.remove();
this.activeSearchHashes.add(jobToExecute.getSearchHash());
this.submit(jobToExecute);
if (newJob != null) {
break;
}
}
}
}
return jobHasBeenQueued;
}
@Override
public void shutdown() {
this.getQueue().clear();
super.shutdown();
}
@Override
protected void afterExecute(Runnable runnable, Throwable throwable) {
super.afterExecute(runnable, throwable);
if (runnable instanceof FutureTask) {
FutureTask<PathSearchJob> task = (FutureTask<PathSearchJob>) runnable;
PathSearchJob job = null;
try {
job = task.get();
} catch (InterruptedException | ExecutionException e) {
// Empty catch
}
if (job != null) {
synchronized (this.filter) {
this.activeSearchHashes.remove(job.getSearchHash());
}
}
}
this.queuePathSearch(null);
}
public static void adjustPoolSize(int size) {
if (instance != null) {
if (size > instance.getMaximumPoolSize()) {
instance.setMaximumPoolSize(size);
instance.setCorePoolSize(size);
} else if (size < instance.getMaximumPoolSize()) {
instance.setCorePoolSize(size);
instance.setMaximumPoolSize(size);
}
instance.queueLimit = size * 8;
}
}
private void loadEntitiesWithOffloadedPathSearches() {
this.entitiesWithOffloadedPathSearches.clear();
for (String name : AzuriteConfig.entitiesPathSearchOffload.getValue()) {
try {
EntityType type = EntityType.valueOf(name.toUpperCase());
this.entitiesWithOffloadedPathSearches.add(type);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
public boolean isPathSearchOffloadedFor(EntityInsentient entity) {
return AzuriteConfig.enableAsyncPathSearch.getValue() && this.entitiesWithOffloadedPathSearches.contains(entity.getBukkitEntity().getType());
}
}
@@ -0,0 +1,16 @@
package dev.azurite.spigot.pathsearch;
public enum PositionPathSearchType {
ANOTHER,
AVOIDTARGET,
FLEESUN,
GOTOTARGET,
MOVEINDOORS,
MOVETHROUGHVILLAGE,
MOVETOWARDSRESTRICTION,
MOVETOWARDSTARGET,
PANIC,
PLAY,
RANDOMSTROLL,
TAME;
}
@@ -0,0 +1,76 @@
package dev.azurite.spigot.pathsearch.cache;
import net.minecraft.server.BlockPosition;
import net.minecraft.server.Entity;
import net.minecraft.server.EntityInsentient;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.PathEntity;
import net.minecraft.server.PathPoint;
public class SearchCacheEntry {
protected long tick;
protected BlockPosition positionStart;
protected BlockPosition positionTarget;
protected EntityInsentient entity;
private PathEntity path;
public SearchCacheEntry(EntityInsentient entity, PathEntity path) {
this.entity = entity;
this.positionStart = this.getBlockPosition(this.entity);
this.path = path;
this.tick = this.getCurrentTick();
}
protected int getCurrentTick() {
return MinecraftServer.getServer().at();
}
protected BlockPosition getBlockPosition(Entity entity) {
return new BlockPosition(entity).up();
}
protected BlockPosition getBlockPosition(int x, int y, int z) {
return new BlockPosition(x, y, z);
}
public boolean isStillValid() {
return this.didSearchSucceed() && (this.getCurrentTick() - this.tick < 10);
}
public PathEntity getPathEntity() {
return this.path;
}
public boolean hasExpired() {
return !this.entity.isAlive() || !this.entity.valid || (this.getCurrentTick() - this.tick) > 100;
}
public boolean didSearchSucceed() {
return this.path != null;
}
public PathEntity getAdjustedPathEntity() {
if(this.path != null && (this.path.e() < this.path.d() - 1)) {
PathPoint pathpoint = this.path.a(this.path.e());
double currentDist = this.entity.e(pathpoint.a, pathpoint.b, pathpoint.c);
while(this.path.e() < this.path.d() - 1) {
pathpoint = this.path.a(this.path.e() + 1);
double nextDist = this.entity.e(pathpoint.a, pathpoint.b, pathpoint.c);
if(nextDist < currentDist) {
currentDist = nextDist;
this.path.a();
} else {
break;
}
}
}
return this.path;
}
public void cleanup() {
this.positionStart = null;
this.positionTarget = null;
this.entity = null;
this.path = null;
}
}
@@ -0,0 +1,30 @@
package dev.azurite.spigot.pathsearch.cache;
import net.minecraft.server.Entity;
import net.minecraft.server.EntityInsentient;
import net.minecraft.server.PathEntity;
public class SearchCacheEntryEntity extends SearchCacheEntry {
private Entity target;
public SearchCacheEntryEntity(EntityInsentient entity, Entity target, PathEntity path) {
super(entity, path);
this.target = target;
this.positionTarget = this.getBlockPosition(this.target);
}
@Override
public boolean isStillValid() {
if(super.isStillValid()) {
return this.getBlockPosition(this.target).equals(this.positionTarget);
}
return false;
}
@Override
public void cleanup() {
super.cleanup();
this.target = null;
}
}
@@ -0,0 +1,21 @@
package dev.azurite.spigot.pathsearch.cache;
import net.minecraft.server.BlockPosition;
import net.minecraft.server.EntityInsentient;
import net.minecraft.server.PathEntity;
public class SearchCacheEntryPosition extends SearchCacheEntry {
public SearchCacheEntryPosition(EntityInsentient entity, BlockPosition blockposition, PathEntity path) {
super(entity, path);
this.positionTarget = blockposition;
}
@Override
public boolean isStillValid() {
if(super.isStillValid()) {
return this.getBlockPosition(this.entity).equals(this.positionStart);
}
return false;
}
}
@@ -0,0 +1,495 @@
package dev.azurite.spigot.redstone;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import dev.azurite.spigot.utils.LinkedArraySet;
import net.minecraft.server.*;
import org.apache.commons.lang3.ArrayUtils;
import org.bukkit.event.block.BlockRedstoneEvent;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/*
* Based on https://gist.github.com/Panda4994/70ed6d39c89396570e062e4404a8d518
* https://www.spigotmc.org/resources/pandawire-1-8-8-1-15-2.41991/
*
* Mainly based on a decompiled version of PandaWire, with comments and structure
* from the original copied over. This get rid of any errors the decompiler made.
*
* On top of that theres additional optimisations in places.
*/
public class PandaRedstoneWire extends BlockRedstoneWire {
/*
* I considered replacing the lists with LinkedHashSets for faster lookup,
* but an artificial test showed barely any difference in performance
*/
/**
* Positions that need to be turned off
**/
private final List<BlockPosition> turnOff = Lists.newArrayList();
/**
* Positions that need to be checked to be turned on
**/
private final List<BlockPosition> turnOn = Lists.newArrayList();
/**
* Positions of wire that was updated already (Ordering determines update order and is therefore required!)
**/
private final Set<BlockPosition> updatedRedstoneWire = new LinkedArraySet<>();
/**
* Ordered arrays of the facings; Needed for the update order.
* I went with a vertical-first order here, but vertical last would work to.
* However it should be avoided to update the vertical axis between the horizontal ones as this would cause unneeded directional behavior.
**/
private static final EnumDirection[] facingsHorizontal = {EnumDirection.WEST, EnumDirection.EAST, EnumDirection.NORTH, EnumDirection.SOUTH};
private static final EnumDirection[] facingsVertical = {EnumDirection.DOWN, EnumDirection.UP};
private static final EnumDirection[] facings = ArrayUtils.addAll(facingsVertical, facingsHorizontal);
/**
* Offsets for all surrounding blocks that need to receive updates
**/
private static final BaseBlockPosition[] surroundingBlocksOffset;
static {
Set<BaseBlockPosition> set = Sets.newLinkedHashSet();
for (EnumDirection facing : facings) {
set.add(ReflectUtil.getOfT(facing, BaseBlockPosition.class));
}
for (EnumDirection facing1 : facings) {
BaseBlockPosition v1 = ReflectUtil.getOfT(facing1, BaseBlockPosition.class);
for (EnumDirection facing2 : facings) {
BaseBlockPosition v2 = ReflectUtil.getOfT(facing2, BaseBlockPosition.class);
if (v2 == null) continue;
if (v1 == null) continue;
set.add(new BlockPosition(v1.getX() + v2.getX(), v1.getY() + v2.getY(), v1.getZ() + v2.getZ()));
}
}
set.remove(BlockPosition.ZERO);
surroundingBlocksOffset = set.toArray(new BaseBlockPosition[0]);
}
private boolean canProvidePower = true;
public PandaRedstoneWire() {
super();
}
private void updateSurroundingRedstone(World worldIn, BlockPosition pos, IBlockData iblockdata) {
// Recalculate the connected wires
calculateCurrentChanges(worldIn, pos, iblockdata);
// Set to collect all the updates, to only execute them once. Ordering required.
Set<BlockPosition> blocksNeedingUpdate = Sets.newLinkedHashSet();
// Add the needed updates
for (BlockPosition posi : updatedRedstoneWire) {
addBlocksNeedingUpdate(worldIn, posi, blocksNeedingUpdate);
}
// Add all other updates to keep known behaviors
// They are added in a backwards order because it preserves a commonly used behavior with the update order
Iterator<BlockPosition> it = Lists.newLinkedList(updatedRedstoneWire).descendingIterator();
while (it.hasNext()) {
addAllSurroundingBlocks(it.next(), blocksNeedingUpdate);
}
// Remove updates on the wires as they just were updated
blocksNeedingUpdate.removeAll(updatedRedstoneWire);
/* Avoid unnecessary updates on the just updated wires
* A huge scale test showed about 40% more ticks per second
* It's probably less in normal usage but likely still worth it
*/
updatedRedstoneWire.clear();
// Execute updates
for (BlockPosition posi : blocksNeedingUpdate) {
worldIn.d(posi, this);
}
}
/**
* Turns on or off all connected wires
*
* @param worldIn World
* @param position Position of the wire that received the update
* @param state Current state of this block
*/
protected void calculateCurrentChanges(World worldIn, BlockPosition position, IBlockData state) {
// Turn off all connected wires first if needed
if (state.getBlock() == this) {
this.turnOff.add(position);
} else {
// In case this wire was removed, check the surrounding wires
checkSurroundingWires(worldIn, position);
}
while (!turnOff.isEmpty()) {
BlockPosition pos = turnOff.remove(0);
state = worldIn.getType(pos);
int oldPower = state.get(POWER);
this.canProvidePower = false;
int blockPower = worldIn.A(pos);
this.canProvidePower = true;
int wirePower = getSurroundingWirePower(worldIn, pos);
// Lower the strength as it moved a block
--wirePower;
int newPower = Math.max(blockPower, wirePower);
// Power lowered?
if (newPower < oldPower) {
// If it's still powered by a direct source (but weaker) mark for turn on
if (blockPower > 0 && !turnOn.contains(pos)) {
turnOn.add(pos);
}
// Set all the way to off for now, because wires that were powered by this need to update first
setWireState(worldIn, pos, state, 0);
// Power rose?
} else if (newPower > oldPower) {
// Set new Power
setWireState(worldIn, pos, state, newPower);
}
// Check if surrounding wires need to change based on the current/new state and add them to the lists
checkSurroundingWires(worldIn, pos);
}
while (!turnOn.isEmpty()) {
BlockPosition pos = turnOn.remove(0);
state = worldIn.getType(pos);
int oldPower = state.get(POWER);
this.canProvidePower = false;
int blockPower = worldIn.A(pos);
this.canProvidePower = true;
int wirePower = getSurroundingWirePower(worldIn, pos);
// Lower the strength as it moved a block
wirePower--;
int newPower = Math.max(blockPower, wirePower);
if (oldPower != newPower) {
BlockRedstoneEvent event = new BlockRedstoneEvent(
worldIn.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()),
oldPower,
newPower);
worldIn.getServer().getPluginManager().callEvent(event);
newPower = event.getNewCurrent();
}
if (newPower > oldPower) {
setWireState(worldIn, pos, state, newPower);
}
// Check if surrounding wires need to change based on the current/new state and add them to the lists
checkSurroundingWires(worldIn, pos);
}
turnOff.clear();
}
/**
* Checks if an wire needs to be marked for update depending on the power next to it
*
* @param worldIn World
* @param pos Position of the wire that might need to change
* @param otherPower Power of the wire next to it
* @author panda
*/
protected void addWireToList(World worldIn, BlockPosition pos, int otherPower) {
IBlockData state = worldIn.getType(pos);
if (state.getBlock() == this) {
int power = state.get(POWER);
// Could get powered stronger by the neighbor?
if (power < otherPower - 1 && !turnOn.contains(pos)) {
// Mark for turn on check.
turnOn.add(pos);
}
// Should have powered the neighbor? Probably was powered by it and is in turn off phase.
if (power > otherPower && !turnOff.contains(pos)) {
// Mark for turn off check.
turnOff.add(pos);
}
}
}
/**
* Checks if the wires around need to get updated depending on this wires state.
* Checks all wires below before the same layer before on top to keep
* some more rotational symmetry around the y-axis.
*
* @param worldIn World
* @param pos Position of the wire
* @author panda
*/
protected void checkSurroundingWires(World worldIn, BlockPosition pos) {
IBlockData state = worldIn.getType(pos);
int ownPower = 0;
if (state.getBlock() == Blocks.REDSTONE_WIRE) {
ownPower = state.get(POWER);
}
// Check wires on the same layer first as they appear closer to the wire
for (EnumDirection facingHorizontal : facingsHorizontal) {
this.addWireToList(worldIn, pos.shift(facingHorizontal), ownPower);
}
for (EnumDirection facingVertical : facingsVertical) {
BlockPosition offsetPos = pos.shift(facingVertical);
Block block = worldIn.getType(offsetPos).getBlock();
boolean solidBlock = block.u();
for (EnumDirection facingHorizontal : facingsHorizontal) {
// wire can travel upwards if the block on top doesn't cut the wire (is non-solid)
// it can travel down if the block below is solid and the block "diagonal" doesn't cut off the wire (is non-solid)
if (facingVertical == EnumDirection.UP && (!solidBlock || /* This can improve glowstone wiring up to 2.5x */ block == Blocks.GLOWSTONE) || facingVertical == EnumDirection.DOWN && solidBlock && !worldIn.getType(offsetPos.shift(facingHorizontal)).getBlock().isOccluding()) {
this.addWireToList(worldIn, offsetPos.shift(facingHorizontal), ownPower);
}
}
}
}
/**
* Gets the maximum power of the surrounding wires
*
* @param worldIn World
* @param pos Position of the asking wire
* @return The maximum power of the wires that could power the wire at pos
* @author panda
*/
private int getSurroundingWirePower(World worldIn, BlockPosition pos) {
int wirePower = 0;
for (EnumDirection enumfacing : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition offsetPos = pos.shift(enumfacing);
IBlockData iblockdata = worldIn.getType(offsetPos);
boolean occluding = iblockdata.getBlock().isOccluding();
// Wires on the same layer
wirePower = this.getPower(iblockdata, wirePower);
// Block below the wire need to be solid (Upwards diode of slabs/stairs/glowstone) and no block should cut the wire
if (occluding && !worldIn.getType(pos.up()).getBlock().isOccluding()) {
wirePower = this.getPower(worldIn, offsetPos.up(), wirePower);
// Only get from power below if no block is cutting the wire
} else if (!occluding) {
wirePower = this.getPower(worldIn, offsetPos.down(), wirePower);
}
}
return wirePower;
}
/**
* Adds all blocks that need to receive an update from a redstone change in this position.
* This means only blocks that actually could change.
*
* @param worldIn World
* @param pos Position of the wire
* @param set Set to add the update positions too
* @author panda
*/
private void addBlocksNeedingUpdate(World worldIn, BlockPosition pos, Set<BlockPosition> set) {
Set<EnumDirection> connectedSides = getSidesToPower(worldIn, pos);
// Add the blocks next to the wire first (closest first order)
for (EnumDirection facing : facings) {
BlockPosition offsetPos = pos.shift(facing);
IBlockData state = worldIn.getType(offsetPos);
// canConnectTo() is not the nicest solution here as it returns true for e.g. the front of a repeater
// canBlockBePowereFromSide catches these cases
boolean flag = connectedSides.contains(facing.opposite()) || facing == EnumDirection.DOWN;
if (flag || (facing.k().c() && a(state, facing))) {
if (canBlockBePoweredFromSide(state, facing, true)) set.add(offsetPos);
}
// Later add blocks around the surrounding blocks that get powered
if (flag && worldIn.getType(offsetPos).getBlock().isOccluding()) {
for (EnumDirection facing1 : facings) {
if (canBlockBePoweredFromSide(worldIn.getType(offsetPos.shift(facing1)), facing1, false))
set.add(offsetPos.shift(facing1));
}
}
}
}
/**
* Checks if a block can get powered from a side.
* This behavior would better be implemented per block type as follows:
* - return false as default. (blocks that are not affected by redstone don't need to be updated, it doesn't really hurt if they are either)
* - return true for all blocks that can get powered from all side and change based on it (doors, fence gates, trap doors, note blocks, lamps, dropper, hopper, TNT, rails, possibly more)
* - implement own logic for pistons, repeaters, comparators and redstone torches
* The current implementation was chosen to keep everything in one class.
* <p>
* Why is this extra check needed?
* 1. It makes sure that many old behaviors still work (QC + Pistons).
* 2. It prevents updates from "jumping".
* Or rather it prevents this wire to update a block that would get powered by the next one of the same line.
* This is to prefer as it makes understanding the update order of the wire really easy. The signal "travels" from the power source.
*
* @param state State of the block
* @param side Side from which it gets powered
* @param isWire True if it's powered by a wire directly, False if through a block
* @return True if the block can change based on the power level it gets on the given side, false otherwise
* @author panda
*/
private boolean canBlockBePoweredFromSide(IBlockData state, EnumDirection side, boolean isWire) {
Block block = state.getBlock();
if (block == Blocks.AIR) return false;
if (block instanceof BlockPiston && state.get(BlockPiston.FACING) == side.opposite()) return false;
if (block instanceof BlockDiodeAbstract && state.get(BlockDiodeAbstract.FACING) != side.opposite())
return isWire && block instanceof BlockRedstoneComparator && state.get(BlockRedstoneComparator.FACING).k() != side.k() && side.k().c();
return !(state.getBlock() instanceof BlockRedstoneTorch) || (!isWire && state.get(BlockRedstoneTorch.FACING) == side);
}
/**
* Creates a list of all horizontal sides that can get powered by a wire.
* The list is ordered the same as the facingsHorizontal.
*
* @param worldIn World
* @param pos Position of the wire
*/
private Set<EnumDirection> getSidesToPower(World worldIn, BlockPosition pos) {
Set<EnumDirection> retval = Sets.newHashSet();
for (EnumDirection facing : facingsHorizontal) {
if (this.isPowerSourceAt(worldIn, pos, facing)) {
retval.add(facing);
}
}
if (retval.isEmpty()) return Sets.newHashSet(facingsHorizontal);
boolean northsouth = retval.contains(EnumDirection.NORTH) || retval.contains(EnumDirection.SOUTH);
boolean eastwest = retval.contains(EnumDirection.EAST) || retval.contains(EnumDirection.WEST);
if (northsouth) {
retval.remove(EnumDirection.EAST);
retval.remove(EnumDirection.WEST);
}
if (eastwest) {
retval.remove(EnumDirection.NORTH);
retval.remove(EnumDirection.SOUTH);
}
return retval;
}
private boolean canSidePower(World worldIn, BlockPosition pos, EnumDirection side) {
Set<EnumDirection> retval = Sets.newHashSet();
for (EnumDirection facing : facingsHorizontal) {
if (this.isPowerSourceAt(worldIn, pos, facing)) {
retval.add(facing);
}
}
if (retval.isEmpty()) {
return true;
}
boolean northsouth = retval.contains(EnumDirection.NORTH) || retval.contains(EnumDirection.SOUTH);
boolean eastwest = retval.contains(EnumDirection.EAST) || retval.contains(EnumDirection.WEST);
if (northsouth) {
retval.remove(EnumDirection.EAST);
retval.remove(EnumDirection.WEST);
}
if (eastwest) {
retval.remove(EnumDirection.NORTH);
retval.remove(EnumDirection.SOUTH);
}
return retval.contains(side);
}
/**
* Adds all surrounding positions to a set.
* This is the neighbor blocks, as well as their neighbors
*/
private void addAllSurroundingBlocks(BlockPosition pos, Set<BlockPosition> set) {
for (BaseBlockPosition vect : surroundingBlocksOffset) {
set.add(pos.a(vect));
}
}
/**
* Sets the block state of a wire with a new power level and marks for updates
*
* @param worldIn World
* @param pos Position at which the state needs to be set
* @param state Old state
* @param power Power it should get set to
* @author panda
*/
private void setWireState(World worldIn, BlockPosition pos, IBlockData state, int power) {
state = state.set(POWER, power);
worldIn.setTypeAndData(pos, state, 2);
updatedRedstoneWire.add(pos);
}
@Override
public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) {
this.updateSurroundingRedstone(world, blockposition, world.getType(blockposition));
for (EnumDirection enumdirection : EnumDirection.values()) {
world.applyPhysics(blockposition.shift(enumdirection), this);
}
}
@Override
public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) {
for (EnumDirection enumdirection : EnumDirection.values()) {
world.applyPhysics(blockposition.shift(enumdirection), this);
}
this.updateSurroundingRedstone(world, blockposition, world.getType(blockposition));
}
@Override
public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block, BlockPosition source) {
if (this.canPlace(world, blockposition)) {
this.updateSurroundingRedstone(world, blockposition, iblockdata);
} else {
this.b(world, blockposition, iblockdata, 0);
world.setAir(blockposition);
}
}
protected final int getPower(IBlockData state, int power) {
if (state.getBlock() != Blocks.REDSTONE_WIRE) {
return power;
}
int j = state.get(BlockRedstoneWire.POWER);
return Math.max(j, power);
}
@Override
public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) {
if (!this.canProvidePower) {
return 0;
} else {
int i = iblockdata.get(BlockRedstoneWire.POWER);
if (i == 0) { // md_5 change? This isn't in the original.
return 0;
} else if (enumdirection == EnumDirection.UP) {
return i;
} else {
return this.canSidePower((World) iblockaccess, blockposition, enumdirection) ? i : 0;
}
}
}
private boolean isPowerSourceAt(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) {
BlockPosition blockpos = blockposition.shift(enumdirection);
IBlockData iblockdata = iblockaccess.getType(blockpos);
Block block = iblockdata.getBlock();
boolean flag = block.isOccluding();
boolean flag1 = iblockaccess.getType(blockposition.up()).getBlock().isOccluding();
return !flag1 && flag && e(iblockaccess, blockpos.up()) || (a(iblockdata, enumdirection) || (block == Blocks.POWERED_REPEATER && iblockdata.get(BlockDiodeAbstract.FACING) == enumdirection || !flag && e(iblockaccess, blockpos.down())));
}
public static class ReflectUtil {
public static <T> T getOfT(Object obj, Class<T> type) {
for (Field field : obj.getClass().getDeclaredFields()) {
if (type.equals(field.getType())) {
return get(obj, field, type);
}
}
return null;
}
public static <T> T get(Object obj, Field field, Class<T> type) {
try {
field.setAccessible(true);
return type.cast(field.get(obj));
} catch (ReflectiveOperationException ex) {
ex.printStackTrace();
return null;
}
}
}
}
@@ -0,0 +1,94 @@
package dev.azurite.spigot.tickloop;
import dev.azurite.spigot.configs.AzuriteConfig;
import net.minecraft.server.CrashReport;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ServerPing;
import net.minecrell.terminalconsole.TerminalConsoleAppender;
import java.util.Arrays;
import java.util.concurrent.locks.LockSupport;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class AzuriteTickloop implements Runnable {
// Azurite - custom tick loop
private static final long TICK_TIME_IN_NANO = 50_000_000L; // 50 ms in nanos
private static final long TIME_SLEEP = 100000L; // 0.1ms in nanos
private static final long SLEEP_DRIFT = 500000L; // Increasing this number should increase cpu but help with tick drifting, we check 0.5 ms before
private static final long SLEEP_MINIMUM_TIME = TIME_SLEEP + SLEEP_DRIFT; // Instead of sleeping we use more cpu just to keep checking within the minimum time
private static final long MAX_CATCHUP_TIME = 20_000_000_000L; // Make sure if server lagged for a prolonging time that we don't suddenly processes more than 20 seconds within a very short time frame
private final MinecraftServer server;
public AzuriteTickloop(MinecraftServer server) {
this.server = server;
}
@Override
public void run() {
try {
if (server.init()) {
server.ab = MinecraftServer.az();
server.r.setServerInfo(new ServerPing.ServerData("1.8.8", 47));
Arrays.fill(server.recentTps, MinecraftServer.TPS);
long nextTickTime = System.nanoTime();
server.tickSection = nextTickTime;
server.lastTick = nextTickTime - MinecraftServer.TICK_TIME; // Paper
while (server.isRunning()) {
long currentTime = System.nanoTime();
long timeLeftForTick = nextTickTime - currentTime;
// Make sure process packets is called after the tick has started for accurate tick durations
if (timeLeftForTick <= 0) {
nextTickTime += TICK_TIME_IN_NANO;
nextTickTime = Math.max(nextTickTime, currentTime - MAX_CATCHUP_TIME);
server.startTick();
server.processTasks();
server.processLoginTasks();
server.A(); // tick server
server.endTick();
timeLeftForTick = nextTickTime - System.nanoTime(); // Recalculate time left for the next tick (this is needed if the tick took over 50 ms)
} else server.subTick(); // If we are not ticking just process packets + flush world changes (if enabled)
boolean maySleep = server.tasks.isEmpty() || !AzuriteConfig.processPacketsInBetweenTicks.getValue();
if (timeLeftForTick > SLEEP_MINIMUM_TIME && maySleep) {
// Only sleep if we don't have to do another tick within the sleep time & there are no new tasks
Thread.yield();
LockSupport.parkNanos(TIME_SLEEP);
}
}
} else {
server.a((CrashReport) null);
}
} catch (Throwable throwable) {
server.crash(throwable);
} finally {
try {
org.spigotmc.WatchdogThread.doStop();
server.isStopped = true;
server.stop();
} catch (Throwable throwable1) {
MinecraftServer.LOGGER.error("Exception stopping the server", throwable1);
} finally {
// CraftBukkit start - Restore terminal to original settings
try {
TerminalConsoleAppender.close();
} catch (Exception ignored) {
}
// CraftBukkit end
server.z();
}
}
}
}
@@ -0,0 +1,19 @@
package dev.azurite.spigot.utils;
import net.minecraft.server.Item;
import net.minecraft.server.PacketPlayInBlockPlace;
public class BlockPlaceSignature {
private final Item item;
private final long timestamp;
public BlockPlaceSignature(PacketPlayInBlockPlace packet) {
this.item = packet.getItemStack() == null ? null : packet.getItemStack().getItem();
this.timestamp = packet.timestamp;
}
public boolean matches(PacketPlayInBlockPlace packet) {
return Math.abs(packet.timestamp - this.timestamp) < 15 && packet.getItemStack() != null && packet.getItemStack().getItem() == this.item;
}
}
@@ -0,0 +1,52 @@
package dev.azurite.spigot.utils;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Copyright (c) 2024. Keano
* Use or redistribution of source or file is
* only permitted if given explicit permission.
*/
public class CC {
private static final String CONFIG_LINE_TOP = "================ ⚡ AzuriteSpigot ⚡ ================";
private static final String CONFIG_LINE_BOTTOM = "======================================================";
private static String center(String string) {
return StringUtils.center(string, CONFIG_LINE_TOP.length());
}
public static List<String> getConfigHeader(String... centerText) {
List<String> header = new ArrayList<>();
header.add(CONFIG_LINE_TOP);
header.add("");
for (String s : centerText) {
header.add(CC.center(s));
}
header.add("");
header.add(CONFIG_LINE_BOTTOM);
return header;
}
public static String t(String t) {
return ChatColor.translateAlternateColorCodes('&', t);
}
public static void sendMessage(CommandSender sender, String... strings) {
for (String string : strings) {
sender.sendMessage(CC.t(string));
}
}
public static List<String> t(List<String> t) {
return t.stream().map(CC::t).collect(Collectors.toList());
}
}
@@ -0,0 +1,36 @@
package dev.azurite.spigot.utils;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.LongAdder;
public class CachedSizeConcurrentLinkedQueue<E> extends ConcurrentLinkedQueue<E> {
private final LongAdder cachedSize = new LongAdder();
@Override
public boolean add(E e) {
boolean result = super.add(e);
if (result) {
cachedSize.increment();
}
return result;
}
@Override
public E poll() {
E result = super.poll();
if (result != null) {
cachedSize.decrement();
}
return result;
}
@Override
public int size() {
return cachedSize.intValue();
}
@Override
public boolean isEmpty() {
return cachedSize.intValue() == 0;
}
}
@@ -0,0 +1,94 @@
package dev.azurite.spigot.utils;
import net.minecraft.server.BiomeBase;
import net.minecraft.server.BlockPosition;
import net.minecraft.server.Blocks;
import net.minecraft.server.Chunk;
import net.minecraft.server.ChunkSnapshot;
import net.minecraft.server.EnumCreatureType;
import net.minecraft.server.EnumDirection;
import net.minecraft.server.IBlockData;
import net.minecraft.server.IChunkProvider;
import net.minecraft.server.IProgressUpdate;
import net.minecraft.server.World;
import java.util.Arrays;
import java.util.List;
public class ChunkProviderVoid implements IChunkProvider {
private final World world;
private final IBlockData air;
public ChunkProviderVoid(World world) {
air = Blocks.AIR.getBlockData();
(this.world = world).b(0);
}
public Chunk getOrCreateChunk(int i, int j) {
ChunkSnapshot chunksnapshot = new ChunkSnapshot();
for (int y = 0; y < 256; ++y) {
for (int x = 0; x < 16; ++x)
for (int z = 0; z < 16; ++z)
chunksnapshot.a(x, y, z, air);
}
Chunk chunk = new Chunk(this.world, chunksnapshot, i, j);
byte[] biomes = chunk.getBiomeIndex();
Arrays.fill(biomes, (byte) BiomeBase.MUSHROOM_ISLAND.id);
chunk.initLighting();
return chunk;
}
public boolean isChunkLoaded(int i, int j) {
return true;
}
public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) {
if (i == 0 && j == 0) {
this.world.setTypeUpdate(this.world.getSpawn().shift(EnumDirection.DOWN), Blocks.BEDROCK.getBlockData());
}
}
public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) {
return false;
}
public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) {
return true;
}
public void c() {
}
public boolean unloadChunks() {
return false;
}
public boolean canSave() {
return true;
}
public String getName() {
return "VoidLevelSource";
}
public List<BiomeBase.BiomeMeta> getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) {
return BiomeBase.MUSHROOM_ISLAND.getMobs(enumcreaturetype);
}
public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) {
return null;
}
public int getLoadedChunks() {
return 0;
}
public void recreateStructures(Chunk chunk, int i, int j) {
}
public Chunk getChunkAt(BlockPosition blockposition) {
return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4);
}
}
Loaded 100 of 2212 files, more files were not shown because too many files have changed in this diff. Show more