From 2323306c4f7d5bfc36236c46cb7f5fc01bfbc2f2 Mon Sep 17 00:00:00 2001 From: Patrick <147879351+WinniePatGG@users.noreply.github.com> Date: Fri, 1 May 2026 19:57:01 +0200 Subject: [PATCH] first commit --- .gitignore | 5 + LICENSE | 21 ++ README.md | 36 +++ build.gradle | 61 +++++ gradle.properties | 0 gradlew | 251 ++++++++++++++++++ gradlew.bat | 94 +++++++ settings.gradle | 1 + .../java/de/winniepat/clearLag/ClearLag.java | 42 +++ .../de/winniepat/clearLag/ConfigManager.java | 65 +++++ .../clearLag/commands/ClearLagCommand.java | 52 ++++ .../clearLag/commands/CommandManager.java | 20 ++ .../clearLag/listeners/EntityListener.java | 36 +++ .../clearLag/tasks/ClearLagTask.java | 140 ++++++++++ src/main/resources/config.yml | 23 ++ src/main/resources/plugin.yml | 16 ++ 16 files changed, 863 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 build.gradle create mode 100644 gradle.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/java/de/winniepat/clearLag/ClearLag.java create mode 100644 src/main/java/de/winniepat/clearLag/ConfigManager.java create mode 100644 src/main/java/de/winniepat/clearLag/commands/ClearLagCommand.java create mode 100644 src/main/java/de/winniepat/clearLag/commands/CommandManager.java create mode 100644 src/main/java/de/winniepat/clearLag/listeners/EntityListener.java create mode 100644 src/main/java/de/winniepat/clearLag/tasks/ClearLagTask.java create mode 100644 src/main/resources/config.yml create mode 100644 src/main/resources/plugin.yml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bae312e --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.gradle +.idea +build +gradle +srv \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..958ab94 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 WinniePatGG + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..64831b0 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# ClearLag Plugin for 1.21.4 + +[![Minecraft Version](https://img.shields.io/badge/Minecraft-1.21.4-green)](https://www.minecraft.net) +[![PaperMC Compatible](https://img.shields.io/badge/PaperMC-Compatible-blue)](https://papermc.io) + +## Features + +- ⚡ **Configurable automatic clearing** of entities (items, mobs, XP, projectiles, vehicles) +- 🛡️ **Filtering** with whitelist/blacklist for items +- 🧊 **Chunk entity limits** to prevent overcrowding +- ⏳ **Age-based clearing** to protect newly dropped items +- 💬 **Customizable messages** with color codes and placeholders +- 🔐 **Permission system** with bypass option +- 🐛 **Debug logging** for troubleshooting + +## Installation + +1. Download the latest version from [Releases](#) +2. Place the `ClearLag.jar` in your server's `plugins` folder +3. Restart your server +4. Configure the plugin by editing `plugins/ClearLag/config.yml` +5. Reload config with `/clearlag reload` (or restart server) + +## Commands + +| Command | Description | Permission | +|---------|-------------|------------| +| `/clearlag` | Show help menu | `clearlag.command` | +| `/clearlag now` | Clear entities immediately | `clearlag.command` | +| `/clearlag reload` | Reload the configuration | `clearlag.command` | + +## Permissions + +| Permission | Description | Default | +|------------|-------------|---------| +| `clearlag.command` | Allows use of all commands | op | diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..44cd1de --- /dev/null +++ b/build.gradle @@ -0,0 +1,61 @@ +plugins { + id 'java' + id("xyz.jpenilla.run-paper") version "2.3.1" +} + +group = 'de.winniepat' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + name = "papermc-repo" + url = "https://repo.papermc.io/repository/maven-public/" + } +} + +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") +} + +tasks { + runServer { + minecraftVersion("1.21") + } +} + +def targetJavaVersion = 21 +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + sourceCompatibility = javaVersion + targetCompatibility = javaVersion + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + options.release.set(targetJavaVersion) + } +} + +processResources { + def props = [version: version] + inputs.properties props + filteringCharset 'UTF-8' + filesMatching('plugin.yml') { + expand props + } +} + +tasks.register('copyPlugin', Copy) { + dependsOn build + from("$buildDir/libs") + include('*.jar') + into("$rootDir/srv/plugins") +} + +build.finalizedBy(copyPlugin) \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..e69de29 diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..58305a5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'ClearLag' diff --git a/src/main/java/de/winniepat/clearLag/ClearLag.java b/src/main/java/de/winniepat/clearLag/ClearLag.java new file mode 100644 index 0000000..c6c4ed5 --- /dev/null +++ b/src/main/java/de/winniepat/clearLag/ClearLag.java @@ -0,0 +1,42 @@ +package de.winniepat.clearLag; + +import de.winniepat.clearLag.commands.CommandManager; +import de.winniepat.clearLag.listeners.EntityListener; +import de.winniepat.clearLag.tasks.ClearLagTask; +import org.bukkit.plugin.java.JavaPlugin; + +public final class ClearLag extends JavaPlugin { + private ConfigManager configManager; + private ClearLagTask clearLagTask; + + @Override + public void onEnable() { + this.configManager = new ConfigManager(this); + configManager.setupConfig(); + + this.clearLagTask = new ClearLagTask(this); + clearLagTask.startScheduledTasks(); + + new CommandManager(this).registerCommands(); + + getServer().getPluginManager().registerEvents(new EntityListener(this), this); + + getLogger().info("ClearLagPlugin has been enabled!"); + } + + @Override + public void onDisable() { + if (clearLagTask != null) { + clearLagTask.cancelTasks(); + } + getLogger().info("ClearLagPlugin has been disabled!"); + } + + public ConfigManager getConfigManager() { + return configManager; + } + + public ClearLagTask getClearLagTask() { + return clearLagTask; + } +} \ No newline at end of file diff --git a/src/main/java/de/winniepat/clearLag/ConfigManager.java b/src/main/java/de/winniepat/clearLag/ConfigManager.java new file mode 100644 index 0000000..121603c --- /dev/null +++ b/src/main/java/de/winniepat/clearLag/ConfigManager.java @@ -0,0 +1,65 @@ +package de.winniepat.clearLag; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +import java.util.List; + +public class ConfigManager { + private final JavaPlugin plugin; + private FileConfiguration config; + + public ConfigManager(JavaPlugin plugin) { + this.plugin = plugin; + } + + public void setupConfig() { + plugin.saveDefaultConfig(); + this.config = plugin.getConfig(); + + config.addDefault("clear-interval", 300); + config.addDefault("auto-clear-enabled", true); + config.addDefault("max-entities-per-chunk", 25); + config.addDefault("prevent-spawns-when-full", true); + config.addDefault("clear-items", true); + config.addDefault("clear-mobs", true); + config.addDefault("clear-xp", true); + config.addDefault("clear-projectiles", true); + config.addDefault("clear-vehicles", true); + config.addDefault("item-whitelist", List.of("DIAMOND", "NETHERITE_INGOT")); + config.addDefault("item-blacklist", List.of("ROTTEN_FLESH", "COBBLESTONE")); + config.addDefault("item-min-age", 120); + config.addDefault("warning-message", "&cWarning: Clearing laggy entities in 10 seconds!"); + config.addDefault("cleared-message", "&aCleared &e%count% &aentities to reduce lag!"); + config.addDefault("spawn-prevent-message", "&cToo many entities in this chunk! Cannot spawn more."); + config.addDefault("debug", false); + config.addDefault("log-cleared-entities", false); + + config.options().copyDefaults(true); + plugin.saveConfig(); + } + + public FileConfiguration getConfig() { + return this.config; + } + + public void reloadConfig() { + plugin.reloadConfig(); + this.config = plugin.getConfig(); + } + + public int getClearInterval() { + return config.getInt("clear-interval"); + } + + public boolean isAutoClearEnabled() { + return config.getBoolean("auto-clear-enabled"); + } + + public boolean shouldPreventSpawnsWhenFull() { + return config.getBoolean("prevent-spawns-when-full"); + } + + public boolean shouldLogClearedEntities() { + return config.getBoolean("log-cleared-entities"); + } +} \ No newline at end of file diff --git a/src/main/java/de/winniepat/clearLag/commands/ClearLagCommand.java b/src/main/java/de/winniepat/clearLag/commands/ClearLagCommand.java new file mode 100644 index 0000000..3c6d5b4 --- /dev/null +++ b/src/main/java/de/winniepat/clearLag/commands/ClearLagCommand.java @@ -0,0 +1,52 @@ +package de.winniepat.clearLag.commands; + +import de.winniepat.clearLag.ClearLag; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; + +public class ClearLagCommand implements CommandExecutor, TabCompleter { + private final ClearLag plugin; + + public ClearLagCommand(ClearLag plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + if (args.length == 0) { + sender.sendMessage("§aClearLag Plugin Commands:"); + sender.sendMessage("§b/clearlag now §f- Clear entities now"); + sender.sendMessage("§b/clearlag reload §f- Reload the config"); + return true; + } + + switch (args[0].toLowerCase()) { + case "now": + int cleared = plugin.getClearLagTask().clearEntities(); + return true; + case "reload": + plugin.getConfigManager().reloadConfig(); + plugin.getClearLagTask().restartTasks(); + sender.sendMessage("§aConfig reloaded!"); + return true; + default: + return true; + } + } + + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + List completions = new ArrayList<>(); + if (args.length == 1) { + completions.add("now"); + completions.add("reload"); + } + return completions; + } +} \ No newline at end of file diff --git a/src/main/java/de/winniepat/clearLag/commands/CommandManager.java b/src/main/java/de/winniepat/clearLag/commands/CommandManager.java new file mode 100644 index 0000000..383a385 --- /dev/null +++ b/src/main/java/de/winniepat/clearLag/commands/CommandManager.java @@ -0,0 +1,20 @@ +package de.winniepat.clearLag.commands; + +import de.winniepat.clearLag.ClearLag; +import org.bukkit.command.PluginCommand; + +public class CommandManager { + private final ClearLag plugin; + + public CommandManager(ClearLag plugin) { + this.plugin = plugin; + } + + public void registerCommands() { + PluginCommand clearLagCommand = plugin.getCommand("clearlag"); + if (clearLagCommand != null) { + clearLagCommand.setExecutor(new ClearLagCommand(plugin)); + clearLagCommand.setTabCompleter(new ClearLagCommand(plugin)); + } + } +} \ No newline at end of file diff --git a/src/main/java/de/winniepat/clearLag/listeners/EntityListener.java b/src/main/java/de/winniepat/clearLag/listeners/EntityListener.java new file mode 100644 index 0000000..d70f330 --- /dev/null +++ b/src/main/java/de/winniepat/clearLag/listeners/EntityListener.java @@ -0,0 +1,36 @@ +package de.winniepat.clearLag.listeners; + +import de.winniepat.clearLag.ClearLag; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntitySpawnEvent; + +public class EntityListener implements Listener { + private final ClearLag plugin; + + public EntityListener(ClearLag plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onEntitySpawn(EntitySpawnEvent event) { + if (!plugin.getConfigManager().shouldPreventSpawnsWhenFull()) { + return; + } + + if (shouldPreventSpawn(event.getEntity())) { + event.setCancelled(true); + String message = plugin.getConfigManager().getConfig().getString("spawn-prevent-message"); + if (message != null && event.getEntity() instanceof Player player) { + player.sendMessage(message.replace('&', '§')); + } + } + } + + private boolean shouldPreventSpawn(Entity entity) { + int maxEntities = plugin.getConfigManager().getConfig().getInt("max-entities-per-chunk", 25); + return entity.getLocation().getChunk().getEntities().length >= maxEntities; + } +} \ No newline at end of file diff --git a/src/main/java/de/winniepat/clearLag/tasks/ClearLagTask.java b/src/main/java/de/winniepat/clearLag/tasks/ClearLagTask.java new file mode 100644 index 0000000..1fada8a --- /dev/null +++ b/src/main/java/de/winniepat/clearLag/tasks/ClearLagTask.java @@ -0,0 +1,140 @@ +package de.winniepat.clearLag.tasks; + +import de.winniepat.clearLag.ClearLag; +import org.bukkit.Bukkit; +import org.bukkit.entity.*; +import org.bukkit.scheduler.BukkitTask; +import java.util.List; +import java.util.stream.Collectors; + +public class ClearLagTask { + private final ClearLag plugin; + private BukkitTask clearTask; + private BukkitTask warningTask; + + public ClearLagTask(ClearLag plugin) { + this.plugin = plugin; + } + + public void startScheduledTasks() { + cancelTasks(); + + if (!plugin.getConfigManager().getConfig().getBoolean("auto-clear-enabled", true)) { + if (plugin.getConfigManager().getConfig().getBoolean("debug", false)) { + plugin.getLogger().info("Auto-clear is disabled in config"); + } + return; + } + + int interval = plugin.getConfigManager().getConfig().getInt("clear-interval", 300) * 20; + clearTask = Bukkit.getScheduler().runTaskTimer(plugin, this::startClearWarning, interval, interval); + + if (plugin.getConfigManager().getConfig().getBoolean("debug", false)) { + plugin.getLogger().info("[DEBUG] Scheduled clear task started with interval: " + interval + " ticks"); + } + } + + private void startClearWarning() { + String warningMessage = plugin.getConfigManager().getConfig().getString("warning-message"); + if (warningMessage != null && !warningMessage.isEmpty()) { + Bukkit.broadcastMessage(warningMessage.replace('&', '§')); + } + + warningTask = Bukkit.getScheduler().runTaskLater(plugin, () -> { + int cleared = clearEntities(); + sendClearedMessage(cleared); + }, 200); + } + + public int clearEntities() { + if (plugin.getConfigManager().getConfig().getBoolean("debug", false)) { + plugin.getLogger().info("Starting entity clearance..."); + } + + List whitelist = plugin.getConfigManager().getConfig().getStringList("item-whitelist"); + List blacklist = plugin.getConfigManager().getConfig().getStringList("item-blacklist"); + int minAge = plugin.getConfigManager().getConfig().getInt("item-min-age", 0) * 20; + long currentTick = Bukkit.getCurrentTick(); + + List entitiesToClear = Bukkit.getWorlds().stream() + .flatMap(world -> world.getEntities().stream()) + .filter(entity -> shouldClear(entity, whitelist, blacklist, minAge, currentTick)) + .collect(Collectors.toList()); + + entitiesToClear.forEach(Entity::remove); + + if (plugin.getConfigManager().getConfig().getBoolean("debug", false)) { + plugin.getLogger().info("Cleared " + entitiesToClear.size() + " entities"); + } + + return entitiesToClear.size(); + } + + private boolean shouldClear(Entity entity, List whitelist, List blacklist, int minAge, long currentTick) { + if (entity == null) return false; + + if (entity instanceof Player player && player.hasPermission("clearlag.bypass")) { + return false; + } + + if (minAge > 0 && entity instanceof Item item) { + if ((currentTick - item.getTicksLived()) < minAge) { + return false; + } + } + + if (entity instanceof Item item) { + String material = item.getItemStack().getType().toString(); + if (whitelist.contains(material)) { + return false; + } + if (blacklist.contains(material)) { + return true; + } + } + + return switch (entity.getType()) { + case ITEM -> plugin.getConfigManager().getConfig().getBoolean("clear-items", true); + case EXPERIENCE_ORB -> plugin.getConfigManager().getConfig().getBoolean("clear-xp", true); + case ARROW, SPECTRAL_ARROW, SNOWBALL, EGG, ENDER_PEARL, WITHER_SKULL, FIREBALL, DRAGON_FIREBALL, SHULKER_BULLET, LLAMA_SPIT -> + plugin.getConfigManager().getConfig().getBoolean("clear-projectiles", true); + case MINECART, CHEST_MINECART, FURNACE_MINECART, TNT_MINECART, HOPPER_MINECART, COMMAND_BLOCK_MINECART -> + plugin.getConfigManager().getConfig().getBoolean("clear-vehicles", false); + default -> plugin.getConfigManager().getConfig().getBoolean("clear-mobs", false) && isMob(entity.getType()); + }; + } + + private void sendClearedMessage(int count) { + String message = plugin.getConfigManager().getConfig().getString("cleared-message"); + if (message != null && !message.isEmpty()) { + Bukkit.broadcastMessage(message + .replace("%count%", String.valueOf(count)) + .replace('&', '§')); + } + } + + private boolean isMob(EntityType type) { + return switch (type) { + case ITEM, EXPERIENCE_ORB, AREA_EFFECT_CLOUD, PAINTING, ITEM_FRAME, + GLOW_ITEM_FRAME, END_CRYSTAL, EVOKER_FANGS, LEASH_KNOT, LIGHTNING_BOLT, + PLAYER, ARMOR_STAND -> false; + default -> type.isAlive(); + }; + } + + public void cancelTasks() { + if (clearTask != null) { + clearTask.cancel(); + clearTask = null; + } + if (warningTask != null) { + warningTask.cancel(); + warningTask = null; + } + } + + public void restartTasks() { + cancelTasks(); + startScheduledTasks(); + } +} \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..1996281 --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1,23 @@ +auto-clear-enabled: true +prevent-spawns-when-full: false +clear-projectiles: true +clear-vehicles: true +# Items to always clear +item-whitelist: + - DIAMOND + - NETHERITE_INGOT +# Items to never clear +item-blacklist: + - ROTTEN_FLESH + - COBBLESTONE +item-min-age: 120 +spawn-prevent-message: '&cToo many entities in this chunk! Cannot spawn more.' +debug: false +log-cleared-entities: false +clear-interval: 300 +max-entities-per-chunk: 25 +clear-items: true +clear-mobs: true +clear-xp: true +warning-message: Clearing laggy entities in 10 seconds! +cleared-message: Cleared %count% entities! diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..40f8083 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,16 @@ +name: ClearLag +version: '1.0-SNAPSHOT' +main: de.winniepat.clearLag.ClearLag +api-version: '1.21' +authors: [ WinniePatGG ] +description: ClearLag +website: https://winniepat.de +commands: + clearlag: + description: Control the ClearLag plugin + usage: /clearlag [now|reload] + permission: clearlag.command +permissions: + clearlag.command: + description: Allows use of ClearLag commands + default: op \ No newline at end of file