Compare commits

29 Commits
Author SHA1 Message Date
Len 4bd7b6a2cd Update to 26.2 2026-07-31 08:38:44 -05:00
Len 9a775b2702 Remove Java Toolchain 2026-07-31 08:32:18 -05:00
Len e65b4759b4 Update Gradle Stage in Jenkinsfile 2026-07-31 08:31:44 -05:00
Len f4320de479 Update gradle 2026-07-31 08:31:32 -05:00
stijn b60df9dc8d Fix frame iterator resetting mid run, improved logging
Frame iterator was resetting every run due to a shared iterator between runs, this is now unique per run.
Include frame keys for logging, log the frame spawning in debug logs.
2026-02-08 19:48:20 +01:00
stijn f6ee8eacf5 Change size type from int to float and remove validation for size greater than 1 in ParticleConfig 2026-02-07 23:25:32 +01:00
stijn caebd1fed3 Validate particle size 2026-02-07 22:50:23 +01:00
stijn 26cb4474c4 Refactor vanish handling by moving logic to FrameSpawnerPlayer and improving debug logging 2026-01-05 02:10:53 +01:00
stijn e2ab17fb20 Remove return statement in ParticleStorage (broke auto update) 2026-01-04 03:27:11 +01:00
stijn 5425b89b2b Fix color bug (argb <> rgb), fix particles defaulting to size 0 2026-01-04 03:22:40 +01:00
stijn d7c744c20b Refactor particle directory handling and enhance logging 2026-01-04 02:19:12 +01:00
stijn 26b1e6f46c Update Cosmos API dependency and configure Altitude snapshot repository 2025-12-27 23:29:51 +01:00
stijn 42c9530348 Refactor reload method and remove redundant debug logs 2025-07-15 21:12:27 +02:00
stijn ab86d77069 Automatically load particles that are added to or updated in the particles folder 2025-07-14 21:53:31 +02:00
auto 02c4f818a0 Adjust particle loading to work with webui coordinates 2025-06-23 00:45:07 +02:00
auto ed91cf6810 Add Jenkins pipeline for building, archiving, and sending Discord notifications 2025-06-22 23:38:21 +02:00
auto 8aa22a3e7a Add support for color gradients and sizes in particle configurations
Enhanced `ParticleConfig` to handle color gradients and sizes for particles with `DustOptions` and `DustTransition`. Updated `ParticleInfo` to include `colorGradientEnd` and `size` properties. Refactored particle data handling for improved flexibility.
2025-06-22 22:07:10 +02:00
auto 481cb007bf Correct directory name 2025-06-22 21:47:28 +02:00
auto fa14d001da Code cleanup 2025-06-22 21:45:51 +02:00
auto c163885345 Switched to cosmos (1.21.6) 2025-06-22 21:33:06 +02:00
auto 95bb1e90fe Refactor ParticleConfig with Jackson, add ParticleData models, and update dependencies
Replaced JSON-Simple with Jackson for particle configuration parsing. Introduced `ParticleData` and `ParticleInfo` models for structured data. Updated `ParticleConfig` structure for clarity and modularity. Added Jackson and Lombok dependencies in `build.gradle.kts`.
2025-06-22 21:30:14 +02:00
auto a3b4922b70 Refactor particle spawning logic into utility class.
Moved repetitive particle spawning code into a new `SpawnParticleUtil` class to improve readability and maintainability. Updated event listeners to use the utility, simplifying their implementations while preserving functionality.
2025-03-09 18:48:59 +01:00
auto 1caef4bb83 Update Gradle and Java versions, refactor, and fix enchantments
Upgraded Gradle to v8.5, updated Java language version to 21, and replaced the Shadow plugin. Deprecated `MaterialData` was removed. Fixed enchantment from ARROW_INFINITE to INFINITY in GUI and particle actions.
2025-01-18 18:13:58 +01:00
auto 1862288183 Update config file paths
The file paths for DatabaseConfig, ParticleConfig, and Config have been updated. They no longer depend on "user.home" system property, instead they directly point to "/mnt/configs" location. This change is necessary for aligning with the new configuration directories.
2024-07-20 00:19:21 +02:00
auto e33a9ff5b9 idk what this is sorry me 2024-07-20 00:19:08 +02:00
auto d416ec80e1 Added a way to load extra data for particles and added a boolean to determine if all frames should spawn at the same location 2022-09-07 22:39:48 +02:00
auto be97b45833 Fixed frames not properly repeating at the right speed 2022-08-31 05:13:18 +02:00
auto 77dcd8862c Fixed loading colors incorrectly 2022-08-31 05:12:55 +02:00
auto 867d436d0a Converted to json for particle storage 2022-08-30 05:19:05 +02:00
44 changed files with 1207 additions and 812 deletions
Vendored
+26
View File
@@ -0,0 +1,26 @@
pipeline {
agent any
stages {
stage('Gradle') {
steps {
withCredentials([usernamePassword(credentialsId: 'alttd-snapshot-user', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
sh '''
set +x
chmod +x gradlew
./gradlew build -PalttdSnapshotUsername=$USERNAME -PalttdSnapshotPassword=$PASSWORD
'''
}
}
}
stage('Archive') {
steps {
archiveArtifacts artifacts: 'build/libs/', followSymlinks: false
}
}
stage('discord') {
steps {
discordSend description: "Build: ${BUILD_NUMBER}", showChangeset: true, result: currentBuild.currentResult, title: currentBuild.fullProjectName, webhookURL: env.discordwebhook
}
}
}
}
+16 -19
View File
@@ -1,22 +1,14 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
plugins { plugins {
id("java") id("java")
id("com.github.johnrengelman.shadow") version "7.1.0" id("com.gradleup.shadow") version "9.6.1"
} }
group = "com.alttd" group = "com.alttd"
version = "1.0.0-SNAPSHOT" version = System.getenv("BUILD_NUMBER") ?: "1.0.0-SNAPSHOT"
description = "Altitude Particles plugin." description = "Altitude Particles plugin."
apply<JavaLibraryPlugin>() apply<JavaLibraryPlugin>()
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
tasks { tasks {
withType<JavaCompile> { withType<JavaCompile> {
options.encoding = Charsets.UTF_8.name() options.encoding = Charsets.UTF_8.name()
@@ -27,8 +19,8 @@ tasks {
} }
shadowJar { shadowJar {
dependsOn(getByName("relocateJars") as ConfigureShadowRelocation) // archiveFileName.set("${project.name}-${project.version}.jar")
archiveFileName.set("${project.name}-${project.version}.jar") archiveFileName.set("${project.name}.jar")
minimize() minimize()
configurations = listOf(project.configurations.shadow.get()) configurations = listOf(project.configurations.shadow.get())
} }
@@ -36,14 +28,19 @@ tasks {
build { build {
dependsOn(shadowJar) dependsOn(shadowJar)
} }
create<ConfigureShadowRelocation>("relocateJars") {
target = shadowJar.get()
prefix = "${project.name}.lib"
}
} }
dependencies { dependencies {
compileOnly("com.alttd:Galaxy-API:1.19-R0.1-SNAPSHOT") // Cosmos
compileOnly("com.github.LeonMangler:PremiumVanishAPI:2.7.11-2") compileOnly("com.alttd.cosmos:cosmos-api:26.2.build.17-stable")
// Lombok
compileOnly("org.projectlombok:lombok:1.18.38")
annotationProcessor("org.projectlombok:lombok:1.18.38")
// Premium vanish
compileOnly("com.github.LeonMangler:PremiumVanishAPI:2.9.0-4")
// Jackson/Dynamic Beans Integration
implementation("com.fasterxml.jackson.module:jackson-module-parameter-names:2.15.2")
// Jackson for JSON Parsing
implementation("com.fasterxml.jackson.core:jackson-databind:2.15.2")
implementation("com.fasterxml.jackson.core:jackson-annotations:2.15.2")
} }
Binary file not shown.
+3 -1
View File
@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored
+179 -116
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,81 +15,114 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # 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/b631911858264c0b6e4d6603d677ff5218766cee/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 # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" # This is normally unused
APP_BASE_NAME=`basename "$0"` # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 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. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -98,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 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 Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
MAX_FD="$MAX_FD_LIMIT" # shellcheck disable=SC2039,SC3045
fi MAX_FD=$( ulimit -H -n ) ||
ulimit -n $MAX_FD warn "Could not query maximum file descriptor limit"
if [ $? -ne 0 ] ; then esac
warn "Could not set maximum file descriptor limit: $MAX_FD" case $MAX_FD in #(
fi '' | soft) :;; #(
else *)
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
fi # shellcheck disable=SC2039,SC3045
fi ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
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" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@" exec "$JAVACMD" "$@"
Vendored
+20 -16
View File
@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@@ -26,6 +28,7 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -56,32 +59,33 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
+19
View File
@@ -1,9 +1,28 @@
import org.gradle.kotlin.dsl.maven
val nexusUser = providers.gradleProperty("alttdSnapshotUsername").orNull ?: System.getenv("NEXUS_USERNAME")
val nexusPass = providers.gradleProperty("alttdSnapshotPassword").orNull ?: System.getenv("NEXUS_PASSWORD")
rootProject.name = "AltitudeParticles" rootProject.name = "AltitudeParticles"
dependencyResolutionManagement { dependencyResolutionManagement {
repositories { repositories {
mavenLocal() mavenLocal()
mavenCentral() mavenCentral()
maven {
url = uri("https://repo.alttd.com/repository/alttd-snapshot/")
credentials {
username = nexusUser
password = nexusPass
}
}
maven {
url = uri("https://repo.alttd.com/repository/alttd/")
credentials {
username = nexusUser
password = nexusPass
}
}
maven("https://repo.destro.xyz/snapshots") // Galaxy maven("https://repo.destro.xyz/snapshots") // Galaxy
maven("https://papermc.io/repo/repository/maven-public/") // Paper maven("https://papermc.io/repo/repository/maven-public/") // Paper
maven("https://jitpack.io") //PremiumVanish maven("https://jitpack.io") //PremiumVanish
+29 -6
View File
@@ -1,25 +1,28 @@
package com.alttd; package com.alttd;
import com.alttd.commands.CommandManager; import com.alttd.commands.CommandManager;
import com.alttd.commands.subcommands.CommandReload;
import com.alttd.config.Config; import com.alttd.config.Config;
import com.alttd.config.DatabaseConfig; import com.alttd.config.DatabaseConfig;
import com.alttd.config.ParticleConfig; import com.alttd.config.ParticleConfig;
import com.alttd.database.Database; import com.alttd.database.Database;
import com.alttd.listeners.*; import com.alttd.listeners.*;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.particles.InitParticles; import com.alttd.storage.AutoReload;
import com.alttd.util.Logger; import com.alttd.util.Logger;
import lombok.Getter;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
public class AltitudeParticles extends JavaPlugin { public class AltitudeParticles extends JavaPlugin {
@Getter
public static AltitudeParticles instance; public static AltitudeParticles instance;
public static AltitudeParticles getInstance() { private static AutoReload autoReload = null;
return instance;
}
@Override @Override
public void onLoad() { public void onLoad() {
@@ -32,7 +35,6 @@ public class AltitudeParticles extends JavaPlugin {
Database.getDatabase().init(); Database.getDatabase().init();
new CommandManager(); new CommandManager();
registerEvents(); registerEvents();
InitParticles.init();
Logger.info("--------------------------------------------------"); Logger.info("--------------------------------------------------");
Logger.info("Altitude Particles started"); Logger.info("Altitude Particles started");
Logger.info("--------------------------------------------------"); Logger.info("--------------------------------------------------");
@@ -51,9 +53,30 @@ public class AltitudeParticles extends JavaPlugin {
} }
public void reload() { public void reload() {
Logger.info("Reloading AltitudeParticles...");
Config.reload(); Config.reload();
DatabaseConfig.reload(); DatabaseConfig.reload();
ParticleConfig.reload(); ParticleConfig.reload();
startAutoReload();
}
private static void startAutoReload() {
Path path = Path.of(Config.AUTO_RELOAD_PATH);
File file = path.toFile();
if (file.exists() && file.isDirectory()) {
try {
if (autoReload != null) {
autoReload.stop();
}
autoReload = new AutoReload(path);
autoReload.startWatching();
} catch (IOException e) {
Logger.severe("Failed to start AutoReload at path %", Config.AUTO_RELOAD_PATH);
Logger.error("Failed to start AutoReload", e);
}
} else {
Logger.severe("Failed to start AutoReload at path %", Config.AUTO_RELOAD_PATH);
}
} }
} }
@@ -6,6 +6,7 @@ import com.alttd.commands.subcommands.CommandHelp;
import com.alttd.commands.subcommands.CommandReload; import com.alttd.commands.subcommands.CommandReload;
import com.alttd.config.Config; import com.alttd.config.Config;
import com.alttd.util.Logger; import com.alttd.util.Logger;
import lombok.Getter;
import org.bukkit.command.*; import org.bukkit.command.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -13,8 +14,8 @@ import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@Getter
public class CommandManager implements CommandExecutor, TabExecutor { public class CommandManager implements CommandExecutor, TabExecutor {
private final List<SubCommand> subCommands; private final List<SubCommand> subCommands;
@@ -45,7 +46,7 @@ public class CommandManager implements CommandExecutor, TabExecutor {
subCommand = getSubCommand(args[0]); subCommand = getSubCommand(args[0]);
if (!commandSender.hasPermission(subCommand.getPermission())) { if (!commandSender.hasPermission(subCommand.getPermission())) {
commandSender.sendMiniMessage(Config.NO_PERMISSION, null); commandSender.sendRichMessage(Config.NO_PERMISSION);
return true; return true;
} }
@@ -61,7 +62,7 @@ public class CommandManager implements CommandExecutor, TabExecutor {
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission())) .filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getName) .map(SubCommand::getName)
.filter(name -> args.length == 0 || name.startsWith(args[0])) .filter(name -> args.length == 0 || name.startsWith(args[0]))
.collect(Collectors.toList()) .toList()
); );
} else { } else {
SubCommand subCommand = getSubCommand(args[0]); SubCommand subCommand = getSubCommand(args[0]);
@@ -71,10 +72,6 @@ public class CommandManager implements CommandExecutor, TabExecutor {
return res; return res;
} }
public List<SubCommand> getSubCommands() {
return subCommands;
}
private SubCommand getSubCommand(String cmdName) { private SubCommand getSubCommand(String cmdName) {
return subCommands.stream() return subCommands.stream()
.filter(subCommand -> subCommand.getName().equals(cmdName)) .filter(subCommand -> subCommand.getName().equals(cmdName))
@@ -14,7 +14,7 @@ public class CommandGUI extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
if (!(commandSender instanceof Player player)) { if (!(commandSender instanceof Player player)) {
commandSender.sendMiniMessage(Config.NO_CONSOLE, null); commandSender.sendRichMessage(Config.NO_CONSOLE);
return true; return true;
} }
new OpenParticleGUI(player).open(player); new OpenParticleGUI(player).open(player);
@@ -20,11 +20,11 @@ public class CommandHelp extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
commandSender.sendMiniMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", commandManager commandSender.sendRichMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", commandManager
.getSubCommands().stream() .getSubCommands().stream()
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission())) .filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getHelpMessage) .map(SubCommand::getHelpMessage)
.collect(Collectors.joining("\n"))), null); .collect(Collectors.joining("\n"))));
return true; return true;
} }
@@ -3,8 +3,6 @@ package com.alttd.commands.subcommands;
import com.alttd.AltitudeParticles; import com.alttd.AltitudeParticles;
import com.alttd.commands.SubCommand; import com.alttd.commands.SubCommand;
import com.alttd.config.Config; import com.alttd.config.Config;
import com.alttd.config.DatabaseConfig;
import com.alttd.config.ParticleConfig;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.ArrayList; import java.util.ArrayList;
@@ -15,7 +13,7 @@ public class CommandReload extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
AltitudeParticles.getInstance().reload(); AltitudeParticles.getInstance().reload();
commandSender.sendMiniMessage("<green>Reloaded AltitudeParticles config.</green>", null); commandSender.sendRichMessage("<green>Reloaded AltitudeParticles config.</green>");
return true; return true;
} }
@@ -55,7 +55,7 @@ abstract class AbstractConfig {
throw new RuntimeException(ex.getCause()); throw new RuntimeException(ex.getCause());
} catch (Exception ex) { } catch (Exception ex) {
Logger.severe("Error invoking %.", method.toString()); Logger.severe("Error invoking %.", method.toString());
ex.printStackTrace(); Logger.error("Failed to invoke", ex);
} }
} }
} }
@@ -69,7 +69,7 @@ abstract class AbstractConfig {
yaml.save(file); yaml.save(file);
} catch (IOException ex) { } catch (IOException ex) {
Logger.severe("Could not save %.", file.toString()); Logger.severe("Could not save %.", file.toString());
ex.printStackTrace(); Logger.error("Failed to save", ex);
} }
} }
+7 -1
View File
@@ -2,12 +2,13 @@ package com.alttd.config;
import java.io.File; import java.io.File;
@SuppressWarnings("unused")
public final class Config extends AbstractConfig { public final class Config extends AbstractConfig {
static Config config; static Config config;
static int version; static int version;
public Config() { public Config() {
super(new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "AltitudeParticles"), "config.yml"); super(new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "AltitudeParticles"), "config.yml");
} }
public static void reload() { public static void reload() {
@@ -97,4 +98,9 @@ public final class Config extends AbstractConfig {
CLICK_BLOCK_COOL_DOWN = config.getInt("cool_down.click-block", CLICK_BLOCK_COOL_DOWN); CLICK_BLOCK_COOL_DOWN = config.getInt("cool_down.click-block", CLICK_BLOCK_COOL_DOWN);
TELEPORT_ARRIVE_COOL_DOWN = config.getInt("cool_down.teleport-arrive", TELEPORT_ARRIVE_COOL_DOWN); TELEPORT_ARRIVE_COOL_DOWN = config.getInt("cool_down.teleport-arrive", TELEPORT_ARRIVE_COOL_DOWN);
} }
public static String AUTO_RELOAD_PATH = "/mnt/configs/AltitudeParticles/particles";
private static void loadAutoReload() {
AUTO_RELOAD_PATH = config.getString("auto-reload.path", AUTO_RELOAD_PATH);
}
} }
@@ -1,14 +1,13 @@
package com.alttd.config; package com.alttd.config;
import com.alttd.database.Database;
import java.io.File; import java.io.File;
@SuppressWarnings("unused")
public class DatabaseConfig extends AbstractConfig { public class DatabaseConfig extends AbstractConfig {
static DatabaseConfig config; static DatabaseConfig config;
public DatabaseConfig() { public DatabaseConfig() {
super(new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" super(new File(File.separator + "mnt" + File.separator + "configs"
+ File.separator + "AltitudeParticles"), "database.yml"); + File.separator + "AltitudeParticles"), "database.yml");
} }
@@ -1,111 +1,283 @@
package com.alttd.config; package com.alttd.config;
import com.alttd.objects.APartType; import com.alttd.models.ParticleData;
import com.alttd.models.ParticleInfo;
import com.alttd.objects.AParticle; import com.alttd.objects.AParticle;
import com.alttd.objects.Frame; import com.alttd.objects.Frame;
import com.alttd.objects.ParticleSet; import com.alttd.objects.ParticleSet;
import com.alttd.storage.ParticleStorage; import com.alttd.storage.ParticleStorage;
import com.alttd.util.Logger; import com.alttd.util.Logger;
import com.destroystokyo.paper.ParticleBuilder; import com.destroystokyo.paper.ParticleBuilder;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.bukkit.Color;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Particle; import org.bukkit.Particle;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.block.data.BlockData;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.io.IOException;
import java.util.Arrays; import java.nio.file.*;
import java.util.List; import java.nio.file.attribute.BasicFileAttributes;
import java.util.stream.Collectors; import java.util.*;
public class ParticleConfig extends AbstractConfig { @Slf4j
public class ParticleConfig {
static ParticleConfig config; private static final int MAX_DEPTH = 2;
public ParticleConfig() { private static final File particlesDir = new File(File.separator + "mnt" + File.separator + "configs"
super(new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "AltitudeParticles"), "particles.yml"); + File.separator + "AltitudeParticles" + File.separator + "particles");
private static ParticleConfig instance = null;
private static final ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
}
private static ParticleConfig getInstance() {
if (instance == null)
instance = new ParticleConfig();
return instance;
}
/**
* Finds all files in particles directory that are valid .json files
* Only searches one level deep into subdirectories
*
* @return all files found
*/
private List<File> getJsonFiles() {
List<File> files = new ArrayList<>();
if (!ensureParticlesDirectoryExists()) {
log.debug("Particles directory missing or not creatable: {}", particlesDir.getAbsolutePath());
return files;
}
log.debug("Traversing particles directory: {} (exists={}, isDirectory={})", particlesDir.getAbsolutePath(),
particlesDir.exists(), particlesDir.isDirectory());
try {
Files.walkFileTree(particlesDir.toPath(),
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
ParticleConfig.MAX_DEPTH,
getJsonFileVistor(files));
} catch (IOException e) {
log.error("Error while traversing directory: {}", e.getMessage(), e);
}
log.info("Found {} json files in particles directory", files.size());
return files;
}
private FileVisitor<? super @NotNull Path> getJsonFileVistor(List<File> files) {
return new SimpleFileVisitor<>() {
@Override
public @NotNull FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) {
log.debug("preVisitDirectory: {}", dir.toAbsolutePath());
return FileVisitResult.CONTINUE;
}
@Override
public @NotNull FileVisitResult visitFile(@NotNull Path file, @NotNull BasicFileAttributes attrs) {
if (!attrs.isRegularFile()) {
log.debug("Skipping non-regular file path: {} (isDirectory={}, isOther={})", file.toAbsolutePath(), attrs.isDirectory(), attrs.isOther());
return FileVisitResult.CONTINUE;
}
File physicalFile = file.toFile();
log.debug("visitFile: {} (isFile={}, canRead={}, name={})", physicalFile.getAbsolutePath(), physicalFile.isFile(), physicalFile.canRead(), physicalFile.getName());
if (isValidJsonFile(physicalFile)) {
log.debug("Found JSON file: {}", physicalFile.getAbsolutePath());
files.add(physicalFile);
} else {
log.debug("Ignoring non-json or unreadable file: {}", physicalFile.getAbsolutePath());
}
return FileVisitResult.CONTINUE;
}
@Override
public @NotNull FileVisitResult postVisitDirectory(@NotNull Path dir, IOException exc) {
log.debug("postVisitDirectory: {}", dir.toAbsolutePath());
return FileVisitResult.CONTINUE;
}
};
}
/**
* Ensures that the particles directory exists and is a directory
*
* @return true if directory exists or was created successfully, false otherwise
*/
private boolean ensureParticlesDirectoryExists() {
if (!particlesDir.exists()) {
log.info("Particles directory does not exist, attempting to create: {}", particlesDir.getAbsolutePath());
if (!particlesDir.mkdirs()) {
Logger.warning("Unable to create particles directory at {}", particlesDir.getAbsolutePath());
return false;
}
log.info("Created particles directory at {}", particlesDir.getAbsolutePath());
return true;
}
if (!particlesDir.isDirectory()) {
Logger.warning("Particles path exists but is not a directory: {}", particlesDir.getAbsolutePath());
return false;
}
return true;
}
/**
* Checks if a file is a valid JSON file
*
* @param file the file to check
* @return true if the file is a valid JSON file
*/
private boolean isValidJsonFile(File file) {
return file.isFile() && file.canRead() && file.getName().endsWith(".json");
}
/**
* Converts a ParticleData object to a ParticleSet
*
* @param particleData The ParticleData object to convert
* @return A ParticleSet created from the ParticleData
*/
public ParticleSet convertToParticleSet(ParticleData particleData) {
log.info("Converting ParticleData to ParticleSet for [{}]", particleData.getParticleName());
List<Frame> loadedFrames = new ArrayList<>();
double randomOffset = particleData.getRandomOffset();
// Process each frame
for (Map.Entry<String, List<ParticleInfo>> entry : particleData.getFrames().entrySet()) {
List<AParticle> aParticleList = new ArrayList<>();
// Process each particle in the frame
for (ParticleInfo particleInfo : entry.getValue()) {
Particle particleType = Particle.valueOf(particleInfo.getParticleType());
double x = particleInfo.getX();
double y = particleInfo.getY();
double z = particleInfo.getZ();
ParticleBuilder particleBuilder = new ParticleBuilder(particleType);
Class<?> dataType = particleType.getDataType();
// Handle different particle data types
setParticleType(particleInfo, dataType, particleBuilder);
//Add 0.2 to adjust for the player model being 1.6 blocks high
aParticleList.add(new AParticle(x, y + 0.2, z, randomOffset, particleBuilder));
}
loadedFrames.add(new Frame(entry.getKey(), aParticleList));
}
if (Config.DEBUG) {
log.info("Loaded {} frames for [{}]", loadedFrames.size(), particleData.getParticleName());
}
// Create and return the ParticleSet
ItemStack displayItem = new ItemStack(Material.valueOf(particleData.getDisplayItem()));
return new ParticleSet(
loadedFrames,
particleData.getDisplayName(),
List.of(particleData.getLore().split("\n")),
particleData.getFrameDelay(),
particleData.getRepeat(),
particleData.getRepeatDelay(),
particleData.isStationary(),
particleData.getAPartType(),
particleData.getParticleName(),
particleData.getPermission(),
particleData.getPackagePermission(),
displayItem
);
}
private void setParticleType(ParticleInfo particleInfo, Class<?> dataType, ParticleBuilder particleBuilder) {
String color = particleInfo.getColor();
if (dataType.equals(Particle.DustOptions.class)) {
if (color != null) {
particleBuilder.color(getColor(color),
particleInfo.getSize());
log.info("Dust particle color: {} with size: {}", color, particleInfo.getSize());
} else {
log.error("Dust particle must have a color");
}
} else if (dataType.equals(Particle.DustTransition.class)) {
if (color == null || particleInfo.getColorGradientEnd() != null) {
particleBuilder.colorTransition(getColor(color),
getColor(particleInfo.getColorGradientEnd()),
particleInfo.getSize());
log.info("Dust transition particle color start: {} with size: {}", color, particleInfo.getSize());
} else {
log.error("Dust transition particle must have a color gradient start and end");
}
}
else if (dataType.equals(Color.class)) {
particleBuilder.color(getColor(color));
} else if (dataType.equals(BlockData.class)) {
particleBuilder.data(Material.STONE.createBlockData());
log.warn("Block data particles are not yet supported");
//TODO implement
} else if (dataType.equals(Integer.class)) {
particleBuilder.data(1);
log.warn("Integer data particles are not yet supported");
//TODO implement
} else if (dataType.equals(Float.class)) {
particleBuilder.data(1f);
log.warn("Float data particles are not yet supported");
//TODO implement
} else if (dataType.equals(ItemStack.class)) {
particleBuilder.data(new ItemStack(Material.STONE));
log.warn("ItemStack data particles are not yet supported");
//TODO implement
} else if (particleInfo.getExtra() != null) {
particleBuilder.extra(particleInfo.getExtra());
} else {
log.debug("No relevant data type: {}", dataType.getName());
}
}
private Color getColor(String hexColor) {
int hexFormatColor = HexFormat.fromHexDigits(hexColor);
Color color;
if (hexColor.length() == 6) {
color = Color.fromRGB(hexFormatColor);
} else {
color = Color.fromARGB(hexFormatColor);
}
return color;
} }
public static void reload() { public static void reload() {
config = new ParticleConfig();
config.readConfig(config.getClass(), null);
}
private static void loadParticles() {
ParticleStorage.clear(); ParticleStorage.clear();
ConfigurationSection particles = config.getConfigurationSection("particles"); instance = getInstance();
if (particles == null) { log.info("Reloading particles...");
Logger.warning("No particles in particles config");
return; for (File file : instance.getJsonFiles()) {
loadParticleFromFile(file);
} }
for (String key : particles.getKeys(false)) { }
ConfigurationSection cs = particles.getConfigurationSection(key);
if (cs == null) public static void loadParticleFromFile(File file) {
continue; instance = getInstance();
APartType aPartType;
ParticleSet particleSet;
try { try {
aPartType = APartType.valueOf(cs.getString("part-type")); ParticleData particleData = objectMapper.readValue(file, ParticleData.class);
particleSet = new ParticleSet(
getAParticle(cs),
cs.getString("name"),
cs.getStringList("lore"),
cs.getInt("frame-delay"),
cs.getInt("repeat"),
cs.getInt("repeat-delay"),
aPartType,
cs.getString("unique-name"),
cs.getString("permission"),
cs.getString("package-permission"),
new ItemStack(Material.valueOf(cs.getString("material"))));
} catch (Exception e) {//Im lazy rn sorry
e.printStackTrace();
continue;
}
ParticleStorage.addParticleSet(aPartType, particleSet);
}
}
private static List<Frame> getAParticle(ConfigurationSection configurationSection) { ParticleSet particleSet = instance.convertToParticleSet(particleData);
List<Frame> list = new ArrayList<>();
ConfigurationSection frames = configurationSection.getConfigurationSection("frames");
if (frames == null) {
Logger.warning("Unable to find frames for something");
return null;
}
for (String key : frames.getKeys(false)) {
ConfigurationSection cs = frames.getConfigurationSection(key);
if (cs == null) {
Logger.warning("Unable to load particle %", key);
return null;
}
int offset = frames.getInt("offset-range");
List<AParticle> aParticleList = new ArrayList<>();
List<Double> x = Arrays.stream(cs.getString("x").split(", ")).map(Double::valueOf).collect(Collectors.toList());
List<Double> y = Arrays.stream(cs.getString("y").split(", ")).map(Double::valueOf).collect(Collectors.toList());
List<Double> z = Arrays.stream(cs.getString("z").split(", ")).map(Double::valueOf).collect(Collectors.toList());
if (x.size() != y.size() || y.size() != z.size()) {
Logger.warning("Unable to load % xyz is not the same length", key);
}
ParticleBuilder particleBuilder = getParticleBuilder(cs);
for (int i = 0; i < x.size(); i++) {
aParticleList.add(new AParticle(x.get(i), y.get(i), z.get(i), offset, particleBuilder));
}
list.add(new Frame(aParticleList));
}
return list;
}
private static ParticleBuilder getParticleBuilder(ConfigurationSection cs) { ParticleStorage.addParticleSet(particleSet.getAPartType(), particleSet);
cs.getString("particle"); } catch (IOException e) {
ConfigurationSection color = cs.getConfigurationSection("color"); Logger.error("Error reading particle file " + file.getName(), e);
ParticleBuilder particle = new ParticleBuilder(Particle.valueOf(cs.getString("particle"))); } catch (Exception exception) {
// Class<?> dataType = particle.particle().getDataType(); Logger.error("Error processing particle file " + file.getName(), exception);
// Logger.warning(dataType.getSimpleName()); }
particle.extra(cs.getDouble("extra"));
if (color != null) {
particle = particle.color(color.getInt("r"), color.getInt("g"), color.getInt("b"));
}
return particle.count(cs.getInt("count", 1));
} }
} }
+20 -18
View File
@@ -24,7 +24,7 @@ public class Database {
try { try {
openConnection(); openConnection();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error("Unable to open connection", e);
} }
// Tables // Tables
@@ -48,7 +48,7 @@ public class Database {
try { try {
Class.forName("com.mysql.cj.jdbc.Driver"); Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); Logger.error("Error while trying to open connection", e);
} }
connection = DriverManager.getConnection( connection = DriverManager.getConnection(
@@ -66,7 +66,7 @@ public class Database {
try { try {
instance.openConnection(); instance.openConnection();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); Logger.error("Error while trying to get connection", e);
} }
return connection; return connection;
@@ -74,15 +74,17 @@ public class Database {
private static void createActiveParticlesTable() { private static void createActiveParticlesTable() {
try { try {
String sql = "CREATE TABLE IF NOT EXISTS active_particles(" + String sql = """
"uuid VARCHAR(36) NOT NULL, " + CREATE TABLE IF NOT EXISTS active_particles(
"particle_type VARCHAR(36) NOT NULL, " + uuid VARCHAR(36) NOT NULL,
"particle_id VARCHAR(36) NOT NULL, " + particle_type VARCHAR(36) NOT NULL,
"PRIMARY KEY (uuid, particle_type)" + particle_id VARCHAR(36) NOT NULL,
")"; PRIMARY KEY (uuid, particle_type)
)""";
connection.prepareStatement(sql).executeUpdate(); connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error("Error while trying to create user point table", e);
Logger.severe("Error while trying to create user point table"); Logger.severe("Error while trying to create user point table");
Logger.severe("Shutting down AltitudeParticles"); Logger.severe("Shutting down AltitudeParticles");
Bukkit.getPluginManager().disablePlugin(AltitudeParticles.getInstance()); Bukkit.getPluginManager().disablePlugin(AltitudeParticles.getInstance());
@@ -91,16 +93,16 @@ public class Database {
private static void createUserSettingsTable() { private static void createUserSettingsTable() {
try { try {
String sql = "CREATE TABLE IF NOT EXISTS user_settings(" + String sql = """
"uuid VARCHAR(36) NOT NULL, " + CREATE TABLE IF NOT EXISTS user_settings(
"particles_active BIT(1) NOT NULL DEFAULT b'1', " + uuid VARCHAR(36) NOT NULL,
"seeing_particles BIT(1) NOT NULL DEFAULT b'1', " + particles_active BIT(1) NOT NULL DEFAULT b'1',
"PRIMARY KEY (uuid)" + seeing_particles BIT(1) NOT NULL DEFAULT b'1',
")"; PRIMARY KEY (uuid)
)""";
connection.prepareStatement(sql).executeUpdate(); connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error("Error while trying to create user point table", e);
Logger.severe("Error while trying to create user point table");
Logger.severe("Shutting down AltitudeParticles"); Logger.severe("Shutting down AltitudeParticles");
Bukkit.getPluginManager().disablePlugin(AltitudeParticles.getInstance()); Bukkit.getPluginManager().disablePlugin(AltitudeParticles.getInstance());
} }
+46 -44
View File
@@ -16,44 +16,44 @@ import java.util.UUID;
public class Queries { public class Queries {
public static void setSeeingParticles(UUID uuid, boolean seeingParticles) { public static void setSeeingParticles(UUID uuid, boolean seeingParticles) {
String sql = "UPDATE user_settings " + String sql = """
"SET seeing_particles = ?" + UPDATE user_settings
"WHERE uuid = ?"; SET seeing_particles = ?
WHERE uuid = ?""";
try { try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql);
preparedStatement.setInt(1, seeingParticles ? 1 : 0); preparedStatement.setInt(1, seeingParticles ? 1 : 0);
preparedStatement.setString(2, uuid.toString()); preparedStatement.setString(2, uuid.toString());
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to set seeing particles for %s", uuid.toString()), e);
} }
} }
public static void setParticlesActive(UUID uuid, boolean particlesActive) { public static void setParticlesActive(UUID uuid, boolean particlesActive) {
String sql = "UPDATE user_settings " + String sql = """
"SET particles_active = ?" + UPDATE user_settings
"WHERE uuid = ?"; SET particles_active = ?
WHERE uuid = ?""";
try { try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql);
preparedStatement.setInt(1, particlesActive ? 1 : 0); preparedStatement.setInt(1, particlesActive ? 1 : 0);
preparedStatement.setString(2, uuid.toString()); preparedStatement.setString(2, uuid.toString());
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to set particles for %s", uuid.toString()), e);
} }
} }
public static void addParticle(UUID uuid, APartType aPartType, String particleId) { public static void addParticle(UUID uuid, APartType aPartType, String particleId) {
String sql = "INSERT INTO active_particles (uuid, particle_type, particle_id) " + String sql = """
"VALUES (?, ?, ?) " + INSERT INTO active_particles (uuid, particle_type, particle_id)
"ON DUPLICATE KEY UPDATE particle_id = ?"; VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE particle_id = ?""";
try { try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql);
preparedStatement.setString(1, uuid.toString()); preparedStatement.setString(1, uuid.toString());
preparedStatement.setString(2, aPartType.getName()); preparedStatement.setString(2, aPartType.getName());
preparedStatement.setString(3, particleId); preparedStatement.setString(3, particleId);
@@ -61,43 +61,45 @@ public class Queries {
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to add particle for %s", uuid.toString()), e);
} }
} }
public static void removeParticle(UUID uuid, APartType aPartType) { public static void removeParticle(UUID uuid, APartType aPartType) {
String sql = "DELETE FROM active_particles " + String sql = """
"WHERE uuid = ? " + DELETE FROM active_particles
"AND particle_type = ?"; WHERE uuid = ?
AND particle_type = ?""";
try { try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql);
preparedStatement.setString(1, uuid.toString()); preparedStatement.setString(1, uuid.toString());
preparedStatement.setString(2, aPartType.getName()); preparedStatement.setString(2, aPartType.getName());
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to remove particles for %s", uuid.toString()), e);
} }
} }
public static void clearParticles(UUID uuid) { public static void clearParticles(UUID uuid) {
String sql = "DELETE FROM active_particles " + String sql = """
"WHERE uuid = ?"; DELETE FROM active_particles
try { WHERE uuid = ?""";
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql); try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
preparedStatement.setString(1, uuid.toString()); preparedStatement.setString(1, uuid.toString());
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to clear particles for %s", uuid.toString()), e);
} }
} }
public static PlayerSettings getPlayerSettings(UUID uuid) { public static PlayerSettings getPlayerSettings(UUID uuid) {
String sql = "SELECT * FROM user_settings WHERE uuid = ?"; String sql = """
try { SELECT * FROM user_settings
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql); WHERE uuid = ?""";
try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
preparedStatement.setString(1, uuid.toString()); preparedStatement.setString(1, uuid.toString());
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
@@ -109,18 +111,18 @@ public class Queries {
return new PlayerSettings(particlesActive, seeingParticles, uuid, activeParticles); return new PlayerSettings(particlesActive, seeingParticles, uuid, activeParticles);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to get player settings for %s", uuid.toString()), e);
} }
return createNewPlayerSettings(uuid); return createNewPlayerSettings(uuid);
} }
private static HashMap<APartType, ParticleSet> getActiveParticles(UUID uuid) { private static HashMap<APartType, ParticleSet> getActiveParticles(UUID uuid) {
HashMap<APartType, ParticleSet> activeParticles = new HashMap<>(); HashMap<APartType, ParticleSet> activeParticles = new HashMap<>();
String sql = "SELECT * FROM active_particles " + String sql = """
"WHERE uuid = ?"; SELECT * FROM active_particles
WHERE uuid = ?""";
try { try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql);
preparedStatement.setString(1, uuid.toString()); preparedStatement.setString(1, uuid.toString());
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
@@ -145,19 +147,19 @@ public class Queries {
activeParticles.put(aPartType, first.get()); activeParticles.put(aPartType, first.get());
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to get player settings for %s", uuid.toString()), e);
} }
return activeParticles; return activeParticles;
} }
private static PlayerSettings createNewPlayerSettings(UUID uuid) { private static PlayerSettings createNewPlayerSettings(UUID uuid) {
String sql = "INSERT INTO user_settings (uuid, particles_active, seeing_particles)" + String sql = """
"VALUES (?, ?, ?)" + INSERT INTO user_settings (uuid, particles_active, seeing_particles)
"ON DUPLICATE KEY UPDATE particles_active = ?, seeing_particles = ?"; VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE particles_active = ?, seeing_particles = ?""";
try { try (PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql)) {
PreparedStatement preparedStatement = Database.getConnection().prepareStatement(sql);
preparedStatement.setString(1, uuid.toString()); preparedStatement.setString(1, uuid.toString());
preparedStatement.setInt(2, 1); preparedStatement.setInt(2, 1);
preparedStatement.setInt(3, 1); preparedStatement.setInt(3, 1);
@@ -166,7 +168,7 @@ public class Queries {
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); Logger.error(String.format("unable to get player settings for %s", uuid.toString()), e);
} }
return new PlayerSettings(true, true, uuid); return new PlayerSettings(true, true, uuid);
@@ -1,60 +0,0 @@
package com.alttd.frameSpawners;
import com.alttd.config.Config;
import com.alttd.objects.APartType;
import com.alttd.objects.Frame;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import com.alttd.util.Logger;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Iterator;
import java.util.List;
public class FrameSpawnerPlayer extends BukkitRunnable {
private int amount;
private final List<Frame> frames;
private Iterator<Frame> iterator;
private final Player player;
private final PlayerSettings playerSettings;
private final APartType aPartType;
private final String uniqueId;
public FrameSpawnerPlayer(int amount, List<Frame> frames, Player player, PlayerSettings playerSettings, APartType aPartType, String uniqueId) {
this.amount = amount;
this.frames = frames;
this.iterator = frames.iterator();
this.player = player;
this.playerSettings = playerSettings;
this.aPartType = aPartType;
this.uniqueId = uniqueId;
}
@Override
public void run() {
if (!player.isOnline()) {
this.cancel();
if (Config.DEBUG)
Logger.info("Stopped repeating task due to player offline.");
return;
}
ParticleSet activeParticleSet = playerSettings.getParticles(aPartType);
if (activeParticleSet == null || !activeParticleSet.getParticleId().equalsIgnoreCase(uniqueId) || !playerSettings.hasActiveParticles()) {
this.cancel();
if (Config.DEBUG)
Logger.info("Stopped repeating task due to player switching/disabling particles.");
return;
}
if (iterator.hasNext())
iterator.next().spawn(player.getLocation(), player.getLocation().getYaw());
else if (amount != 0) {
iterator = frames.iterator();
amount--;
} else {
this.cancel();
if (Config.DEBUG)
Logger.info("Stopped repeating task due to end of frames.");
}
}
}
@@ -1,5 +1,6 @@
package com.alttd.frameSpawners; package com.alttd.frame_spawners;
import com.alttd.AltitudeParticles;
import com.alttd.config.Config; import com.alttd.config.Config;
import com.alttd.objects.Frame; import com.alttd.objects.Frame;
import com.alttd.util.Logger; import com.alttd.util.Logger;
@@ -16,26 +17,33 @@ public class FrameSpawnerLocation extends BukkitRunnable {
private Iterator<Frame> iterator; private Iterator<Frame> iterator;
private final Location location; private final Location location;
private final float rotation; private final float rotation;
public FrameSpawnerLocation(int amount, List<Frame> frames, Location location, float rotation) { private final int frameDelay;
public FrameSpawnerLocation(int amount, List<Frame> frames, int frameDelay, Location location, float rotation) {
this.amount = amount; this.amount = amount;
this.frames = frames; this.frames = frames;
this.iterator = frames.iterator(); this.iterator = frames.iterator();
this.location = location; this.location = location;
this.rotation = rotation; this.rotation = rotation;
this.frameDelay = frameDelay;
} }
@Override @Override
public void run() { public void run() {
if (iterator.hasNext()) if (amount == 0){
iterator.next().spawn(location, rotation);
else if (amount != 0) {
iterator = frames.iterator();
if (amount > 0)
amount--;
} else {
this.cancel(); this.cancel();
if (Config.DEBUG) if (Config.DEBUG)
Logger.info("Stopped repeating task due to end of frames"); Logger.info("Stopped repeating task due to end of frames");
} }
new BukkitRunnable() {
@Override
public void run() {
if (!iterator.hasNext())
this.cancel();
iterator.next().spawn(location, rotation);
}
}.runTaskTimerAsynchronously(AltitudeParticles.getInstance(), 0, frameDelay);
iterator = frames.iterator();
if (amount != -1)
amount--;
} }
} }
@@ -0,0 +1,105 @@
package com.alttd.frame_spawners;
import com.alttd.AltitudeParticles;
import com.alttd.config.Config;
import com.alttd.objects.APartType;
import com.alttd.objects.Frame;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import com.alttd.util.Logger;
import com.destroystokyo.paper.ParticleBuilder;
import de.myzelyam.api.vanish.VanishAPI;
import lombok.extern.slf4j.Slf4j;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Iterator;
import java.util.List;
@Slf4j
public class FrameSpawnerPlayer extends BukkitRunnable {
private int amount;
private final List<Frame> frames;
private final Player player;
private final PlayerSettings playerSettings;
private final APartType aPartType;
private final String uniqueId;
private final int frameDelay;
private final boolean stationary;
public FrameSpawnerPlayer(int amount, List<Frame> frames, int frameDelay, Player player, PlayerSettings playerSettings, APartType aPartType, String uniqueId, boolean stationary) {
this.amount = amount;
this.frames = frames;
this.player = player;
this.playerSettings = playerSettings;
this.aPartType = aPartType;
this.uniqueId = uniqueId;
this.frameDelay = frameDelay;
this.stationary = stationary;
}
@Override
public void run() {
if (!player.isOnline()) {
this.cancel();
if (Config.DEBUG)
log.info("Stopped repeating task due to player offline.");
return;
}
if (isVanished(player)) {
log.debug("Player {} is vanished, skipping frame spawn.", player.getName());
return;
}
Location location = player.getLocation();
float yaw = location.getYaw();
ParticleSet activeParticleSet = playerSettings.getParticles(aPartType);
if (shouldStopTask(activeParticleSet)) return;
if (amount == 0) {
this.cancel();
if (Config.DEBUG)
log.info("Stopped repeating task due to end of frames.");
}
final Iterator<Frame> iterator = frames.iterator();
if (Config.DEBUG) {
log.info("Starting frame spawn for player {}.", player.getName());
}
new BukkitRunnable() {
@Override
public void run() {
if (!iterator.hasNext() || shouldStopTask(activeParticleSet)) {
this.cancel();
return;
}
Frame next = iterator.next();
if (Config.DEBUG) {
log.info("Spawning frame with {} particles at {} for player {}", next.getKey(), location, player.getName());
}
if (stationary) {
next.spawn(location, yaw);
}
else {
next.spawn(player.getLocation(), player.getLocation().getYaw());
}
}
}.runTaskTimerAsynchronously(AltitudeParticles.getInstance(), 0, frameDelay);
if (amount != -1)
amount--;
}
private boolean shouldStopTask(ParticleSet activeParticleSet) {
if (activeParticleSet == null || !activeParticleSet.getParticleId().equalsIgnoreCase(uniqueId) || !playerSettings.hasActiveParticles()) {
this.cancel();
if (Config.DEBUG)
log.info("Stopped repeating task due to player switching/disabling particles.");
return true;
}
return false;
}
private boolean isVanished(Player player) {
return VanishAPI.isInvisible(player) || player.getGameMode().equals(GameMode.SPECTATOR);
}
}
@@ -58,7 +58,7 @@ public class ActivateParticleSet implements GUIAction {
meta.getEnchants().forEach((enchantment, integer) -> meta.removeEnchant(enchantment)); meta.getEnchants().forEach((enchantment, integer) -> meta.removeEnchant(enchantment));
item.setItemMeta(meta); item.setItemMeta(meta);
}); });
itemMeta.addEnchant(Enchantment.ARROW_INFINITE, 1, true); itemMeta.addEnchant(Enchantment.INFINITY, 1, true);
itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
Queries.addParticle(player.getUniqueId(), particleSet.getAPartType(), particleSet.getParticleId()); Queries.addParticle(player.getUniqueId(), particleSet.getAPartType(), particleSet.getParticleId());
enable = true; enable = true;
@@ -19,7 +19,6 @@ import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
public class ChooseParticleGUI extends DefaultGUI { public class ChooseParticleGUI extends DefaultGUI {
@@ -38,7 +37,7 @@ public class ChooseParticleGUI extends DefaultGUI {
super(name); super(name);
List<ParticleSet> availableParticles = ParticleStorage.getParticleSets(aPartType).stream() List<ParticleSet> availableParticles = ParticleStorage.getParticleSets(aPartType).stream()
.filter(particleSet -> player.hasPermission(particleSet.getPackPermission()) || player.hasPermission(particleSet.getPermission())) .filter(particleSet -> player.hasPermission(particleSet.getPackPermission()) || player.hasPermission(particleSet.getPermission()))
.collect(Collectors.toList()); .toList();
PlayerSettings playerSettings = PlayerSettings.getPlayer(player.getUniqueId()); PlayerSettings playerSettings = PlayerSettings.getPlayer(player.getUniqueId());
int i = 0; int i = 0;
for (ParticleSet particleSet : availableParticles) { for (ParticleSet particleSet : availableParticles) {
@@ -49,7 +48,7 @@ public class ChooseParticleGUI extends DefaultGUI {
if (activeParticleSet != null && playerSettings.getParticles(aPartType).equals(particleSet)) { if (activeParticleSet != null && playerSettings.getParticles(aPartType).equals(particleSet)) {
ItemMeta itemMeta = itemStack.getItemMeta(); ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.addEnchant(Enchantment.ARROW_INFINITE, 1, true); itemMeta.addEnchant(Enchantment.INFINITY, 1, true);
itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
itemStack.setItemMeta(itemMeta); itemStack.setItemMeta(itemMeta);
} }
@@ -1,19 +1,12 @@
package com.alttd.listeners; package com.alttd.listeners;
import com.alttd.AltitudeParticles;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List; import java.util.List;
import java.util.UUID;
public class BlockBreakListener implements Listener { public class BlockBreakListener implements Listener {
@@ -27,21 +20,7 @@ public class BlockBreakListener implements Listener {
public void onBlockBreak(BlockBreakEvent event) { public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) if (event.isCancelled())
return; return;
new BukkitRunnable() { SpawnParticleUtil.spawnAsyncParticles(particlesToActivate, event.getPlayer(), () ->
@Override event.getBlock().getLocation());
public void run() {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
PlayerSettings playerSettings = PlayerSettings.getPlayer(uuid);
if (!playerSettings.hasActiveParticles())
return;
particlesToActivate.forEach(aPartType -> {
ParticleSet particleSet = playerSettings.getParticles(aPartType);
if (particleSet == null)
return;
particleSet.run(event.getBlock().getLocation(), player);
});
}
}.runTaskAsynchronously(AltitudeParticles.getInstance());
} }
} }
@@ -1,19 +1,12 @@
package com.alttd.listeners; package com.alttd.listeners;
import com.alttd.AltitudeParticles;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List; import java.util.List;
import java.util.UUID;
public class BlockPlaceListener implements Listener { public class BlockPlaceListener implements Listener {
@@ -27,21 +20,7 @@ public class BlockPlaceListener implements Listener {
public void onBlockPlace(BlockPlaceEvent event) { public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) if (event.isCancelled())
return; return;
new BukkitRunnable() { SpawnParticleUtil.spawnAsyncParticles(particlesToActivate, event.getPlayer(), () ->
@Override event.getBlock().getLocation());
public void run() {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
PlayerSettings playerSettings = PlayerSettings.getPlayer(uuid);
if (!playerSettings.hasActiveParticles())
return;
particlesToActivate.forEach(aPartType -> {
ParticleSet particleSet = playerSettings.getParticles(aPartType);
if (particleSet == null)
return;
particleSet.run(event.getBlock().getLocation(), player);
});
}
}.runTaskAsynchronously(AltitudeParticles.getInstance());
} }
} }
@@ -1,18 +1,13 @@
package com.alttd.listeners; package com.alttd.listeners;
import com.alttd.AltitudeParticles;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List; import java.util.List;
import java.util.UUID;
public class DeathListener implements Listener { public class DeathListener implements Listener {
@@ -26,21 +21,7 @@ public class DeathListener implements Listener {
public void onDeath(PlayerDeathEvent event) { public void onDeath(PlayerDeathEvent event) {
if (event.isCancelled()) if (event.isCancelled())
return; return;
new BukkitRunnable() {
@Override
public void run() {
Player player = event.getPlayer(); Player player = event.getPlayer();
UUID uuid = player.getUniqueId(); SpawnParticleUtil.spawnAsyncParticles(particlesToActivate, player, player::getLocation);
PlayerSettings playerSettings = PlayerSettings.getPlayer(uuid);
if (!playerSettings.hasActiveParticles())
return;
particlesToActivate.forEach(aPartType -> {
ParticleSet particleSet = playerSettings.getParticles(aPartType);
if (particleSet == null)
return;
particleSet.run(player.getLocation(), player);
});
}
}.runTaskAsynchronously(AltitudeParticles.getInstance());
} }
} }
@@ -1,19 +1,13 @@
package com.alttd.listeners; package com.alttd.listeners;
import com.alttd.AltitudeParticles;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List; import java.util.List;
import java.util.UUID;
public class KillListener implements Listener { public class KillListener implements Listener {
private final List<APartType> particlesToActivate; private final List<APartType> particlesToActivate;
@@ -29,20 +23,6 @@ public class KillListener implements Listener {
Player player = event.getEntity().getKiller(); Player player = event.getEntity().getKiller();
if (player == null) if (player == null)
return; return;
new BukkitRunnable() { SpawnParticleUtil.spawnAsyncParticles(particlesToActivate, player, () -> event.getEntity().getLocation());
@Override
public void run() {
UUID uuid = player.getUniqueId();
PlayerSettings playerSettings = PlayerSettings.getPlayer(uuid);
if (!playerSettings.hasActiveParticles())
return;
particlesToActivate.forEach(aPartType -> {
ParticleSet particleSet = playerSettings.getParticles(aPartType);
if (particleSet == null)
return;
particleSet.run(event.getEntity().getLocation(), player);
});
}
}.runTaskAsynchronously(AltitudeParticles.getInstance());
} }
} }
@@ -8,7 +8,7 @@ import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerQuitListener implements Listener { public class PlayerQuitListener implements Listener {
@EventHandler @EventHandler
public void onPlayerLeave(PlayerQuitEvent event) { public void onPlayerLeave(PlayerQuitEvent event) { //TODO particles when a player leaves
PlayerSettings.removePlayer(event.getPlayer().getUniqueId()); PlayerSettings.removePlayer(event.getPlayer().getUniqueId());
} }
} }
@@ -1,9 +1,6 @@
package com.alttd.listeners; package com.alttd.listeners;
import com.alttd.AltitudeParticles;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -14,10 +11,8 @@ import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List; import java.util.List;
import java.util.UUID;
public class RightClickListener implements Listener { public class RightClickListener implements Listener {
@@ -38,22 +33,7 @@ public class RightClickListener implements Listener {
Block clickedBlock = event.getClickedBlock(); Block clickedBlock = event.getClickedBlock();
if (clickedBlock == null) if (clickedBlock == null)
return; return;
new BukkitRunnable() {
@Override
public void run() {
Player player = event.getPlayer(); Player player = event.getPlayer();
UUID uuid = player.getUniqueId(); SpawnParticleUtil.spawnAsyncParticles(particlesToActivate, player, player::getLocation);
PlayerSettings playerSettings = PlayerSettings.getPlayer(uuid);
if (!playerSettings.hasActiveParticles())
return;
particlesToActivate.forEach(aPartType -> {
ParticleSet particleSet = playerSettings.getParticles(aPartType);
if (particleSet == null)
return;
particleSet.run(player.getLocation(), player);
});
}
}.runTaskAsynchronously(AltitudeParticles.getInstance());
} }
} }
@@ -0,0 +1,43 @@
package com.alttd.listeners;
import com.alttd.AltitudeParticles;
import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
import java.util.UUID;
public class SpawnParticleUtil {
@FunctionalInterface
public interface LocationConsumer {
Location getLocation();
}
public static void spawnAsyncParticles(List<APartType> particlesToActivate, Player player, LocationConsumer locationConsumer) {
new BukkitRunnable() {
@Override
public void run() {
spawn(particlesToActivate, player, locationConsumer);
}
}.runTaskAsynchronously(AltitudeParticles.getInstance());
}
private static void spawn(List<APartType> particlesToActivate, Player player, LocationConsumer locationConsumer) {
UUID uuid = player.getUniqueId();
PlayerSettings playerSettings = PlayerSettings.getPlayer(uuid);
if (!playerSettings.hasActiveParticles())
return;
particlesToActivate.forEach(aPartType -> {
ParticleSet particleSet = playerSettings.getParticles(aPartType);
if (particleSet == null)
return;
particleSet.run(locationConsumer.getLocation(), player);
});
}
}
@@ -1,19 +1,12 @@
package com.alttd.listeners; package com.alttd.listeners;
import com.alttd.AltitudeParticles;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.PlayerSettings;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List; import java.util.List;
import java.util.UUID;
public class TeleportArriveListener implements Listener { public class TeleportArriveListener implements Listener {
private final List<APartType> particlesToActivate; private final List<APartType> particlesToActivate;
@@ -26,22 +19,7 @@ public class TeleportArriveListener implements Listener {
public void onTeleportArrive(PlayerTeleportEvent event) { public void onTeleportArrive(PlayerTeleportEvent event) {
if (event.isCancelled()) if (event.isCancelled())
return; return;
new BukkitRunnable() { SpawnParticleUtil.spawnAsyncParticles(particlesToActivate, event.getPlayer(), event::getTo);
@Override
public void run() {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
PlayerSettings playerSettings = PlayerSettings.getPlayer(uuid);
if (!playerSettings.hasActiveParticles())
return;
particlesToActivate.forEach(aPartType -> {
ParticleSet particleSet = playerSettings.getParticles(aPartType);
if (particleSet == null)
return;
particleSet.run(event.getTo(), player);
});
}
}.runTaskAsynchronously(AltitudeParticles.getInstance());
} }
} }
@@ -0,0 +1,85 @@
package com.alttd.models;
import com.alttd.objects.APartType;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
import java.util.List;
/**
* Represents the configuration data for a particle effect, including its name, type, display properties,
* animations, and permissions. This class is primarily used for managing particle data in the context
* of custom particle effects and animations.
* <p>
* Fields:
* - particleName: The unique name of the particle effect, used internally.
* - displayName: The name displayed to the user.
* - particleType: The type of the particle effect, which corresponds to an {@link APartType}.
* - lore: Additional descriptive text associated with the particle effect.
* - displayItem: An item representation for display purposes in order to visually represent the effect.
* - permission: The permission string required for accessing the particle effect.
* - packagePermission: A specific permission string linked to a grouped set of effects.
* - frameDelay: The delay between animation frames, in milliseconds.
* - repeat: The number of times the particle animation should repeat.
* - repeatDelay: The delay between repeat executions, in milliseconds.
* - randomOffset: A random position offset applied to the particle effect for variances.
* - stationary: Determines if the particle effect remains static or follows movement.
* - frames: A map defining animation frames for the particle effect. The key is an identifier, and the
* value is a list of {@link ParticleInfo} objects representing the frame's particle configuration.
* <p>
* Methods:
* - getAPartType(): Converts the particleType string field into an equivalent {@link APartType} enum value.
* This allows for accessing predefined properties of the particle type.
*/
@Setter
@Getter
public class ParticleData {
// TODO add optional property for a list of users that can use the particle
// If that list is present the particle should be loaded as a dev particle
// Dev particles should disable all others while in use and all be grouped together
// (since the dev should know what each particle is and does)
// Seeing dev particles should require a permission
@JsonProperty("user_list")
private List<String> userList;
@JsonProperty("particle_name")
private String particleName;
@JsonProperty("display_name")
private String displayName;
@JsonProperty("particle_type")
private String particleType;
private String lore;
@JsonProperty("display_item")
private String displayItem;
private String permission;
@JsonProperty("package_permission")
private String packagePermission;
@JsonProperty("frame_delay")
private int frameDelay;
private int repeat;
@JsonProperty("repeat_delay")
private int repeatDelay;
@JsonProperty("random_offset")
private double randomOffset;
private boolean stationary;
private Map<String, List<ParticleInfo>> frames;
public APartType getAPartType() {
return APartType.valueOf(particleType);
}
}
@@ -0,0 +1,45 @@
package com.alttd.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
/**
* Represents information about a particle, including its type, position, and additional properties.
* This class is used to describe the details of individual particles, including support for
* particle-specific attributes such as color and extra data.
* <p>
* Fields:
* - particleType: The type of the particle, as defined by its name or identifier.
* - x, y, z: Coordinates representing the position of the particle in the 3D space.
* - color: A string representing the color of the particle, used primarily for "DustOptions".
* - extra: An additional property used for some specific particle types, allowing for further customization.
* <p>
* The class is annotated for JSON serialization and deserialization using the Jackson library,
* ensuring smooth integration with JSON-based configurations.
* <p>
* This object is used in the context of particle data configurations and animations.
*/
@Setter
@Getter
public class ParticleInfo {
@JsonProperty("particle_type")
private String particleType;
private double x;
private double y;
private double z;
// For DustOptions
private String color;
@JsonProperty("color_gradient_end")
private String colorGradientEnd;
// For DustOptions
@JsonProperty(value = "size", defaultValue = "1")
private float size = 1;
// For other particle types
private Double extra;
}
+8 -24
View File
@@ -1,6 +1,8 @@
package com.alttd.objects; package com.alttd.objects;
import com.alttd.config.Config; import com.alttd.config.Config;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -15,37 +17,19 @@ public enum APartType { //TODO add description?
CLICK_BLOCK("CLICK_BLOCK", "Right click block", Material.DIAMOND_BLOCK, TimeUnit.SECONDS.toMillis(Config.CLICK_BLOCK_COOL_DOWN), null, true), CLICK_BLOCK("CLICK_BLOCK", "Right click block", Material.DIAMOND_BLOCK, TimeUnit.SECONDS.toMillis(Config.CLICK_BLOCK_COOL_DOWN), null, true),
TELEPORT_ARRIVE("TELEPORT", "Teleport", Material.DRAGON_EGG, TimeUnit.SECONDS.toMillis(Config.TELEPORT_ARRIVE_COOL_DOWN), null, true); TELEPORT_ARRIVE("TELEPORT", "Teleport", Material.DRAGON_EGG, TimeUnit.SECONDS.toMillis(Config.TELEPORT_ARRIVE_COOL_DOWN), null, true);
@Getter
private final String name; private final String name;
@Getter
private final String displayName; private final String displayName;
@Getter
private final Material material; private final Material material;
@Getter
private final long delay; private final long delay;
@Setter
@Getter
private ItemStack itemStack; private ItemStack itemStack;
private final boolean event; private final boolean event;
public String getName() {
return name;
}
public String getDisplayName() {
return displayName;
}
public Material getMaterial() {
return material;
}
public long getDelay() {
return delay;
}
public ItemStack getItemStack() {
return itemStack;
}
public void setItemStack(ItemStack itemStack) {
this.itemStack = itemStack;
}
public boolean hasEvent() { public boolean hasEvent() {
return event; return event;
} }
+30 -20
View File
@@ -1,20 +1,24 @@
package com.alttd.objects; package com.alttd.objects;
import com.alttd.config.Config;
import com.alttd.storage.PlayerSettings; import com.alttd.storage.PlayerSettings;
import com.alttd.util.Logger; import lombok.Getter;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class Frame { public class Frame {
List<AParticle> AParticles; @Getter
private final String key;
private final List<AParticle> aParticles;
public Frame(List<AParticle> AParticles) { public Frame(String key, List<AParticle> aParticles) {
this.AParticles = AParticles; this.key = key;
this.aParticles = aParticles;
} }
/** /**
@@ -24,20 +28,28 @@ public class Frame {
*/ */
public void spawn(Location location, float rotation) { public void spawn(Location location, float rotation) {
Location tmpLocation = location.clone(); Location tmpLocation = location.clone();
AParticles.forEach(AParticle -> { aParticles.forEach(aParticle -> {
ThreadLocalRandom current = ThreadLocalRandom.current(); ThreadLocalRandom current = ThreadLocalRandom.current();
double offsetX = ((AParticle.offset_range() == 0) ? 0 : current.nextDouble(-AParticle.offset_range(), AParticle.offset_range())); double offsetX = ((aParticle.offset_range() == 0) ? 0 : current.nextDouble(-aParticle.offset_range(), aParticle.offset_range()));
double offsetZ = ((AParticle.offset_range() == 0) ? 0 : current.nextDouble(-AParticle.offset_range(), AParticle.offset_range())); double offsetZ = ((aParticle.offset_range() == 0) ? 0 : current.nextDouble(-aParticle.offset_range(), aParticle.offset_range()));
double offsetY = ((AParticle.offset_range() == 0) ? 0 : current.nextDouble(-AParticle.offset_range(), AParticle.offset_range())); double offsetY = ((aParticle.offset_range() == 0) ? 0 : current.nextDouble(-aParticle.offset_range(), aParticle.offset_range()));
XZ xz = new XZ(location.getX(), location.getX() + AParticle.x() + offsetX, XZ xz = new XZ(location.getX(), location.getX() + aParticle.x() + offsetX,
location.getZ(), location.getZ() + AParticle.z() + offsetZ, location.getZ(), location.getZ() + aParticle.z() + offsetZ,
rotation); rotation);
AParticle.particleBuilder() List<Player> receivers = getReceivers(location);
.location(tmpLocation.set( tmpLocation.set(
xz.getRotatedX(), xz.getRotatedX(),
location.getY() + AParticle.y() + offsetY, location.getY() + aParticle.y() + offsetY,
xz.getRotatedZ())) xz.getRotatedZ());
.receivers(Bukkit.getOnlinePlayers().stream() aParticle.particleBuilder()
.location(tmpLocation)
.receivers(receivers)
.spawn();
});
}
private static @NotNull List<Player> getReceivers(Location location) {
return Bukkit.getOnlinePlayers().stream()
.filter(player -> { .filter(player -> {
PlayerSettings playerSettings = PlayerSettings.getPlayer(player.getUniqueId()); PlayerSettings playerSettings = PlayerSettings.getPlayer(player.getUniqueId());
if (playerSettings == null) if (playerSettings == null)
@@ -46,12 +58,10 @@ public class Frame {
return false; return false;
Location playerLocation = player.getLocation(); Location playerLocation = player.getLocation();
return location.getWorld().getUID().equals(playerLocation.getWorld().getUID()) && player.getLocation().distance(location) < 100; return location.getWorld().getUID().equals(playerLocation.getWorld().getUID()) && player.getLocation().distance(location) < 100;
}).collect(Collectors.toList())) }).collect(Collectors.toList());
.spawn();
});
} }
private class XZ { private static class XZ {
private final double cx, cz; //Coordinates to rotate around private final double cx, cz; //Coordinates to rotate around
private double x, z; //Coordinated to rotate private double x, z; //Coordinated to rotate
@@ -2,11 +2,13 @@ package com.alttd.objects;
import com.alttd.AltitudeParticles; import com.alttd.AltitudeParticles;
import com.alttd.config.Config; import com.alttd.config.Config;
import com.alttd.frameSpawners.FrameSpawnerLocation; import com.alttd.frame_spawners.FrameSpawnerLocation;
import com.alttd.frameSpawners.FrameSpawnerPlayer; import com.alttd.frame_spawners.FrameSpawnerPlayer;
import com.alttd.storage.PlayerSettings; import com.alttd.storage.PlayerSettings;
import com.alttd.util.Logger; import com.alttd.util.Logger;
import de.myzelyam.api.vanish.VanishAPI; import de.myzelyam.api.vanish.VanishAPI;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
@@ -18,17 +20,23 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Slf4j
public class ParticleSet { public class ParticleSet {
private final List<Frame> frames; private final List<Frame> frames;
private final int frameDelay, repeat, repeatDelay; private final int frameDelay, repeat, repeatDelay;
@Getter
private final APartType aPartType; private final APartType aPartType;
private final String uniqueId; private final String uniqueId;
@Getter
private final String permission; private final String permission;
@Getter
private final String packPermission; private final String packPermission;
@Getter
private final ItemStack itemStack; private final ItemStack itemStack;
private final boolean stationary;
public ParticleSet(List<Frame> frames, String name, List<String> lore, int frameDelay, int repeat, int repeatDelay, APartType aPartType, String uniqueId, String permission, String packPermission,ItemStack itemStack) { public ParticleSet(List<Frame> frames, String name, List<String> lore, int frameDelay, int repeat, int repeatDelay, boolean stationary, APartType aPartType, String uniqueId, String permission, String packPermission, ItemStack itemStack) {
MiniMessage miniMessage = MiniMessage.miniMessage(); MiniMessage miniMessage = MiniMessage.miniMessage();
this.frames = frames; this.frames = frames;
this.frameDelay = frameDelay; this.frameDelay = frameDelay;
@@ -38,6 +46,7 @@ public class ParticleSet {
this.uniqueId = uniqueId; this.uniqueId = uniqueId;
this.permission = permission; this.permission = permission;
this.packPermission = packPermission; this.packPermission = packPermission;
this.stationary = stationary;
ItemMeta itemMeta = itemStack.getItemMeta(); ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.displayName(miniMessage.deserialize(name)); itemMeta.displayName(miniMessage.deserialize(name));
itemMeta.lore(lore.stream().map(miniMessage::deserialize).collect(Collectors.toList())); itemMeta.lore(lore.stream().map(miniMessage::deserialize).collect(Collectors.toList()));
@@ -46,51 +55,31 @@ public class ParticleSet {
} }
public void run(Location location, Player player) { public void run(Location location, Player player) {
if (tooSoon(player.getUniqueId()) || isVanished(player)) if (tooSoon(player.getUniqueId()))
return; return;
FrameSpawnerLocation frameSpawnerLocation = new FrameSpawnerLocation(repeat, frames, location, player.getLocation().getYaw()); FrameSpawnerLocation frameSpawnerLocation = new FrameSpawnerLocation(repeat, frames, frameDelay, location, player.getLocation().getYaw());
frameSpawnerLocation.runTaskTimerAsynchronously(AltitudeParticles.getInstance(), frameDelay, repeatDelay); frameSpawnerLocation.runTaskTimerAsynchronously(AltitudeParticles.getInstance(), 0, repeatDelay);
} }
public void run(Player player, PlayerSettings playerSettings) { public void run(Player player, PlayerSettings playerSettings) {
if (tooSoon(player.getUniqueId()) && !player.hasPermission("apart.bypass-cooldown")) if (tooSoon(player.getUniqueId()) && !player.hasPermission("apart.bypass-cooldown"))
return; return;
if (Config.DEBUG) if (Config.DEBUG) {
Logger.info("Starting particle set % for %.", uniqueId, player.getName()); log.info("Starting particle set {} for {}.", uniqueId, player.getName());
FrameSpawnerPlayer frameSpawnerPlayer = new FrameSpawnerPlayer(repeat, frames, player, playerSettings, aPartType, uniqueId);
frameSpawnerPlayer.runTaskTimerAsynchronously(AltitudeParticles.getInstance(), frameDelay, repeatDelay);
} }
FrameSpawnerPlayer frameSpawnerPlayer = new FrameSpawnerPlayer(repeat, frames, frameDelay, player, playerSettings, aPartType, uniqueId, stationary);
private boolean isVanished(Player player) { frameSpawnerPlayer.runTaskTimerAsynchronously(AltitudeParticles.getInstance(), 0, repeatDelay);
return VanishAPI.isInvisible(player) || player.getGameMode().equals(GameMode.SPECTATOR);
} }
private boolean tooSoon(UUID uuid) { private boolean tooSoon(UUID uuid) {
PlayerSettings ps = PlayerSettings.getPlayer(uuid); PlayerSettings ps = PlayerSettings.getPlayer(uuid);
if (ps.canRun(aPartType)) if (ps.canRun(aPartType)) {
{
ps.run(aPartType); ps.run(aPartType);
return false; return false;
} }
return true; return true;
} }
public APartType getAPartType() {
return aPartType;
}
public String getPermission() {
return permission;
}
public String getPackPermission() {
return packPermission;
}
public ItemStack getItemStack() {
return itemStack;
}
public String getParticleId() { public String getParticleId() {
return uniqueId; return uniqueId;
} }
@@ -1,53 +0,0 @@
package com.alttd.particles;
import com.alttd.objects.APartType;
import com.alttd.objects.AParticle;
import com.alttd.objects.Frame;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.ParticleStorage;
import com.destroystokyo.paper.ParticleBuilder;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
public class Alpha {
// private static final ItemStack itemStack;
//
// static {
// MiniMessage miniMessage = MiniMessage.miniMessage();
// itemStack = new ItemStack(Material.ANVIL);
// ItemMeta itemMeta = itemStack.getItemMeta();
// itemMeta.displayName(miniMessage.deserialize("<gold>Alpha Particles</gold>"));
// itemMeta.lore(List.of(
// miniMessage.deserialize("<dark_aqua>An exclusive particle</dark_aqua>"),
// miniMessage.deserialize("<dark_aqua>set for Alpha testers!</dark_aqua>")));
// itemStack.setItemMeta(itemMeta);
// }
//
// public Alpha() {
// List<Frame> frameList = new ArrayList<>();
//
// frameList.add(new Frame(frameOne()));
//
// ParticleStorage.addParticleSet(APartType.TELEPORT_ARRIVE, new ParticleSet(frameList, 5, 10, 10, APartType.TELEPORT_ARRIVE, "ALPHA_TELEPORT", "apart.particle.alpha", itemStack));
// ParticleStorage.addParticleSet(APartType.CLICK_BLOCK, new ParticleSet(frameList, 5, 10, 10, APartType.CLICK_BLOCK, "ALPHA_CLICK", "apart.particle.alpha", itemStack));
// }
//
//
// public List<AParticle> frameOne() {
// List<AParticle> list = new ArrayList<>();
// double[] xPts = {0.23, 0.21, 0.19, 0.17, 0.15, 0.13, 0.11, 0.09, 0.06, 0.02, -0.03, -0.08, -0.14, -0.19, -0.24, -0.26, -0.28, -0.28, -0.27, -0.25, -0.22, -0.18, -0.13, -0.08, -0.03, 0.00, 0.03, 0.06, 0.09, 0.11, 0.14, 0.15, 0.16, 0.18, 0.22, 0.26, 0.30, 0.32};
// double[] yPts = {0.91, 0.86, 0.81, 0.76, 0.70, 0.63, 0.58, 0.52, 0.47, 0.42, 0.39, 0.38, 0.39, 0.42, 0.47, 0.52, 0.58, 0.63, 0.69, 0.75, 0.81, 0.86, 0.89, 0.90, 0.89, 0.87, 0.83, 0.79, 0.74, 0.69, 0.57, 0.51, 0.46, 0.42, 0.40, 0.40, 0.42, 0.47};
//
// for(int i = 0; i < xPts.length; i++) {
// list.add(new AParticle(xPts[i] * 2, (yPts[i] * 2) + 1.5, 0.5, 0, new ParticleBuilder(Particle.REDSTONE).color(Color.GRAY).count(1)));
// }
// return list;
// }
}
@@ -1,59 +0,0 @@
package com.alttd.particles;
import com.alttd.objects.APartType;
import com.alttd.objects.AParticle;
import com.alttd.objects.Frame;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.ParticleStorage;
import com.destroystokyo.paper.ParticleBuilder;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionType;
import java.util.ArrayList;
import java.util.List;
public class Cupid {
// private static final ItemStack itemStack;
//
// static {
// MiniMessage miniMessage = MiniMessage.miniMessage();
// itemStack = new ItemStack(Material.PINK_TULIP);
// /*PotionMeta meta = (PotionMeta) itemStack.getItemMeta();
// meta.setBasePotionData(new PotionData(PotionType.REGEN));
// itemStack.setItemMeta(meta);*/
// ItemMeta itemMeta = itemStack.getItemMeta();
// itemMeta.displayName(miniMessage.deserialize("<gold>Cupid Particles</gold>"));
// itemMeta.lore(List.of(
// miniMessage.deserialize("<dark_aqua>No one is immune</dark_aqua>"),
// miniMessage.deserialize("<dark_aqua>to Cupid's arrow...</dark_aqua>")));
// itemStack.setItemMeta(itemMeta);
// }
//
// public Cupid() {
// List<Frame> frameList = new ArrayList<>();
//
// frameList.add(new Frame(frameOne()));
//
// ParticleStorage.addParticleSet(APartType.HEAD, new ParticleSet(frameList, 10, 5, 40, APartType.HEAD, "CUPID_HEAD", "apart.particle.test", itemStack));
// ParticleStorage.addParticleSet(APartType.TELEPORT_ARRIVE, new ParticleSet(frameList, 10, 5, 40, APartType.TELEPORT_ARRIVE, "CUPID_TELEPORT", "apart.particle.test", itemStack));
// ParticleStorage.addParticleSet(APartType.CLICK_BLOCK, new ParticleSet(frameList, 10, 5, 40, APartType.CLICK_BLOCK, "CUPID_CLICK", "apart.particle.test", itemStack));
// }
//
//
// public List<AParticle> frameOne() {
// List<AParticle> list = new ArrayList<>();
//
// list.add(new AParticle((Math.random() * 2) - 1, (Math.random() * 2) - 1, (Math.random() * 2) - 1, 0.5, new ParticleBuilder(Particle.HEART).count(1)));
// list.add(new AParticle((Math.random() * 2) - 1, (Math.random() * 2) - 1, (Math.random() * 2) - 1, 0.5, new ParticleBuilder(Particle.HEART).count(1)));
// list.add(new AParticle((Math.random() * 2) - 1, (Math.random() * 2) - 1, (Math.random() * 2) - 1, 0.5,new ParticleBuilder(Particle.HEART).count(1)));
// return list;
// }
}
@@ -1,9 +0,0 @@
package com.alttd.particles;
public class InitParticles {
public static void init() {
// new Test();
// new Alpha();
// new Cupid();
}
}
@@ -1,56 +0,0 @@
package com.alttd.particles;
import com.alttd.objects.APartType;
import com.alttd.objects.AParticle;
import com.alttd.objects.Frame;
import com.alttd.objects.ParticleSet;
import com.alttd.storage.ParticleStorage;
import com.destroystokyo.paper.ParticleBuilder;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
public class Test {
//
// private static final ItemStack itemStack;
//
// static {
// MiniMessage miniMessage = MiniMessage.miniMessage();
// itemStack = new ItemStack(Material.BUCKET);
// ItemMeta itemMeta = itemStack.getItemMeta();
// itemMeta.displayName(miniMessage.deserialize("<gold>TestParticles</gold>"));
// itemMeta.lore(List.of(
// miniMessage.deserialize("<dark_aqua>A particle to test</dark_aqua>"),
// miniMessage.deserialize("<dark_aqua>the functionality of this plugin</dark_aqua>")));
// itemStack.setItemMeta(itemMeta);
// }
//
// public Test() {
// APartType test = APartType.BREAK_PLACE_BLOCK;
// List<Frame> frameList = new ArrayList<>();
// //
// frameList.add(new Frame(frameOne()));
// //....
// ParticleStorage.addParticleSet(test, new ParticleSet(frameList, 5, 5, 0, test, "UNIQUE_NAME_TEST", "apart.particle.test", itemStack));
// ParticleStorage.addParticleSet(APartType.TRAIL, new ParticleSet(frameList, 5, -1, 40, APartType.TRAIL, "UNIQUE_NAME_TEST", "apart.particle.test", itemStack));
// ParticleStorage.addParticleSet(APartType.DEATH, new ParticleSet(frameList, 5, 2, 10, APartType.DEATH, "UNIQUE_NAME_TEST", "apart.particle.test", itemStack));
// ParticleStorage.addParticleSet(APartType.KILL, new ParticleSet(frameList, 5, -1, 10, APartType.KILL, "UNIQUE_NAME_TEST", "apart.particle.test", itemStack));
// ParticleStorage.addParticleSet(APartType.TELEPORT_ARRIVE, new ParticleSet(frameList, 5, 5, 40, APartType.TELEPORT_ARRIVE, "UNIQUE_NAME_TEST", "apart.particle.test", itemStack));
// ParticleStorage.addParticleSet(APartType.CLICK_BLOCK, new ParticleSet(frameList, 5, 5, 40, APartType.CLICK_BLOCK, "UNIQUE_NAME_TEST", "apart.particle.test", itemStack));
// }
//
//
// public List<AParticle> frameOne() {
// List<AParticle> list = new ArrayList<>();
// list.add(new AParticle(0, 2, 0, 0.3, new ParticleBuilder(Particle.TOTEM)));
// list.add(new AParticle(0, 2, 0, 0.3, new ParticleBuilder(Particle.TOTEM)));
// list.add(new AParticle(0, 2, 0, 0.3, new ParticleBuilder(Particle.TOTEM)));
// list.add(new AParticle(0, 2, 0, 0.3, new ParticleBuilder(Particle.TOTEM)));
// return list;
// }
}
@@ -0,0 +1,171 @@
package com.alttd.storage;
import com.alttd.config.ParticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class AutoReload {
private final WatchService watchService;
private final Map<WatchKey, Path> keys;
private final Path rootDirectory;
private volatile boolean running = true;
public AutoReload(Path directory) throws IOException {
this.watchService = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<>();
this.rootDirectory = directory;
register(directory);
registerAll(directory);
}
private void registerAll(Path start) throws IOException {
Files.walkFileTree(start, new SimpleFileVisitor<>() {
@Override
public @NotNull FileVisitResult preVisitDirectory(@NotNull Path path, @NotNull BasicFileAttributes attrs) throws IOException {
if (path.toFile().isDirectory()) {
register(path);
}
return FileVisitResult.CONTINUE;
}
});
}
private void register(@NotNull Path dir) throws IOException {
WatchKey key = dir.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
keys.put(key, dir);
}
public void startWatching() {
log.info("Starting watch thread.");
Thread watchThread = new Thread(() -> {
log.info("Watch thread started.");
while (running) {
log.info("Watch thread loop start");
WatchKey key;
try {
key = watchService.take();
log.info("Watch thread loop key {}", key.toString());
} catch (InterruptedException e) {
log.error("Interrupted while waiting for key", e);
return;
}
if (!running) {
log.info("Exiting watch thread.");
return;
}
Path dir = keys.get(key);
if (dir == null) {
log.warn("Detected unknown key: {}. Ignoring.", key.toString());
continue;
}
detectChanges(key, dir);
if (!key.reset()) {
keys.remove(key);
if (keys.isEmpty()) {
log.info("No longer watching any directories. Exiting.");
break;
}
}
}
});
watchThread.start();
}
private void detectChanges(@NotNull WatchKey key, Path dir) {
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
log.warn("Detected overflow event. Ignoring.");
continue;
}
Path child = resolveEventPath(event, dir);
boolean isDirectory = Files.isDirectory(child);
if (shouldIgnoreDirectoryEvent(isDirectory, dir)) {
continue;
}
if (kind == StandardWatchEventKinds.ENTRY_CREATE && isDirectory) {
handleNewDirectoryCreation(child);
continue;
}
if (isDirectory) {
continue;
}
handleFileEvent(kind, child);
}
}
private @NotNull Path resolveEventPath(@NotNull WatchEvent<?> event, Path dir) {
Object context = event.context();
if (!(context instanceof Path path)) {
throw new IllegalArgumentException("Expected event context to be a Path, but got: " + context);
}
return dir.resolve(path);
}
private boolean shouldIgnoreDirectoryEvent(boolean isDirectory, Path dir) {
if (isDirectory && !dir.equals(rootDirectory)) {
log.warn("Detected directory {} outside of root directory. Ignoring.", dir);
return true;
}
return false;
}
private void handleNewDirectoryCreation(Path child) {
try {
log.info("Registering new directory: {}", child);
registerAll(child);
} catch (IOException e) {
log.error("Failed to register directory: {}", child);
}
}
private void handleFileEvent(WatchEvent.Kind<?> kind, Path child) {
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
log.debug("Detected file modification: {}", child);
reloadFile(child);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
log.debug("Detected file deletion: {}", child);
handleFileDeletion();
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
log.debug("Detected file creation: {}", child);
reloadFile(child);
} else {
log.warn("Unknown event kind: {}", kind);
}
}
private void reloadFile(Path child) {
ParticleConfig.loadParticleFromFile(child.toFile());
}
private void handleFileDeletion() {
log.info("Detected file deletion. Reloading all particles.");
ParticleConfig.reload();
}
public void stop() {
running = false;
}
}
@@ -2,18 +2,25 @@ package com.alttd.storage;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet; import com.alttd.objects.ParticleSet;
import com.alttd.util.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional;
public class ParticleStorage { public class ParticleStorage {
private static final HashMap<APartType, List<ParticleSet>> particles = new HashMap<>(); private static final HashMap<APartType, List<ParticleSet>> particles = new HashMap<>();
public static void addParticleSet(APartType aPartType, ParticleSet particleSet) { public static void addParticleSet(APartType aPartType, ParticleSet particleSet) {
List<ParticleSet> particleSets = particles.getOrDefault(aPartType, new ArrayList<>()); List<ParticleSet> particleSets = particles.getOrDefault(aPartType, new ArrayList<>());
if (particleSets.contains(particleSet)) Optional<ParticleSet> existingParticleSet = particleSets.stream()
return; .filter(p -> p.getParticleId().equalsIgnoreCase(particleSet.getParticleId()))
.findAny();
if (existingParticleSet.isPresent()) {
Logger.warning("Overwriting particle set %", particleSet.getParticleId());
particleSets.remove(existingParticleSet.get());
}
particleSets.add(particleSet); particleSets.add(particleSet);
particles.put(aPartType, particleSets); particles.put(aPartType, particleSets);
} }
@@ -3,6 +3,7 @@ package com.alttd.storage;
import com.alttd.database.Queries; import com.alttd.database.Queries;
import com.alttd.objects.APartType; import com.alttd.objects.APartType;
import com.alttd.objects.ParticleSet; import com.alttd.objects.ParticleSet;
import lombok.Getter;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
@@ -12,8 +13,12 @@ public class PlayerSettings {
private static final HashMap<UUID, PlayerSettings> playerSettingsMap = new HashMap<>(); private static final HashMap<UUID, PlayerSettings> playerSettingsMap = new HashMap<>();
private boolean particlesActive, seeingParticles; private boolean particlesActive;
@Getter
private boolean seeingParticles;
@Getter
private final UUID uuid; private final UUID uuid;
@Getter
private final HashMap<APartType, ParticleSet> particles; private final HashMap<APartType, ParticleSet> particles;
private final HashMap<APartType, Long> lastUsed; private final HashMap<APartType, Long> lastUsed;
@@ -54,23 +59,11 @@ public class PlayerSettings {
return particlesActive; return particlesActive;
} }
public boolean isSeeingParticles() {
return seeingParticles;
}
public boolean toggleSeeingParticles() { public boolean toggleSeeingParticles() {
seeingParticles = !seeingParticles; seeingParticles = !seeingParticles;
return seeingParticles; return seeingParticles;
} }
public UUID getUuid() {
return uuid;
}
public HashMap<APartType, ParticleSet> getParticles() {
return particles;
}
public void addParticle(APartType aPartType, ParticleSet particleSet) { public void addParticle(APartType aPartType, ParticleSet particleSet) {
particles.put(aPartType, particleSet); particles.put(aPartType, particleSet);
} }
+6
View File
@@ -2,6 +2,8 @@ package com.alttd.util;
import com.alttd.AltitudeParticles; import com.alttd.AltitudeParticles;
import java.util.logging.Level;
public class Logger { public class Logger {
static private final java.util.logging.Logger logger; static private final java.util.logging.Logger logger;
@@ -33,4 +35,8 @@ public class Logger {
} }
logger.severe(severe); logger.severe(severe);
} }
public static void error(String error, Throwable throwable) {
logger.log(Level.SEVERE, error, throwable);
}
} }