Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c5b8bcc31
|
||
|
|
31a7b7c087
|
||
|
|
eff7e517a6 | ||
|
|
2a34066187 | ||
|
|
35bbe9ecba | ||
|
|
7197787ad3 | ||
|
|
f93401ff26 | ||
|
|
6169116dc7 | ||
|
|
3b13e277f7 | ||
|
|
a8bb0f159a | ||
|
|
aa76e82b16 | ||
|
|
9c6f94c10b | ||
|
|
fec77fba15 | ||
|
|
3a5625508b | ||
|
|
cb864f7eba | ||
|
|
9d50254dec | ||
|
|
2bfd3c48b6 | ||
|
|
c6df9f029a | ||
|
|
cc6e38c7f2 | ||
|
|
c22f4f0efe | ||
|
|
71cd756337 | ||
|
|
4a5543da2a | ||
|
|
5a8682dc26 | ||
|
|
0ed4e78afd | ||
|
|
6b049d98b0 | ||
|
|
791e0575a9 | ||
|
|
35faf08cfa | ||
|
|
622c23a729 | ||
|
|
2eba6ec2ab | ||
|
|
8783dd0683 | ||
|
|
e861daa8c1 | ||
|
|
c970c1af6f | ||
|
|
921c009a59 | ||
|
|
ea0c2736e1 | ||
|
|
25411ba54f | ||
|
|
715013d90f | ||
|
|
a59ff6e625 | ||
|
|
bf609a1964 | ||
|
|
af5446f33e | ||
|
|
da3ceeca55 | ||
|
|
f665d1e13e | ||
|
|
8e52dae5b2 | ||
|
|
01188bc79f | ||
|
|
664d3899d7 | ||
|
|
60f0b37adc | ||
|
|
511c634c41 | ||
|
|
a3b5999de3 | ||
|
|
1666d815b2 | ||
|
|
b447154d52 | ||
|
|
73e862a782 | ||
|
|
6d1ab1acbe | ||
|
|
151eb58fb6 | ||
|
|
1beedd84d0 | ||
|
|
bc3175faed | ||
|
|
58f61073c6 | ||
|
|
26c72b5490 | ||
|
|
991e70e676 | ||
|
|
c8519f4d74 | ||
|
|
c9fef78eac | ||
|
|
0ce7104f72 | ||
|
|
74e7c3930c | ||
|
|
31ab0aa7ff | ||
|
|
fc34b3402e | ||
|
|
db6440d87c | ||
|
|
0119309ffb | ||
|
|
f31fcc437f | ||
|
|
ab4d9d13c9 | ||
|
|
052454fee0 | ||
|
|
0f0b9f2cec | ||
|
|
2eb1fff556 | ||
|
|
b4f8786683 | ||
|
|
5c7f314071 | ||
|
|
73ab2388dc | ||
|
|
7c129185c5 | ||
|
|
ac5bd598f0 | ||
|
|
98f23966db | ||
|
|
0803d2800f | ||
|
|
83dab3cb8c | ||
|
|
768bc20e14 | ||
|
|
f3bd42ff2f | ||
|
|
a56fd79d29 | ||
|
|
e1b2487396 | ||
|
|
f19499205f | ||
|
|
39e8cbddcb | ||
|
|
42c3129060 | ||
|
|
a6a2577e07 | ||
|
|
47ff08d62a | ||
|
|
619e50dd6a | ||
|
|
98cbf4adfc | ||
|
|
185bb72f10 | ||
|
|
7b5949dba6 | ||
|
|
0be787c1e2 | ||
|
|
74ee5d8c7e | ||
|
|
2d98d4cbff | ||
|
|
c2bacd2f5c | ||
|
|
164d073861 | ||
|
|
77c4dde70f | ||
|
|
3745648821 | ||
|
|
b339a53dc8 | ||
|
|
3895b35941 | ||
|
|
ac5175b63c | ||
|
|
8e61e44012 | ||
|
|
233a1e04d3 | ||
|
|
170caff375 | ||
|
|
a2cc42a0a7 | ||
|
|
ae76933a5d | ||
|
|
992ab4002a | ||
|
|
bb5b39810c | ||
|
|
dc7edf4361 | ||
|
|
702618482d | ||
|
|
a35b208df2 | ||
|
|
a51e9ac32e | ||
|
|
f4df09802b | ||
|
|
0a08b76d35 | ||
|
|
f7e572ef02 | ||
|
|
40d60b62a2 | ||
|
|
92f0cf7729 | ||
|
|
b34417d1c8 | ||
|
|
b9cc9f1f7f | ||
|
|
0c7b6effde | ||
|
|
f2807153b5 | ||
|
|
4a460f28cd | ||
|
|
fb62b8d99d | ||
|
|
e056cec07c | ||
|
|
e18a58e4f2 | ||
|
|
36a2bb5165 | ||
|
|
7a898acfd9 | ||
|
|
ac5d3307ed | ||
|
|
a652147e2c | ||
|
|
f7c4e179b7 | ||
|
|
3991e8f09a | ||
|
|
44239355b9 | ||
|
|
0b6af2aacd | ||
|
|
85c6a2cf14 | ||
|
|
ca937a86d0 | ||
|
|
8a2f85fadc | ||
|
|
24b32f2eca | ||
|
|
7bfe5c584f | ||
|
|
e904f44a5f | ||
|
|
9797780d81 | ||
|
|
9da919e910 | ||
|
|
fe395f2cbd | ||
|
|
581bef78fe | ||
|
|
35e19c56b1 | ||
|
|
e2514fd229 | ||
|
|
1fceee5319 | ||
|
|
07b34d4744 | ||
|
|
b8ac667e5f | ||
|
|
a467a06df4 | ||
|
|
50bde1375a | ||
|
|
6ce4469db9 | ||
|
|
d63e4a0c29 | ||
|
|
e5b70523bc | ||
|
|
cf0e5decd7 | ||
|
|
cbe1c3c46e | ||
|
|
1db1e02c8b | ||
|
|
7a9fee6e2d | ||
|
|
addb077133 | ||
|
|
1fcbd33a62 | ||
|
|
f6e2498722 | ||
|
|
e6367842ed | ||
|
|
380174dade | ||
|
|
dab6b7a85b | ||
|
|
4124c3ade3 | ||
|
|
9abe7259a2 | ||
|
|
79656875c3 | ||
|
|
bc6872d56f | ||
|
|
fb24f31146 | ||
|
|
4df4b6c637 | ||
|
|
c15caa32e3 | ||
|
|
833559eec9 | ||
|
|
c3e6f06b9f | ||
|
|
af39cda3b8 | ||
|
|
98d39570d8 | ||
|
|
be88498fe5 | ||
|
|
1250cc1abc |
No files matched your search
@@ -0,0 +1 @@
|
||||
.gitea/CODEOWNERS linguist-detectable=false
|
||||
@@ -0,0 +1,3 @@
|
||||
# Pull requests request review from the eligible staff team(s).
|
||||
# One approval from either an Admin or Developer satisfies branch protection.
|
||||
* @trueog/Admins @trueog/Developers
|
||||
@@ -19,39 +19,17 @@ jobs:
|
||||
- name: Checkout main repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
# 2. Install JDK 21 – NO Gradle cache here
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v2
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '21'
|
||||
distribution: 'adopt'
|
||||
distribution: temurin
|
||||
java-version: 21
|
||||
cache: '' # ← disable Maven/Gradle cache
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/gradle-build-action@v2
|
||||
with:
|
||||
gradle-version: 8.8
|
||||
|
||||
# Temporary workaround to packetevents bugs, use custom fork build
|
||||
- name: Checkout packetevents repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
repository: Axionize/packetevents
|
||||
ref: 2.0-fabric-serverside-fix
|
||||
path: packetevents
|
||||
|
||||
- name: Update version in packetevents
|
||||
run: |
|
||||
cd packetevents
|
||||
sed -i 's/val fullVersion = ".*"/val fullVersion = "2.5.8"/' build.gradle.kts
|
||||
|
||||
- name: Build packetevents with Gradle
|
||||
run: |
|
||||
cd packetevents
|
||||
gradle build -x test
|
||||
|
||||
- name: Publish packetevents to Maven Local
|
||||
run: |
|
||||
cd packetevents
|
||||
gradle publishToMavenLocal
|
||||
# 3. Set up Gradle + dependency cache
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
|
||||
- name: Generate build number
|
||||
id: buildnumber
|
||||
@@ -75,37 +53,26 @@ jobs:
|
||||
# Ensure snapshot is set to false
|
||||
sed -i "s/val snapshot = .*/val snapshot = false/" build.gradle.kts
|
||||
|
||||
- name: Build with Gradle
|
||||
run: gradle clean build -x test
|
||||
- name: Build without PE shaded
|
||||
run: ./gradlew build -PshadePE=false -x test
|
||||
env:
|
||||
GITHUB_REPOSITORY: ${{ github.repository }}
|
||||
|
||||
- name: Rename shaded jar to overwrite non-shaded jar
|
||||
run: mv bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}-all.jar bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
- name: Build with PE shaded Gradle
|
||||
run: ./gradlew build -PshadePE=true -x test
|
||||
env:
|
||||
GITHUB_REPOSITORY: ${{ github.repository }}
|
||||
|
||||
# Download PaperSpigot (Choose version for reproducibility
|
||||
- name: Download PaperSpigot
|
||||
run: |
|
||||
mkdir -p paper-server/plugins
|
||||
curl -o paperclip.jar https://api.papermc.io/v2/projects/paper/versions/1.21.1/builds/120/downloads/paper-1.21.1-120.jar
|
||||
mv paperclip.jar paper-server/
|
||||
|
||||
# Copy Plugin into Plugins Folder and Start Server
|
||||
- name: Copy Plugin and Start Paper Server
|
||||
run: |
|
||||
cp bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar paper-server/plugins/
|
||||
cd paper-server
|
||||
# Start the server to remap the plugin
|
||||
timeout 60 java -Xms3G -Xmx3G -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1 -jar -Dcom.mojang.eula.agree=true paperclip.jar --nogui || true
|
||||
|
||||
# Get the Hashes of the Original and Remapped JARs
|
||||
# Get the Hashes of the Original and Lite JARs
|
||||
- name: Calculate Hashes
|
||||
run: |
|
||||
# Calculate hash for the original JAR
|
||||
ORIGINAL_HASH=$(sha256sum bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "ORIGINAL_HASH=$ORIGINAL_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the remapped JAR
|
||||
REMAPPED_HASH=$(sha256sum paper-server/plugins/.paper-remapped/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "REMAPPED_HASH=$REMAPPED_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the remapped JAR
|
||||
BUKKIT_HASH=$(sha256sum bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "BUKKIT_HASH=$BUKKIT_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the lite JAR
|
||||
BUKKIT_LITE_HASH=$(sha256sum bukkit/build/libs/knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "BUKKIT_LITE_HASH=$BUKKIT_LITE_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the lite JAR
|
||||
FABRIC_HASH=$(sha256sum fabric/build/libs/knockbacksync-fabric-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "FABRIC_HASH=$FABRIC_HASH" >> $GITHUB_ENV
|
||||
|
||||
@@ -115,64 +82,85 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
# Download the current dev-builds.txt
|
||||
curl -L -o dev-builds.txt https://github.com/Axionize/knockback-sync/releases/download/hashlist/dev-builds.txt
|
||||
curl -L -o dev-builds.txt https://github.com/${{ github.repository }}/releases/latest/download/dev-builds.txt
|
||||
|
||||
# Ensure the file ends with a newline, then append new information
|
||||
# Create a copy of the original file
|
||||
cp dev-builds.txt dev-builds.txt.original
|
||||
|
||||
# Ensure the file ends with a newline
|
||||
sed -i -e '$a\' dev-builds.txt
|
||||
# echo "KnockBackSync-${{ env.NEW_VERSION }}.jar" >> dev-builds.txt
|
||||
echo "${{ env.ORIGINAL_HASH }}" >> dev-builds.txt
|
||||
# echo "KnockBackSync-${{ env.NEW_VERSION }}-remapped.jar" >> dev-builds.txt
|
||||
echo "${{ env.REMAPPED_HASH }}" >> dev-builds.txt
|
||||
|
||||
echo "${{ env.FABRIC_HASH }}" >> dev-builds.txt
|
||||
# Function to add hash if it doesn't exist
|
||||
add_hash_if_new() {
|
||||
if ! grep -q "$1" dev-builds.txt; then
|
||||
echo "$1" >> dev-builds.txt
|
||||
fi
|
||||
}
|
||||
|
||||
# Get the release ID for the 'hashlist' release
|
||||
RELEASE_ID=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
|
||||
"https://api.github.com/repos/Axionize/knockback-sync/releases/tags/hashlist" | jq -r .id)
|
||||
# Add new hashes if they don't exist
|
||||
add_hash_if_new "${{ env.BUKKIT_HASH }}"
|
||||
add_hash_if_new "${{ env.BUKKIT_LITE_HASH }}"
|
||||
add_hash_if_new "${{ env.FABRIC_HASH }}"
|
||||
|
||||
# Delete the old dev-builds.txt asset
|
||||
ASSET_ID=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
|
||||
"https://api.github.com/repos/Axionize/knockback-sync/releases/$RELEASE_ID/assets" | \
|
||||
jq -r '.[] | select(.name == "dev-builds.txt") | .id')
|
||||
if [ ! -z "$ASSET_ID" ]; then
|
||||
curl -X DELETE -H "Authorization: token $GITHUB_TOKEN" \
|
||||
"https://api.github.com/repos/Axionize/knockback-sync/releases/assets/$ASSET_ID"
|
||||
# Check if the file has changed
|
||||
if cmp -s dev-builds.txt dev-builds.txt.original; then
|
||||
echo "No changes to dev-builds.txt, skipping upload."
|
||||
else
|
||||
echo "Changes detected in dev-builds.txt, uploading new version."
|
||||
|
||||
# Get the latest release ID
|
||||
RELEASE_ID=$(curl -s "https://api.github.com/repos/${{ github.repository }}/releases/latest" | jq -r .id)
|
||||
|
||||
# Delete the old dev-builds.txt asset
|
||||
ASSET_ID=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases/$RELEASE_ID/assets" | \
|
||||
jq -r '.[] | select(.name == "dev-builds.txt") | .id')
|
||||
if [ ! -z "$ASSET_ID" ]; then
|
||||
curl -X DELETE -H "Authorization: token $GITHUB_TOKEN" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases/assets/$ASSET_ID"
|
||||
fi
|
||||
|
||||
# Upload the new dev-builds.txt
|
||||
curl -X POST -H "Authorization: token $GITHUB_TOKEN" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @dev-builds.txt \
|
||||
"https://uploads.github.com/repos/${{ github.repository }}/releases/$RELEASE_ID/assets?name=dev-builds.txt"
|
||||
fi
|
||||
|
||||
# Upload the new dev-builds.txt
|
||||
curl -X POST -H "Authorization: token $GITHUB_TOKEN" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @dev-builds.txt \
|
||||
"https://uploads.github.com/repos/Axionize/knockback-sync/releases/$RELEASE_ID/assets?name=dev-builds.txt"
|
||||
# Clean up
|
||||
rm dev-builds.txt.original
|
||||
|
||||
- name: Create artifacts directory
|
||||
run: mkdir -p artifacts
|
||||
|
||||
- name: Copy bukkit artifact
|
||||
run: cp bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar artifacts/
|
||||
|
||||
- name: Copy fabric artifact
|
||||
run: cp fabric/build/libs/knockbacksync-fabric-${{ env.NEW_VERSION }}.jar artifacts/
|
||||
|
||||
- name: Zip the artifacts
|
||||
run: zip -r KnockbackSync-${{ env.NEW_VERSION }}.zip artifacts/*
|
||||
|
||||
- name: Upload artifacts zip
|
||||
- name: Upload Bukkit Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: KnockbackSync-${{ env.NEW_VERSION }}.zip
|
||||
path: KnockbackSync-${{ env.NEW_VERSION }}.zip
|
||||
name: knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
path: bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
retention-days: 90
|
||||
|
||||
- name: Upload Bukkit Lite Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar
|
||||
path: bukkit/build/libs/knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar
|
||||
retention-days: 90
|
||||
|
||||
- name: Upload Fabric Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: knockbacksync-fabric-${{ env.NEW_VERSION }}.jar
|
||||
path: fabric/build/libs/knockbacksync-fabric-${{ env.NEW_VERSION }}.jar
|
||||
retention-days: 90
|
||||
|
||||
- uses: Kir-Antipov/mc-publish@v3.3
|
||||
with:
|
||||
modrinth-id: wGTbjSTq
|
||||
modrinth-id: ${{ vars.MODRINTH_ID }}
|
||||
modrinth-featured: true
|
||||
modrinth-unfeature-mode: subset
|
||||
modrinth-token: ${{ secrets.MODRINTH_TOKEN }}
|
||||
|
||||
files: |
|
||||
bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
bukkit/build/libs/knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar
|
||||
|
||||
name: KnockbackSync-${{ env.NEW_VERSION }}
|
||||
version: ${{ env.NEW_VERSION }}
|
||||
@@ -183,9 +171,10 @@ jobs:
|
||||
spigot
|
||||
paper
|
||||
folia
|
||||
purpur
|
||||
|
||||
game-versions: |
|
||||
>=1.16.5
|
||||
>=1.12.2
|
||||
|
||||
retry-attempts: 2
|
||||
retry-delay: 10000
|
||||
@@ -193,7 +182,7 @@ jobs:
|
||||
|
||||
- uses: Kir-Antipov/mc-publish@v3.3
|
||||
with:
|
||||
modrinth-id: wGTbjSTq
|
||||
modrinth-id: ${{ vars.MODRINTH_ID }}
|
||||
modrinth-featured: true
|
||||
modrinth-unfeature-mode: subset
|
||||
modrinth-token: ${{ secrets.MODRINTH_TOKEN }}
|
||||
@@ -209,7 +198,10 @@ jobs:
|
||||
fabric
|
||||
|
||||
game-versions: |
|
||||
>=1.21
|
||||
1.21.11
|
||||
|
||||
dependencies: |
|
||||
fabric-api
|
||||
|
||||
retry-attempts: 2
|
||||
retry-delay: 10000
|
||||
|
||||
+5
-2
@@ -7,9 +7,12 @@ dependency-reduced-pom.xml
|
||||
# Ignore maven build files
|
||||
target/
|
||||
|
||||
# Eclipse files
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
|
||||
.gradle/
|
||||
gradle/
|
||||
build/
|
||||
|
||||
run/
|
||||
run/
|
||||
+5
-9
@@ -1,4 +1,4 @@
|
||||
Project Structure
|
||||
## Project Structure
|
||||
|
||||
- `common` submodule contains shared code for all platforms.
|
||||
- It contains the interfaces and abstractions for
|
||||
@@ -6,11 +6,11 @@ Project Structure
|
||||
- Scheduling
|
||||
- Players
|
||||
- Blocks
|
||||
- World
|
||||
- Worlds/Levels
|
||||
- The Server
|
||||
- In addition to the interfaces, the code also contains the implementations for
|
||||
- Commands
|
||||
- Commands use Brigadier with Reflection to handle version differences. Simply call our command code in common by registering KnockBackSyncCommand.build() and implementing CommandOperations
|
||||
- Commands use incendio's `cloud` command system. All you have to do to add platform support is to create a CommandManager and call register().
|
||||
- Handling Events
|
||||
- Gathering Statistics
|
||||
- `fabric` contains code for latest fabric version (currently 1.21)
|
||||
@@ -21,6 +21,7 @@ If you want to add support for a new platform, simply make a new submodule and i
|
||||
- Checking for Permissions
|
||||
- Listening for events and calling the right handler
|
||||
- Players + Blocks + World + Server
|
||||
- Metrics
|
||||
|
||||
You will need to handle events when Players:
|
||||
- join/leave
|
||||
@@ -31,9 +32,4 @@ If you find your platform is lacking events, take a look at how the PlayerVeloci
|
||||
|
||||
|
||||
## List of version and platform-specific caveats
|
||||
- Runnable and manual ping does not work on fabric right now due b/c packetevents. Ping measurement will be less accurate
|
||||
|
||||
- Command System
|
||||
- context.getSource().sendSuccess() takes a Supplier<Component> in > 1.19.4
|
||||
- context.getSource().sendSuccess() takes a Component in <= 1.19.4
|
||||
- Component.literal() does not exist in <= 1.18.2
|
||||
- Runnable and manual ping does not work on fabric right now due b/c packetevents. Ping measurement will be less accurate
|
||||
@@ -0,0 +1,37 @@
|
||||
KnockbackSync
|
||||
=============
|
||||
|
||||
KnockbackSync is licensed under the GNU General Public License v3.0 or later.
|
||||
See README.md (section "License") and https://www.gnu.org/licenses/gpl-3.0.en.html.
|
||||
|
||||
Bundled / ported third-party code
|
||||
----------------------------------
|
||||
|
||||
This distribution contains a port of the 1.8 melee knockback formula from:
|
||||
|
||||
BukkitOldCombatMechanics (OldCombatMechanics)
|
||||
Copyright (c) the OldCombatMechanics contributors (kernitus et al.)
|
||||
https://github.com/kernitus/BukkitOldCombatMechanics
|
||||
Licensed under the Mozilla Public License, Version 2.0 (MPL-2.0)
|
||||
https://mozilla.org/MPL/2.0/
|
||||
|
||||
The ported code lives in:
|
||||
|
||||
common/src/main/java/me/caseload/knockbacksync/util/LegacyKnockback.java
|
||||
|
||||
It is derived from OldCombatMechanics' module
|
||||
`kernitus.plugin.OldCombatMechanics.module.ModulePlayerKnockback`.
|
||||
|
||||
License compatibility
|
||||
---------------------
|
||||
|
||||
The OldCombatMechanics source files are distributed under the standard MPL-2.0
|
||||
notice (Exhibit A) and do NOT carry the "Incompatible With Secondary Licenses"
|
||||
notice (Exhibit B). Under MPL-2.0 section 3.3, such Covered Software may be
|
||||
distributed as part of a Larger Work governed by a "Secondary License" — which
|
||||
MPL-2.0 section 1.12 defines to include the GNU General Public License, Version
|
||||
3. Accordingly, the ported file may be combined with and distributed alongside
|
||||
the GPL-3.0-or-later code that makes up the rest of KnockbackSync.
|
||||
|
||||
The terms of the MPL-2.0 continue to govern the ported file itself; its MPL
|
||||
header is retained. The combined/Larger Work is offered under GPL-3.0-or-later.
|
||||
@@ -1,172 +1,15 @@
|
||||
[](https://modrinth.com/plugin/knockbacksync)
|
||||
# KnockbackSync-OG
|
||||
|
||||
Tired of inconsistent knockback ruining your PvP experience? Our plugin recalculates knockback as if it were done clientside, leveling the playing field and ensuring every player enjoys a fair fight, no matter their connection quality.
|
||||
|
||||
Minecraft doesn’t factor in network latency when determining a player's actions on the server. This causes the server to receive outdated information that doesn’t reflect the player's clientside position, leading to varying knockback effects based on connection quality.
|
||||
|
||||
This plugin intercepts and adjusts knockback calculations to match what would occur clientside, effectively mitigating the disadvantages caused by high latency. By synchronizing knockback handling, we ensure that players experience consistent and fair knockback, providing a balanced and competitive environment for all."
|
||||
|
||||
Showcase: https://www.youtube.com/watch?v=SVokpr3v-TA
|
||||
|
||||
Official Discord: https://discord.gg/nnpqpAtyVW
|
||||
|
||||
## Frequently Asked Questions (FAQ)
|
||||
|
||||
### Does this change put high ping players at a disadvantage?
|
||||
**It depends on the player.** Some may notice a difference if they're used to relying on high ping to reduce knockback. For others, it could actually be an advantage.
|
||||
|
||||
### How does this change benefit high ping players?
|
||||
**Knockback control.** For example, it will be easier to escape crit chains and punish crit.
|
||||
|
||||
### How do I change the ping offset?
|
||||
Open up `config.yml` and edit the line that says `ping_offset: 25`. Replace 25 with your desired ping offset.
|
||||
;
|
||||
Then just type
|
||||
```
|
||||
/knockbacksync reload
|
||||
```
|
||||
or restart your server.
|
||||
|
||||
## What servers are using this plugin?
|
||||
| IP | Location | Region | Ping Offset | spike_threshold |
|
||||
|------------------|-----------------------------------|--------|-------------|-----------------|
|
||||
| `pvparcade.club` | Ashburn, Virginia, United States | NA | 20 | 15 |
|
||||
| `stray.gg` | Ashburn, Virginia, United States | NA | 25 | 20 |
|
||||
| `eu.stray.gg` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
|
||||
| `valed.gg` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
|
||||
| `eu.catpvp.xyz` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
|
||||
| `as.catpvp.xyz` | Singapore | AS | 25 | 20 |
|
||||
| `na.catpvp.xyz` | New York, New York, United States | NA | 25 | 20 |
|
||||
| `hyperium.pl` | Wrocław, Dolnośląskie, Poland | EU | 25 | 20 |
|
||||
|
||||
## Commands
|
||||
---
|
||||
### /knockbacksync ping [target]
|
||||
|
||||
**Description:**
|
||||
|
||||
This command allows you to check the ping of a player, including jitter. If no target is specified, it will check your own ping.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.ping` (defaults to true for players)
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync ping`: Checks your own ping.
|
||||
* `/knockbacksync ping Steve`: Checks the ping of a player named Steve.
|
||||
|
||||
**Output:**
|
||||
|
||||
* If a pong packet has been received: "Your last ping packet took [ping]ms. Jitter: [jitter]ms." or "[Player]'s last ping packet took [ping]ms. Jitter: [jitter]ms."
|
||||
* If a pong packet has not been received: "Pong not received. Your estimated ping is [estimated ping]ms." or "Pong not received. [Player]'s estimated ping is [estimated ping]ms."
|
||||
|
||||
**Notes:**
|
||||
|
||||
* The estimated ping is based on the player's platform reported ping.
|
||||
* Jitter represents the variation in ping over time.
|
||||
---
|
||||
### /knockbacksync status [target]
|
||||
|
||||
**Description:**
|
||||
|
||||
This command allows you to check the KnockbackSync status of a player or the server. If no target is specified, it will show both the global status and your own status.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.status.self` (defaults to true for players): Allows checking your own status.
|
||||
* `knockbacksync.status.other` (defaults to op only): Allows checking the status of other players.
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync status`: Shows the global status and your own status.
|
||||
* `/knockbacksync status Steve`: Shows the status of a player named Steve.
|
||||
|
||||
**Output:**
|
||||
|
||||
* **Global status:** "Global KnockbackSync status: [Enabled/Disabled]"
|
||||
* **Player status:** "[Player]'s KnockbackSync status: [Enabled/Disabled]" (or "Disabled (Global toggle is off)" if the global toggle is off)
|
||||
|
||||
**Notes:**
|
||||
|
||||
* The player status will be "Disabled" if the global toggle is off, even if the player has individually enabled KnockbackSync.
|
||||
* The messages displayed by this command are configurable in the `config.yml` file.
|
||||
---
|
||||
### /knockbacksync toggle [target]
|
||||
|
||||
**Description:**
|
||||
|
||||
This command allows you to toggle KnockbackSync for yourself, another player, or globally.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.toggle.self` (defaults to true for players): Allows toggling KnockbackSync for yourself.
|
||||
* `knockbacksync.toggle.other` (defaults to op only): Allows toggling KnockbackSync for other players.
|
||||
* `knockbacksync.toggle.global` (defaults to op only): Allows toggling KnockbackSync globally for the server.
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync toggle`: Toggles KnockbackSync globally (if you have permission) or for yourself.
|
||||
* `/knockbacksync toggle Steve`: Toggles KnockbackSync for a player named Steve.
|
||||
|
||||
**Output:**
|
||||
|
||||
* **Global toggle:** Sends a message indicating whether KnockbackSync has been enabled or disabled globally. The messages are configurable in the `config.yml` file.
|
||||
* **Player toggle:** Sends a message indicating whether KnockbackSync has been enabled or disabled for the specified player. The messages are configurable in the `config.yml` file.
|
||||
* **Ineligible player:** If a player is ineligible for KnockbackSync (e.g., due to permissions), a configurable message will be sent.
|
||||
* **KnockbackSync disabled:** If KnockbackSync is disabled globally and you try to toggle it for a player, a message will be sent indicating that KnockbackSync is disabled.
|
||||
|
||||
**Notes:**
|
||||
|
||||
* If KnockbackSync is disabled globally, toggling it for a player will have no effect until KnockbackSync is enabled globally.
|
||||
* Players can only toggle KnockbackSync for themselves if they have the `knockbacksync.toggle.self` permission.
|
||||
* Operators can toggle KnockbackSync for other players and globally.
|
||||
---
|
||||
### /knockbacksync reload
|
||||
|
||||
**Description:**
|
||||
|
||||
This command reloads the KnockbackSync plugin's configuration file.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.reload` (defaults to op only)
|
||||
|
||||
**Examples:**
|
||||
* `/knockbacksync reload`
|
||||
|
||||
**Output:**
|
||||
|
||||
* Sends a message to the command sender indicating that the configuration has been reloaded. The message is configurable in the `config.yml` file.
|
||||
|
||||
**Notes:**
|
||||
|
||||
* This command is useful for applying changes made to the configuration file without restarting the server.
|
||||
---
|
||||
### /knockbacksync toggleoffground
|
||||
|
||||
**Description:**
|
||||
|
||||
This command toggles the experimental off-ground knockback synchronization feature.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.toggleoffground` (defaults to op only)
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync toggleoffground`
|
||||
|
||||
**Output:**
|
||||
|
||||
* Sends a message indicating whether the experimental off-ground knockback synchronization has been enabled or disabled. The messages are configurable in the `config.yml` file.
|
||||
|
||||
**Notes:**
|
||||
|
||||
* **This command currently does not do anything as off-ground synchronization has yet to be implemented.**
|
||||
* This feature is experimental and may not work as expected.
|
||||
Soft fork of KnockbackSync to ensure compatibility with OldCombatMechanics on Purpur 1.19.4.
|
||||
|
||||
## License
|
||||
GNU General Public License v3.0 or later
|
||||
|
||||
See [LICENSE](LICENSE) to see the full text.
|
||||
See [LICENSE](https://www.gnu.org/licenses/gpl-3.0.en.html) to see the full text.
|
||||
|
||||
The optional legacy (1.8) knockback formula
|
||||
(`common/src/main/java/me/caseload/knockbacksync/util/LegacyKnockback.java`) is a
|
||||
port from [OldCombatMechanics](https://github.com/kernitus/BukkitOldCombatMechanics),
|
||||
which is licensed under the Mozilla Public License 2.0 (MPL-2.0). MPL-2.0 permits
|
||||
combining that code into this GPL-3.0-or-later work as a Larger Work (MPL-2.0
|
||||
§3.3 / §1.12). See the [NOTICE](NOTICE) file for details.
|
||||
+61
-28
@@ -1,27 +1,57 @@
|
||||
import java.io.ByteArrayOutputStream
|
||||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("com.gradleup.shadow") version "8.3.3" apply false
|
||||
id("fabric-loom") version "1.7.4" apply false
|
||||
eclipse
|
||||
id("com.gradleup.shadow") version "9.2.2" apply false
|
||||
}
|
||||
|
||||
fun getGitCommitHash(project: Project): String? {
|
||||
// Only try to get the hash if the .git directory exists
|
||||
if (!project.file(".git").isDirectory) {
|
||||
return null
|
||||
}
|
||||
return try {
|
||||
val process = ProcessBuilder("git", "rev-parse", "--short", "HEAD")
|
||||
.redirectOutput(ProcessBuilder.Redirect.PIPE)
|
||||
.redirectError(ProcessBuilder.Redirect.PIPE)
|
||||
.start()
|
||||
|
||||
process.waitFor(5, TimeUnit.SECONDS)
|
||||
|
||||
if (process.exitValue() == 0) {
|
||||
process.inputStream.bufferedReader().readText().trim().takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
val fullVersion = "1.3.5"
|
||||
val snapshot = true
|
||||
val githubRepo = System.getenv("GITHUB_REPOSITORY") ?: project.findProperty("githubRepo").toString()
|
||||
|
||||
// Suite default external provider; shaded standalone via -PshadePE=true.
|
||||
extra["shadePE"] = project.findProperty("shadePE")?.toString()?.toBoolean()
|
||||
?: System.getenv("SHADE_PE")?.toBoolean()
|
||||
?: false
|
||||
|
||||
extra["relocate"] = project.findProperty("relocate")?.toString()?.toBoolean()
|
||||
?: System.getenv("RELOCATE_JAR")?.toBoolean()
|
||||
?: true
|
||||
|
||||
allprojects {
|
||||
fun getVersionMeta(includeHash: Boolean): String {
|
||||
if (!snapshot) {
|
||||
return ""
|
||||
}
|
||||
var commitHash = ""
|
||||
if (includeHash && file(".git").isDirectory) {
|
||||
val stdout = ByteArrayOutputStream()
|
||||
exec {
|
||||
commandLine("git", "rev-parse", "--short", "HEAD")
|
||||
standardOutput = stdout
|
||||
}
|
||||
commitHash = "+${stdout.toString().trim()}"
|
||||
val commitHash = if (includeHash) {
|
||||
getGitCommitHash(project)?.let { "+$it" } ?: ""
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "$commitHash-SNAPSHOT"
|
||||
}
|
||||
@@ -29,9 +59,11 @@ allprojects {
|
||||
group = "me.caseload.knockbacksync"
|
||||
version = "$fullVersion${getVersionMeta(true)}"
|
||||
ext["versionNoHash"] = "$fullVersion${getVersionMeta(false)}"
|
||||
ext["githubRepo"] = githubRepo
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
// mavenLocal()
|
||||
maven("https://repo.grim.ac/snapshots")
|
||||
mavenCentral()
|
||||
maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/")
|
||||
maven("https://repo.codemc.io/repository/maven-releases/")
|
||||
@@ -52,21 +84,22 @@ subprojects {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
// if (project.name != "common") {
|
||||
// tasks.withType<JavaCompile> {
|
||||
// source(project(":common").sourceSets.main.get().allSource)
|
||||
// }
|
||||
// tasks.withType<Javadoc> {
|
||||
// source(project(":common").sourceSets.main.get().allJava)
|
||||
// }
|
||||
|
||||
// tasks.named<Jar>("sourcesJar") {
|
||||
// from(project(":common").sourceSets.main.get().allSource)
|
||||
// }
|
||||
|
||||
// tasks.named<JavaCompile>("compileTestJava") {
|
||||
// exclude("**/*")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
// The root project has no plugin entrypoint; do not emit an empty deployable-looking JAR.
|
||||
enabled = false
|
||||
}
|
||||
|
||||
val copyBukkitPluginJar by tasks.registering(Copy::class) {
|
||||
val bukkitShadowJar = project(":bukkit").tasks.named<ShadowJar>("shadowJar")
|
||||
|
||||
dependsOn(bukkitShadowJar)
|
||||
from(bukkitShadowJar.flatMap { it.archiveFile })
|
||||
into(layout.buildDirectory.dir("libs"))
|
||||
rename { "KnockbackSync-OG-$fullVersion${if (snapshot) "-SNAPSHOT" else ""}.jar" }
|
||||
}
|
||||
|
||||
tasks.assemble {
|
||||
dependsOn(copyBukkitPluginJar)
|
||||
}
|
||||
+32
-63
@@ -2,14 +2,12 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
id("com.gradleup.shadow")
|
||||
// id("io.papermc.paperweight.userdev") version "1.7.3"
|
||||
// id("net.neoforged.moddev") version "1.0.11"
|
||||
}
|
||||
|
||||
//paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.REOBF_PRODUCTION
|
||||
val shadePE: Boolean by rootProject.extra
|
||||
|
||||
base {
|
||||
archivesName.set("${rootProject.property("archives_base_name")}-bukkit")
|
||||
archivesName.set("${rootProject.property("archives_base_name")}-bukkit${if (shadePE) "" else "-lite"}")
|
||||
}
|
||||
|
||||
val shadeThisThing: Configuration by configurations.creating {
|
||||
@@ -17,23 +15,9 @@ val shadeThisThing: Configuration by configurations.creating {
|
||||
isTransitive = true
|
||||
}
|
||||
|
||||
//sourceSets {
|
||||
// main {
|
||||
// java {
|
||||
// srcDir(project(":common").sourceSets.main.get().java.srcDirs)
|
||||
// }
|
||||
// resources {
|
||||
// srcDir(project(":common").sourceSets.main.get().resources.srcDirs)
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
// TODO migrate to only including sourceset for compile, test and javadoc tasks
|
||||
// Currently must build with gradle build -x test to skip test
|
||||
// TODO migrate to only including sources sets for compile, test and javadoc tasks
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
source(project(":common").sourceSets.main.get().java.srcDirs)
|
||||
source(project(":common").sourceSets.main.get().resources.srcDirs())
|
||||
options.annotationProcessorPath = configurations["annotationProcessor"] + configurations["compileClasspath"]
|
||||
source(project(":common").sourceSets.main.get().allSource)
|
||||
}
|
||||
|
||||
tasks.withType<Javadoc>().configureEach {
|
||||
@@ -44,78 +28,63 @@ tasks.named<JavaCompile>("compileTestJava") {
|
||||
exclude("**/*")
|
||||
}
|
||||
|
||||
// Dirty hack exists so the build process will finish running
|
||||
//tasks.withType<Test>().configureEach {
|
||||
// classpath += project(":common").sourceSets["main"].output + configurations["compileClasspath"] + configurations["runtimeClasspath"]
|
||||
//}
|
||||
|
||||
|
||||
dependencies {
|
||||
// shadeThisThing(implementation(project(":common"))!!)
|
||||
implementation(project(":common"))
|
||||
|
||||
// paperweight.paperDevBundle("1.16.5-R0.1-SNAPSHOT")
|
||||
// compileOnly("com.mojang:brigadier:1.0.18")
|
||||
compileOnly("org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT")
|
||||
compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT")
|
||||
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
|
||||
// compileOnly("dev.folia:folia-api:1.20.4-R0.1-SNAPSHOT")
|
||||
compileOnly("io.netty:netty-all:4.1.72.Final")
|
||||
|
||||
compileOnly("org.projectlombok:lombok:1.18.34")
|
||||
annotationProcessor("org.projectlombok:lombok:1.18.34")
|
||||
|
||||
shadeThisThing(implementation("org.kohsuke:github-api:1.326")!!)
|
||||
if (shadePE) {
|
||||
shadeThisThing(implementation("com.github.retrooper:packetevents-spigot:2.11.2")!!)
|
||||
} else {
|
||||
compileOnly("com.github.retrooper:packetevents-spigot:2.11.2")
|
||||
}
|
||||
shadeThisThing(implementation("org.incendo:cloud-paper:2.0.0-beta.14")!!)
|
||||
shadeThisThing(implementation("org.incendo:cloud-core:2.0.0")!!)
|
||||
|
||||
// shadeThisThing(implementation("org.kohsuke:github-api:1.326") {
|
||||
// exclude(group = "commons-io", module = "commons-io")
|
||||
// exclude(group = "org.apache.commons", module = "commons-lang3")
|
||||
// })
|
||||
|
||||
|
||||
shadeThisThing(implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")!!)
|
||||
shadeThisThing(implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")!!)
|
||||
|
||||
shadeThisThing(implementation("com.github.retrooper:packetevents-spigot:2.5.0")!!)
|
||||
shadeThisThing(implementation("dev.jorel:commandapi-bukkit-shade:9.5.3")!!)
|
||||
// Required for 1.14.4 support because gson is too old to have JosnParser.parseString()
|
||||
shadeThisThing(implementation("com.google.code.gson:gson:2.11.0")!!)
|
||||
}
|
||||
|
||||
tasks.withType<ShadowJar> {
|
||||
// Exclude Java 21 specific classes
|
||||
// exclude("META-INF/**")
|
||||
manifest {
|
||||
attributes["paperweight-mappings-namespace"] = "mojang"
|
||||
}
|
||||
|
||||
// Remove the -all suffix from the output JAR file name
|
||||
archiveClassifier.set("")
|
||||
|
||||
// archiveClassifier.set("-all")
|
||||
configurations = listOf(shadeThisThing)
|
||||
isEnableRelocation = true
|
||||
enableAutoRelocation = true
|
||||
relocationPrefix = "${project.property("maven_group")}.${project.property("archives_base_name")}.shaded"
|
||||
}
|
||||
|
||||
//tasks.named("reobfJar") {
|
||||
// dependsOn(tasks.named("shadowJar"))
|
||||
//}
|
||||
|
||||
tasks.build {
|
||||
// dependsOn(tasks.named("reobfJar"))
|
||||
dependsOn(tasks.shadowJar)
|
||||
tasks.jar {
|
||||
// The shaded archive is the runtime plugin; do not emit a misleading thin plugin JAR.
|
||||
enabled = false
|
||||
}
|
||||
|
||||
tasks.build {
|
||||
dependsOn(tasks.shadowJar)
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
from(project(":common").sourceSets.main.get().resources)
|
||||
inputs.property("version", project.version)
|
||||
inputs.property("shadePE", shadePE) // Add shadePE as an input to trigger reprocessing if it changes
|
||||
filteringCharset = "UTF-8"
|
||||
|
||||
|
||||
filesMatching("plugin.yml") {
|
||||
expand(
|
||||
"version" to project.version,
|
||||
// Bukkit accepts `depend` only; `depends` is silently ignored.
|
||||
"depend" to if (shadePE) "[]" else listOf("PacketEvents")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
//neoForge {
|
||||
// Look for versions on https://projects.neoforged.net/neoforged/neoform
|
||||
// neoFormVersion.set("1.21-20240613.152323")
|
||||
//}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.protocol.world.Location;
|
||||
import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
|
||||
import me.caseload.knockbacksync.common.BuildConfig;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.listener.bukkit.*;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.permission.PluginPermissionChecker;
|
||||
import me.caseload.knockbacksync.scheduler.BukkitSchedulerAdapter;
|
||||
import me.caseload.knockbacksync.scheduler.FoliaSchedulerAdapter;
|
||||
import me.caseload.knockbacksync.sender.BukkitPlayerSelectorParser;
|
||||
import me.caseload.knockbacksync.sender.BukkitSenderFactory;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.stats.custom.BukkitStatsManager;
|
||||
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
|
||||
import me.caseload.knockbacksync.world.BukkitServer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.incendo.cloud.bukkit.CloudBukkitCapabilities;
|
||||
import org.incendo.cloud.execution.ExecutionCoordinator;
|
||||
import org.incendo.cloud.paper.LegacyPaperCommandManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class BukkitBase extends Base {
|
||||
|
||||
private final JavaPlugin plugin;
|
||||
private final BukkitSenderFactory bukkitSenderFactory = new BukkitSenderFactory(this);
|
||||
private final PluginPermissionChecker permissionChecker = new PluginPermissionChecker();
|
||||
|
||||
private int playerUpdateInterval;
|
||||
|
||||
private final MethodHandle tickRateMethodHandle;
|
||||
|
||||
public BukkitBase(JavaPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
super.configManager = new ConfigManager();
|
||||
super.playerSelectorParser = new BukkitPlayerSelectorParser<>();
|
||||
super.statsManager = new BukkitStatsManager(plugin);
|
||||
super.platformServer = new BukkitServer();
|
||||
super.pluginJarHashProvider = new PluginJarHashProvider(this.getClass().getProtectionDomain().getCodeSource().getLocation());
|
||||
this.playerUpdateInterval = this.getConfigManager().getConfigWrapper().getInt("entity_tick_intervals.player", 2);
|
||||
|
||||
MethodHandle handle = null;
|
||||
try {
|
||||
Server craftServer = Bukkit.getServer();
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
// Get handle for getServerTickManager
|
||||
MethodHandle getServerTickManager = lookup.findVirtual(craftServer.getClass(),
|
||||
"getServerTickManager", MethodType.methodType(Object.class));
|
||||
|
||||
Object serverTickManager = getServerTickManager.invoke(craftServer);
|
||||
|
||||
// Get handle for getTickRate
|
||||
handle = lookup.findVirtual(serverTickManager.getClass(),
|
||||
"getTickRate", MethodType.methodType(float.class));
|
||||
|
||||
} catch (Throwable t) {
|
||||
// If anything fails, handle will remain null
|
||||
}
|
||||
this.tickRateMethodHandle = handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Logger getLogger() {
|
||||
return this.plugin.getLogger();
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getDataFolder() {
|
||||
return this.plugin.getDataFolder();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getResource(String filename) {
|
||||
return this.plugin.getResource(filename);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
// External-provider mode delegates PacketEvents lifecycle to the installed PE plugin.
|
||||
if (!BuildConfig.SHADE_PE) {
|
||||
return;
|
||||
}
|
||||
PacketEvents.setAPI(SpigotPacketEventsBuilder.build(this.plugin));
|
||||
PacketEvents.getAPI().load();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enable() {
|
||||
super.enable();
|
||||
super.eventBus.registerListeners(this);
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_20_5) && this.getPlatform() == Platform.BUKKIT) {
|
||||
scheduler.runTaskTimerAsynchronously(this::setUpdateIntervals, 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeScheduler() {
|
||||
switch (getPlatform()) {
|
||||
case BUKKIT:
|
||||
super.scheduler = new BukkitSchedulerAdapter(this.plugin);
|
||||
break;
|
||||
case FOLIA:
|
||||
super.scheduler = new FoliaSchedulerAdapter(this.plugin);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerPlatformListeners() {
|
||||
registerPluginListeners(
|
||||
new BukkitPlayerDamageListener(),
|
||||
new BukkitPlayerKnockbackListener(),
|
||||
new me.caseload.knockbacksync.listener.bukkit.KnockbackResistanceNullifier()
|
||||
);
|
||||
// Reconcile away any leftover owned knockback-resistance marker for players already
|
||||
// online (e.g. across a /reload), so none is stranded.
|
||||
me.caseload.knockbacksync.listener.bukkit.KnockbackResistanceNullifier.cleanupAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerCommands() {
|
||||
super.commandManager = new LegacyPaperCommandManager<>(
|
||||
this.plugin,
|
||||
ExecutionCoordinator.simpleCoordinator(),
|
||||
bukkitSenderFactory
|
||||
);
|
||||
if (commandManager instanceof LegacyPaperCommandManager) {
|
||||
LegacyPaperCommandManager<Sender> legacyPaperCommandManager = (LegacyPaperCommandManager<Sender>) commandManager;
|
||||
if (legacyPaperCommandManager.hasCapability(CloudBukkitCapabilities.NATIVE_BRIGADIER)) {
|
||||
legacyPaperCommandManager.registerBrigadier();
|
||||
} else if (commandManager.hasCapability(CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION)) {
|
||||
legacyPaperCommandManager.registerAsynchronousCompletions();
|
||||
}
|
||||
}
|
||||
super.registerCommands();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getVersion() {
|
||||
return this.plugin.getDescription().getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveDefaultConfig() {
|
||||
this.plugin.saveDefaultConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionChecker getPermissionChecker() {
|
||||
return permissionChecker;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTickRate() {
|
||||
if (tickRateMethodHandle != null) {
|
||||
try {
|
||||
return (float) tickRateMethodHandle.invoke();
|
||||
} catch (Throwable t) {
|
||||
return 20.0f;
|
||||
}
|
||||
}
|
||||
return 20.0f;
|
||||
}
|
||||
|
||||
public URL getJarURL() {
|
||||
try {
|
||||
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
|
||||
File pluginJarFile = new File(path);
|
||||
|
||||
return Paths.get(getDataFolder().getParentFile().getAbsolutePath(), pluginJarFile.getName()).toUri().toURL();
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Couldn't find plugin file: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void registerPluginListeners(Listener... listeners) {
|
||||
PluginManager pluginManager = this.plugin.getServer().getPluginManager();
|
||||
for (Listener listener : listeners)
|
||||
pluginManager.registerEvents(listener, this.plugin);
|
||||
}
|
||||
|
||||
public BukkitSenderFactory getSenderFactory() {
|
||||
return this.bukkitSenderFactory;
|
||||
}
|
||||
|
||||
public void setUpdateIntervals() {
|
||||
try {
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
Method getWorldHandleMethod = world.getClass().getMethod("getHandle");
|
||||
Object serverLevel = getWorldHandleMethod.invoke(world);
|
||||
|
||||
// Get ChunkMap
|
||||
Method getChunkSource = serverLevel.getClass().getMethod("getChunkSource");
|
||||
Object chunkSource = getChunkSource.invoke(serverLevel);
|
||||
Field chunkMapField = chunkSource.getClass().getDeclaredField("chunkMap");
|
||||
chunkMapField.setAccessible(true);
|
||||
Object chunkMap = chunkMapField.get(chunkSource);
|
||||
|
||||
// Get entityMap from ChunkMap
|
||||
Field entityMapField = chunkMap.getClass().getDeclaredField("entityMap");
|
||||
entityMapField.setAccessible(true);
|
||||
Map<Integer, ?> entityMap = (Map<Integer, ?>) entityMapField.get(chunkMap);
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
Object trackedEntity = entityMap.get(player.getEntityId());
|
||||
if (trackedEntity == null)
|
||||
continue;
|
||||
|
||||
Field serverEntityField = trackedEntity.getClass().getDeclaredField("serverEntity");
|
||||
serverEntityField.setAccessible(true);
|
||||
Object serverEntity = serverEntityField.get(trackedEntity);
|
||||
|
||||
Field updateIntervalField = serverEntity.getClass().getDeclaredField("updateInterval");
|
||||
updateIntervalField.setAccessible(true);
|
||||
updateIntervalField.set(serverEntity, playerUpdateInterval);
|
||||
}
|
||||
}
|
||||
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | NoSuchFieldException e) {
|
||||
throw new IllegalStateException("Unable to use reflection to modify updateIntervals" + e);
|
||||
}
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onConfigReload(ConfigReloadEvent event) {
|
||||
playerUpdateInterval = event.getConfigManager().getConfigWrapper().getInt("entity_tick_intervals.player", 2);
|
||||
}
|
||||
|
||||
public void restartServer() {
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "restart");
|
||||
}
|
||||
|
||||
public boolean hasRestartScript() {
|
||||
File spigotFile = new File("spigot.yml");
|
||||
if (!spigotFile.exists())
|
||||
return false;
|
||||
|
||||
FileConfiguration spigotConfig = YamlConfiguration.loadConfiguration(spigotFile);
|
||||
String scriptValue = spigotConfig.getString("settings.restart-script");
|
||||
if (scriptValue == null || scriptValue.isEmpty())
|
||||
return false;
|
||||
|
||||
return Paths.get(scriptValue).toAbsolutePath().normalize().toFile().exists();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import me.caseload.knockbacksync.common.BuildConfig;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public final class BukkitLoaderPlugin extends JavaPlugin {
|
||||
|
||||
private final Base core = new BukkitBase(this);
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
core.load();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
core.enable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
// Reconcile away any leftover owned knockback-resistance marker so no player is left
|
||||
// with reduced resistance after the plugin unloads.
|
||||
me.caseload.knockbacksync.listener.bukkit.KnockbackResistanceNullifier.cleanupAll();
|
||||
// Drop listener handles before any lifecycle decision; the shared API may outlive this plugin.
|
||||
core.unregisterPacketListeners();
|
||||
// Terminate only when this plugin owns the PacketEvents lifecycle (shaded build).
|
||||
if (BuildConfig.SHADE_PE) {
|
||||
PacketEvents.getAPI().terminate();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import dev.jorel.commandapi.CommandAPIBukkitConfig;
|
||||
import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
|
||||
import me.caseload.knockbacksync.command.bukkit.MainCommand;
|
||||
import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerDamageListener;
|
||||
import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerJoinQuitListener;
|
||||
import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerKnockbackListener;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.permission.PluginPermissionChecker;
|
||||
import me.caseload.knockbacksync.scheduler.BukkitSchedulerAdapter;
|
||||
import me.caseload.knockbacksync.scheduler.FoliaSchedulerAdapter;
|
||||
import me.caseload.knockbacksync.stats.custom.BukkitStatsManager;
|
||||
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
|
||||
import me.caseload.knockbacksync.world.BukkitServer;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public final class KnockbackSyncPlugin extends JavaPlugin {
|
||||
|
||||
private final KnockbackSyncBase core = new KnockbackSyncBase() {
|
||||
|
||||
private final PluginPermissionChecker permissionChecker = new PluginPermissionChecker();
|
||||
|
||||
{
|
||||
statsManager = new BukkitStatsManager();
|
||||
platformServer = new BukkitServer();
|
||||
pluginJarHashProvider = new PluginJarHashProvider(this.getClass().getProtectionDomain().getCodeSource().getLocation());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Logger getLogger() {
|
||||
return KnockbackSyncPlugin.this.getLogger();
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getDataFolder() {
|
||||
return KnockbackSyncPlugin.this.getDataFolder();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getResource(String filename) {
|
||||
return KnockbackSyncPlugin.this.getResource(filename);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
PacketEvents.setAPI(SpigotPacketEventsBuilder.build(KnockbackSyncPlugin.this));
|
||||
PacketEvents.getAPI().load();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enable() {
|
||||
super.enable();
|
||||
initializeScheduler();
|
||||
configManager.loadConfig(false);
|
||||
statsManager.init();
|
||||
checkForUpdates();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeScheduler() {
|
||||
switch (platform) {
|
||||
case BUKKIT:
|
||||
super.scheduler = new BukkitSchedulerAdapter(KnockbackSyncPlugin.this);
|
||||
break;
|
||||
case FOLIA:
|
||||
super.scheduler = new FoliaSchedulerAdapter(KnockbackSyncPlugin.this);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerPlatformListeners() {
|
||||
registerPluginListeners(
|
||||
new BukkitPlayerDamageListener(),
|
||||
new BukkitPlayerKnockbackListener(),
|
||||
new BukkitPlayerJoinQuitListener()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerCommands() {
|
||||
new MainCommand().register();
|
||||
// CommandDispatcher dispatcher = Brigadier.getCommandDispatcher();
|
||||
// dispatcher.register(KnockbackSyncCommand.build());
|
||||
// dispatcher.register(
|
||||
// Commands.literal("kbsync")
|
||||
// .redirect(dispatcher.getRoot().getChild("knockbacksync"))
|
||||
// );
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getVersion() {
|
||||
return getDescription().getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveDefaultConfig() {
|
||||
KnockbackSyncPlugin.this.saveDefaultConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionChecker getPermissionChecker() {
|
||||
return permissionChecker;
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
CommandAPI.onLoad(new CommandAPIBukkitConfig(this));
|
||||
core.load();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
CommandAPI.onEnable();
|
||||
core.enable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
CommandAPI.onDisable();
|
||||
PacketEvents.getAPI().terminate();
|
||||
}
|
||||
|
||||
private void registerPluginListeners(Listener... listeners) {
|
||||
PluginManager pluginManager = getServer().getPluginManager();
|
||||
for (Listener listener : listeners)
|
||||
pluginManager.registerEvents(listener, this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package me.caseload.knockbacksync.api;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
/**
|
||||
* Stable, reflection-friendly entry point for other plugins (notably OldCombatMechanics'
|
||||
* old-fishing-knockback module) to hand KnockbackSync a pre-computed knockback vector, so that
|
||||
* KnockbackSync owns the final velocity and applies the same latency Y-correction it gives melee
|
||||
* knockback.
|
||||
*
|
||||
* <p>Why this exists: a fishing-rod hit reaches KnockbackSync as an ordinary player-vs-player
|
||||
* damage event. KnockbackSync cannot tell it apart from a sword hit, so it computes a melee vector
|
||||
* and the caller's own {@code setVelocity} either fights it or is re-corrected with melee-tuned
|
||||
* latency logic — the rod pop ends up flattened/inconsistent under latency. Routing the
|
||||
* bobber-direction vector through here makes the rod feel like 1.8, latency-synced like melee.</p>
|
||||
*
|
||||
* <p>Resolved by callers via reflection; keep the class name, package, and method signature
|
||||
* stable.</p>
|
||||
*/
|
||||
public final class KnockbackSyncRodApi {
|
||||
|
||||
private KnockbackSyncRodApi() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a fishing-rod knockback vector for {@code victim}, to be applied and latency-synced
|
||||
* by the {@code PlayerVelocityEvent} produced by the caller's subsequent damage tick.
|
||||
*
|
||||
* <p>MUST be called on the main thread, immediately before the caller deals the rod's damage.</p>
|
||||
*
|
||||
* @param victim the player being knocked back
|
||||
* @param rodKnockback the 1.8 bobber-direction knockback vector
|
||||
* @return {@code true} if KnockbackSync will own this knockback (caller must NOT also call
|
||||
* {@code setVelocity}); {@code false} if KnockbackSync is disabled or not tracking this
|
||||
* player, in which case the caller should apply the knockback itself.
|
||||
*/
|
||||
public static boolean applyRodKnockback(Player victim, Vector rodKnockback) {
|
||||
if (victim == null || rodKnockback == null) return false;
|
||||
|
||||
final Base base = Base.INSTANCE;
|
||||
if (base == null) return false;
|
||||
|
||||
final ConfigManager config = base.getConfigManager();
|
||||
if (config == null || !config.isToggled() || !config.isLegacyKnockbackEnabled())
|
||||
return false;
|
||||
|
||||
final User user = new BukkitPlayer(victim).getUser();
|
||||
if (user == null) return false;
|
||||
|
||||
final PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData == null) return false; // not tracked (exempt/Geyser/etc.) — caller falls back
|
||||
|
||||
final Vector3d kb = new Vector3d(rodKnockback.getX(), rodKnockback.getY(), rodKnockback.getZ());
|
||||
playerData.setRodKnockback(kb);
|
||||
// On-ground sync should target the rod's vertical, mirroring the melee damage path.
|
||||
playerData.setVerticalVelocity(kb.getY());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package me.caseload.knockbacksync.command.bukkit;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import me.caseload.knockbacksync.command.bukkit.subcommand.PingSubcommand;
|
||||
import me.caseload.knockbacksync.command.bukkit.subcommand.ReloadSubcommand;
|
||||
import me.caseload.knockbacksync.command.bukkit.subcommand.StatusSubcommand;
|
||||
import me.caseload.knockbacksync.command.bukkit.subcommand.ToggleSubcommand;
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
public class MainCommand {
|
||||
|
||||
public void register() {
|
||||
new CommandAPICommand("knockbacksync")
|
||||
.withAliases("kbsync")
|
||||
.withSubcommand(new PingSubcommand().getCommand())
|
||||
.withSubcommand(new ToggleSubcommand().getCommand())
|
||||
.withSubcommand(new ReloadSubcommand().getCommand())
|
||||
.withSubcommand(new StatusSubcommand().getCommand())
|
||||
.executes((sender, args) -> {
|
||||
sender.sendMessage(ChatColor.translateAlternateColorCodes(
|
||||
'&',
|
||||
"&6This server is running the &eKnockbackSync &6plugin. &bhttps://github.com/CASELOAD7000/knockback-sync"
|
||||
));
|
||||
})
|
||||
.register();
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package me.caseload.knockbacksync.command.bukkit.subcommand;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import me.caseload.knockbacksync.command.PlatformSender;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class PingSubcommand {
|
||||
|
||||
public CommandAPICommand getCommand() {
|
||||
return new CommandAPICommand("ping")
|
||||
.withPermission("knockbacksync.ping")
|
||||
.withOptionalArguments(new PlayerArgument("target"))
|
||||
.executes((sender, args) -> {
|
||||
Player target = (Player) args.get("target");
|
||||
if (target == null) {
|
||||
if (sender instanceof ConsoleCommandSender) {
|
||||
sender.sendMessage(ChatColor.RED + "You must specify a player to use this command from the console.");
|
||||
} else if (sender instanceof Player) {
|
||||
sender.sendMessage(ChatUtil.getPingMessage(((Player) sender).getUniqueId(), null));
|
||||
}
|
||||
} else {
|
||||
if (sender instanceof ConsoleCommandSender) {
|
||||
sender.sendMessage(ChatUtil.getPingMessage(PlatformSender.CONSOLE_UUID, target.getUniqueId()));
|
||||
} else if (sender instanceof Player) {
|
||||
sender.sendMessage(ChatUtil.getPingMessage(((Player) sender).getUniqueId(), target.getUniqueId()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package me.caseload.knockbacksync.command.bukkit.subcommand;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public class ReloadSubcommand implements Listener {
|
||||
|
||||
public CommandAPICommand getCommand() {
|
||||
return new CommandAPICommand("reload")
|
||||
.withPermission("knockbacksync.reload")
|
||||
.executes((sender, args) -> {
|
||||
ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager();
|
||||
configManager.loadConfig(true);
|
||||
|
||||
String reloadMessage = ChatColor.translateAlternateColorCodes('&',
|
||||
configManager.getReloadMessage()
|
||||
);
|
||||
|
||||
sender.sendMessage(reloadMessage);
|
||||
});
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
package me.caseload.knockbacksync.command.bukkit.subcommand;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class StatusSubcommand implements Listener {
|
||||
|
||||
public CommandAPICommand getCommand() {
|
||||
return new CommandAPICommand("status")
|
||||
.withPermission(CommandPermission.NONE)
|
||||
.withOptionalArguments(new PlayerArgument("target"))
|
||||
.executes((sender, args) -> {
|
||||
ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager();
|
||||
Player target = (Player) args.get("target");
|
||||
|
||||
// Show global status
|
||||
boolean globalStatus = configManager.isToggled();
|
||||
sender.sendMessage(ChatColor.YELLOW + "Global KnockbackSync status: " +
|
||||
(globalStatus ? ChatColor.GREEN + "Enabled" : ChatColor.RED + "Disabled"));
|
||||
|
||||
// Show player status
|
||||
if (target == null && sender instanceof Player)
|
||||
target = (Player) sender;
|
||||
|
||||
if (target == null)
|
||||
return;
|
||||
|
||||
if (sender.hasPermission("knockbacksync.status.self") ||
|
||||
(sender.hasPermission("knockbacksync.status.other") && !sender.equals(target))) {
|
||||
|
||||
UUID uuid = target.getUniqueId();
|
||||
boolean playerStatus = PlayerDataManager.containsPlayerData(uuid);
|
||||
|
||||
if (!globalStatus) {
|
||||
sender.sendMessage(ChatColor.YELLOW + target.getName() + "'s KnockbackSync status: " +
|
||||
ChatColor.RED + "Disabled (Global toggle is off)");
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.YELLOW + target.getName() + "'s KnockbackSync status: " +
|
||||
(playerStatus ? ChatColor.GREEN + "Enabled" : ChatColor.RED + "Disabled"));
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.RED + "You don't have the "
|
||||
+ (sender.equals(target) ? "knockbacksync.status.self" : "knockbacksync.status.other") +
|
||||
" permission needed to check status for " +
|
||||
(sender.equals(target) ? "yourself" : "other players") + ".");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
package me.caseload.knockbacksync.command.bukkit.subcommand;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class ToggleSubcommand implements Listener {
|
||||
|
||||
public CommandAPICommand getCommand() {
|
||||
return new CommandAPICommand("toggle")
|
||||
.withPermission(CommandPermission.NONE)
|
||||
.withOptionalArguments(new PlayerArgument("target"))
|
||||
.executes((sender, args) -> {
|
||||
ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager();
|
||||
Player target = (Player) args.get("target");
|
||||
String message;
|
||||
|
||||
if (target == null) {
|
||||
// Global toggle
|
||||
if (sender.hasPermission("knockbacksync.toggle.global")) {
|
||||
boolean toggledState = !configManager.isToggled();
|
||||
configManager.setToggled(toggledState);
|
||||
|
||||
KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().set("enabled", toggledState);
|
||||
KnockbackSyncBase.INSTANCE.getConfigManager().saveConfig();
|
||||
|
||||
message = ChatColor.translateAlternateColorCodes('&',
|
||||
toggledState ? configManager.getEnableMessage() : configManager.getDisableMessage()
|
||||
);
|
||||
} else {
|
||||
message = ChatColor.RED + "You don't have permission to toggle the global setting.";
|
||||
}
|
||||
sender.sendMessage(message);
|
||||
} else {
|
||||
// Player-specific toggle
|
||||
if (!configManager.isToggled()) {
|
||||
message = ChatColor.RED + "Knockbacksync is currently disabled on this server. Contact your server administrator for more information.";
|
||||
sender.sendMessage(message);
|
||||
} else if (sender instanceof Player && sender.equals(target) && sender.hasPermission("knockbacksync.toggle.self")) {
|
||||
togglePlayerKnockback(target, configManager, sender);
|
||||
} else if (sender.hasPermission("knockbacksync.toggle.other")) {
|
||||
togglePlayerKnockback(target, configManager, sender);
|
||||
} else {
|
||||
message = ChatColor.RED + "You don't have permission to toggle knockback for " +
|
||||
(sender.equals(target) ? "yourself" : "other players") + ".";
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void togglePlayerKnockback(Player target, ConfigManager configManager, CommandSender sender) {
|
||||
UUID uuid = target.getUniqueId();
|
||||
|
||||
if (PlayerDataManager.shouldExempt(uuid)) {
|
||||
String message = ChatColor.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerIneligibleMessage()
|
||||
).replace("%player%", target.getName());
|
||||
|
||||
sender.sendMessage(message);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean hasPlayerData = PlayerDataManager.containsPlayerData(uuid);
|
||||
if (hasPlayerData)
|
||||
PlayerDataManager.removePlayerData(uuid);
|
||||
else
|
||||
PlayerDataManager.addPlayerData(uuid, new PlayerData(new BukkitPlayer(target)));
|
||||
|
||||
String message = ChatColor.translateAlternateColorCodes('&',
|
||||
hasPlayerData ? configManager.getPlayerDisableMessage() : configManager.getPlayerEnableMessage()
|
||||
).replace("%player%", target.getName());
|
||||
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
}
|
||||
+49
-5
@@ -1,23 +1,67 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.listener.PlayerDamageListener;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.util.MultiLibUtil;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
|
||||
public class BukkitPlayerDamageListener extends PlayerDamageListener implements Listener {
|
||||
|
||||
/**
|
||||
* D3 — projectile PvP knockback-resistance nullification.
|
||||
*
|
||||
* <p>For a hit that {@link PvpSource} classifies as {@code PROJECTILE} PvP, zero the
|
||||
* victim's effective knockback resistance BEFORE vanilla computes the knockback, so a
|
||||
* netherite victim takes full (diamond-level) projectile knockback. Runs at {@code LOW}
|
||||
* so it precedes OCM's {@code projectile-knockback} damage raise ({@code NORMAL}) and
|
||||
* vanilla knockback. The decision is gated on classification + config only — never on the
|
||||
* current event damage, because OCM may not have raised snowball/egg/ender-pearl damage
|
||||
* yet at this priority.</p>
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onProjectilePvpDamage(EntityDamageByEntityEvent event) {
|
||||
final ConfigManager config = Base.INSTANCE.getConfigManager();
|
||||
// Single source of truth: active only when toggled on, legacy knockback enabled,
|
||||
// and knockback resistance is NOT being kept (matching OCM's default).
|
||||
if (!config.isToggled() || !config.isLegacyKnockbackEnabled() || config.isLegacyKnockbackResistanceEnabled())
|
||||
return;
|
||||
|
||||
if (PvpSource.classify(event) != PvpSource.Type.PROJECTILE)
|
||||
return;
|
||||
|
||||
final Player victim = (Player) event.getEntity();
|
||||
if (MultiLibUtil.isExternalPlayer(victim))
|
||||
return;
|
||||
|
||||
KnockbackResistanceNullifier.nullify(victim);
|
||||
}
|
||||
|
||||
/**
|
||||
* Melee PvP: KnockbackSync owns the 1.8 melee velocity via {@code LegacyKnockback}
|
||||
* (applied at {@code PlayerVelocityEvent}), so melee already delivers full knockback
|
||||
* without touching the resistance attribute. The previous {@code stripKnockbackResistance()}
|
||||
* (which removed the victim's {@code KNOCKBACK_RESISTANCE} modifiers and never restored them,
|
||||
* leaking into PvE) has been deleted. Projectile/explosion/fishing hits are NOT routed
|
||||
* through this melee path (their damager is not a player), so no stale legacy-knockback
|
||||
* vector can be stored for them.
|
||||
*/
|
||||
@EventHandler(ignoreCancelled = true)
|
||||
public void onPlayerDamage(EntityDamageByEntityEvent event) {
|
||||
Entity victim = event.getEntity();
|
||||
Entity attacker = event.getDamager();
|
||||
if ((victim instanceof Player) && (attacker instanceof Player))
|
||||
if (!MultiLibUtil.isExternalPlayer((Player) victim)) {
|
||||
onPlayerDamage(new BukkitPlayer((Player) victim), new BukkitPlayer((Player) attacker));
|
||||
}
|
||||
if (!(victim instanceof Player) || !(attacker instanceof Player))
|
||||
return;
|
||||
|
||||
if (MultiLibUtil.isExternalPlayer((Player) victim))
|
||||
return;
|
||||
|
||||
onPlayerDamage(new BukkitPlayer((Player) victim), new BukkitPlayer((Player) attacker));
|
||||
}
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import me.caseload.knockbacksync.listener.PlayerJoinQuitListener;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
public class BukkitPlayerJoinQuitListener extends PlayerJoinQuitListener implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
onPlayerJoin(new PlayerData(new BukkitPlayer(event.getPlayer())));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
onPlayerQuit(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
+12
-5
@@ -16,7 +16,11 @@ import org.bukkit.util.Vector;
|
||||
|
||||
public class BukkitPlayerKnockbackListener extends PlayerKnockbackListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
// HIGHEST so KnockbackSync is the last writer in the event chain: it owns the final
|
||||
// melee velocity. We read and write the EVENT velocity (not player.getVelocity()/
|
||||
// player.setVelocity()) so we integrate with the chain instead of fighting it. See
|
||||
// knockback-sync issue #7 (kernitus, Krymonota, Axionize).
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlayerVelocity(PlayerVelocityEvent event) {
|
||||
Player victim = event.getPlayer();
|
||||
EntityDamageEvent entityDamageEvent = victim.getLastDamageCause();
|
||||
@@ -34,8 +38,11 @@ public class BukkitPlayerKnockbackListener extends PlayerKnockbackListener imple
|
||||
if (MultiLibUtil.isExternalPlayer(victim))
|
||||
return;
|
||||
|
||||
Vector vector = event.getVelocity();
|
||||
onPlayerVelocity(new BukkitPlayer(victim), new Vector3d(vector.getX(), vector.getY(), vector.getZ()));
|
||||
// callback.setVelocity(victim.getVelocity()); // Update the callback's velocity in Spigot
|
||||
Vector eventVelocity = event.getVelocity();
|
||||
Vector3d result = onPlayerVelocity(new BukkitPlayer(victim),
|
||||
new Vector3d(eventVelocity.getX(), eventVelocity.getY(), eventVelocity.getZ()));
|
||||
|
||||
if (result != null)
|
||||
event.setVelocity(new Vector(result.getX(), result.getY(), result.getZ()));
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeInstance;
|
||||
import org.bukkit.attribute.AttributeModifier;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* D3 — Resistance Nullification (M1).
|
||||
*
|
||||
* <p>For player-vs-player projectile hits (classified by {@link PvpSource}), forces the
|
||||
* victim's effective {@code generic.knockback_resistance} to 0 for the duration of the
|
||||
* hit by adding a single plugin-owned {@code MULTIPLY_SCALAR_1} {@code -1.0} modifier,
|
||||
* lets vanilla compute full knockback, then removes the owned marker on the next tick.
|
||||
* Equipment and other plugins' modifiers are never read, captured, or removed — only the
|
||||
* owned marker (identified by a constant UUID) is added/removed.</p>
|
||||
*
|
||||
* <p>Melee PvP is owned by {@code LegacyKnockback} (which already ignores resistance when
|
||||
* {@code enable_knockback_resistance=false}) and needs no attribute work; fishing PvP is
|
||||
* owned by OCM's {@code old-fishing-knockback}. Explosions are out of scope on 1.19.4.</p>
|
||||
*
|
||||
* <p>The marker is permanent NMS state until removed, so a leftover marker is reconciled
|
||||
* away on join/quit and on plugin enable/disable (see {@link #cleanupAll()}), guaranteeing
|
||||
* a player is never left permanently with reduced resistance.</p>
|
||||
*/
|
||||
public final class KnockbackResistanceNullifier implements Listener {
|
||||
|
||||
// Constant, plugin-owned modifier identity. Add skips if this UUID is already present;
|
||||
// removal matches by this UUID. Equipment/foreign modifiers are never touched.
|
||||
private static final UUID MODIFIER_UUID = UUID.fromString("7b2a1c84-4d3e-4f0a-9c6b-1e5a9d8c7f30");
|
||||
private static final String MODIFIER_NAME = "knockbacksync_pvp_kb_nullify";
|
||||
|
||||
// Mirrors the previous stripKnockbackResistance guard: if the attribute is unavailable
|
||||
// on this server version, disable for the session and warn once (no per-hit log spam).
|
||||
private static volatile boolean unsupported = false;
|
||||
|
||||
/**
|
||||
* Force the victim's effective knockback resistance to 0 for the current hit by adding the
|
||||
* owned marker, then schedule its removal on the next tick. Idempotent and re-entrancy safe:
|
||||
* if the marker is already present (e.g. a second hit in the same tick) the add is skipped.
|
||||
*
|
||||
* <p>Must be called before vanilla computes the hit's knockback (i.e. during the damage
|
||||
* event at an early priority).</p>
|
||||
*/
|
||||
public static void nullify(Player victim) {
|
||||
final AttributeInstance attribute = resolve(victim);
|
||||
if (attribute == null) return;
|
||||
if (hasOwnedModifier(attribute)) return;
|
||||
|
||||
try {
|
||||
attribute.addModifier(new AttributeModifier(
|
||||
MODIFIER_UUID, MODIFIER_NAME, -1.0, AttributeModifier.Operation.MULTIPLY_SCALAR_1));
|
||||
} catch (IllegalArgumentException alreadyApplied) {
|
||||
return; // raced — modifier already present; nothing to add
|
||||
}
|
||||
|
||||
// Remove on the NEXT tick. Same-event (MONITOR/finally) removal is forbidden: vanilla
|
||||
// computes the knockback after the event returns, so an in-event removal would restore
|
||||
// the attribute before vanilla reads it. On the non-Folia target this is a main-thread
|
||||
// next-tick task; it stays compile-safe (no Player#getScheduler()).
|
||||
Base.INSTANCE.getScheduler().runTaskLater(() -> remove(victim), 1L);
|
||||
}
|
||||
|
||||
/** Remove the owned marker if present. Idempotent; never touches foreign/equipment modifiers. */
|
||||
public static void remove(Player victim) {
|
||||
final AttributeInstance attribute = resolve(victim);
|
||||
if (attribute == null) return;
|
||||
for (AttributeModifier modifier : attribute.getModifiers()) {
|
||||
if (MODIFIER_UUID.equals(modifier.getUniqueId())) {
|
||||
attribute.removeModifier(modifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip the owned marker from every online player (plugin enable/disable reconciliation). */
|
||||
public static void cleanupAll() {
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
remove(player);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasOwnedModifier(AttributeInstance attribute) {
|
||||
for (AttributeModifier modifier : attribute.getModifiers()) {
|
||||
if (MODIFIER_UUID.equals(modifier.getUniqueId())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static AttributeInstance resolve(Player victim) {
|
||||
if (unsupported || victim == null) return null;
|
||||
try {
|
||||
return victim.getAttribute(Attribute.GENERIC_KNOCKBACK_RESISTANCE);
|
||||
} catch (Throwable t) {
|
||||
unsupported = true;
|
||||
Base.INSTANCE.getLogger().warning(
|
||||
"Could not access KNOCKBACK_RESISTANCE attribute; PvP knockback-resistance "
|
||||
+ "nullification disabled for this session: " + t.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── R7 fail-safe: reconcile away any leftover owned marker ──────────────────────────────
|
||||
|
||||
@EventHandler
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
remove(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
remove(event.getPlayer());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.entity.Projectile;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.projectiles.ProjectileSource;
|
||||
|
||||
/**
|
||||
* D1 — PvP Source Attribution.
|
||||
*
|
||||
* <p>Classifies a damage event on a player victim into a source class so the
|
||||
* knockback-resistance nullifier (D3) knows whether and how to act. Attribution is
|
||||
* self-inclusive: the victim's own projectile (e.g. their own arrow) still counts as
|
||||
* PvP. This classifier only answers "is this player-attributed, and by what source
|
||||
* class?" — it does not modify damage or knockback.</p>
|
||||
*
|
||||
* <p>Scope note (Purpur 1.19.4 target): netherite {@code generic.knockback_resistance}
|
||||
* only reduces knockback applied through {@code LivingEntity.knockback(...)} (melee and
|
||||
* projectile). Explosion knockback is not reduced by it on 1.19.4 (Blast Protection
|
||||
* governs that), and wind charges do not exist, so explosion/wind-charge sources are
|
||||
* classified {@link Type#NONE}.</p>
|
||||
*/
|
||||
public final class PvpSource {
|
||||
|
||||
public enum Type {
|
||||
/** Direct player melee. Owned by {@code LegacyKnockback}; no attribute nullification. */
|
||||
MELEE,
|
||||
/** Player-shot projectile (arrow, spectral arrow, trident, snowball, egg, ender pearl, ...). Nullified by D3. */
|
||||
PROJECTILE,
|
||||
/** Fishing-rod hit (OCM {@code old-fishing-knockback}); owned by the rod sync. No nullification. */
|
||||
FISHING,
|
||||
/** Not attributable to a player (mob, environment, explosion, ...). */
|
||||
NONE
|
||||
}
|
||||
|
||||
private PvpSource() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param event a damage-by-entity event (the caller has not necessarily checked the victim type)
|
||||
* @return the PvP source class; {@link Type#NONE} when the damage is not attributable to a player
|
||||
*/
|
||||
public static Type classify(EntityDamageByEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player)) return Type.NONE;
|
||||
final Player victim = (Player) event.getEntity();
|
||||
final Entity damager = event.getDamager();
|
||||
|
||||
// Direct player damager: either a melee hit, or an OCM fishing-rod hit.
|
||||
// old-fishing-knockback deals its damage via damage(victim, rodder), so the
|
||||
// damager is the rodding player (not the bobber). Distinguish the rod hit via
|
||||
// the rod-pending marker KnockbackSync stores for the rod path. Both MELEE and
|
||||
// FISHING are owned elsewhere and get no attribute nullification, so a mislabel
|
||||
// between the two cannot change knockback behaviour.
|
||||
if (damager instanceof Player) {
|
||||
return isRodPending(victim) ? Type.FISHING : Type.MELEE;
|
||||
}
|
||||
|
||||
// Player-shot projectile, resolved generically via ProjectileSource so any
|
||||
// player-shot projectile type is covered without a per-type list (including
|
||||
// types absent from the compile-time API). Self-inclusive: the shooter may be
|
||||
// the victim. A non-player projectile source (e.g. a dispenser's
|
||||
// BlockProjectileSource) or a null shooter is not PvP. Note: the ender pearl's
|
||||
// post-teleport fall damage is a separate non-by-entity event, so it never
|
||||
// reaches this projectile branch.
|
||||
if (damager instanceof Projectile) {
|
||||
final ProjectileSource shooter = ((Projectile) damager).getShooter();
|
||||
return (shooter instanceof Player) ? Type.PROJECTILE : Type.NONE;
|
||||
}
|
||||
|
||||
// Explosions (TNT, end crystal, fireball), mobs, environment: out of scope on 1.19.4.
|
||||
return Type.NONE;
|
||||
}
|
||||
|
||||
private static boolean isRodPending(Player victim) {
|
||||
final User user = new BukkitPlayer(victim).getUser();
|
||||
if (user == null) return false;
|
||||
final PlayerData data = PlayerDataManager.getPlayerData(user);
|
||||
return data != null && data.isRodKnockbackPending();
|
||||
}
|
||||
}
|
||||
+10
-5
@@ -1,8 +1,10 @@
|
||||
package me.caseload.knockbacksync.permission;
|
||||
|
||||
import me.caseload.knockbacksync.command.PlatformSender;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class PluginPermissionChecker implements PermissionChecker {
|
||||
|
||||
@@ -18,13 +20,16 @@ public class PluginPermissionChecker implements PermissionChecker {
|
||||
|
||||
// Currently shouldn't be called
|
||||
@Override
|
||||
public boolean hasPermission(Object CommandSourceStack, String s, boolean defaultIfUnset) {
|
||||
return false;
|
||||
public boolean hasPermission(Object nativeType, String s, boolean defaultIfUnset) {
|
||||
if (nativeType instanceof CommandSender) {
|
||||
return ((CommandSender) nativeType).hasPermission(s);
|
||||
}
|
||||
throw new IllegalArgumentException("Attempted to check permission of an object that wasn't a platformplayer or Sender. This should never happen on Bukkit!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(PlatformSender source, String s, boolean defaultIfUnset) {
|
||||
return false;
|
||||
public boolean hasPermission(Sender source, String s, boolean defaultIfUnset) {
|
||||
return source.hasPermission(s, defaultIfUnset);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,22 +1,83 @@
|
||||
package me.caseload.knockbacksync.player;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.BoundingBox;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import com.google.common.base.Preconditions;
|
||||
import me.caseload.knockbacksync.BukkitBase;
|
||||
import me.caseload.knockbacksync.Platform;
|
||||
import me.caseload.knockbacksync.world.FoliaWorld;
|
||||
import me.caseload.knockbacksync.world.PlatformWorld;
|
||||
import me.caseload.knockbacksync.world.SpigotWorld;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.UUID;
|
||||
|
||||
public class BukkitPlayer implements PlatformPlayer {
|
||||
public final Player bukkitPlayer;
|
||||
public final User user;
|
||||
private String clientBrand = "vanilla";
|
||||
|
||||
// Reflection variables
|
||||
private static Class<?> craftPlayerClass;
|
||||
private static Method getHandleMethod;
|
||||
private static Method getAttackStrengthScaleMethod;
|
||||
private static final ServerVersion currentVersion = PacketEvents.getAPI().getServerManager().getVersion();
|
||||
|
||||
// 1.12.2 support
|
||||
static {
|
||||
try {
|
||||
// Check the current server version
|
||||
|
||||
// If the version is greater than 1.14.4, use the Player method directly
|
||||
if (currentVersion.isOlderThan(ServerVersion.V_1_15)) {
|
||||
Object server = Bukkit.getServer().getClass().getDeclaredMethod("getServer").invoke(Bukkit.getServer());
|
||||
String nmsPackage = server.getClass().getPackage().getName();
|
||||
String bukkitPackage = Bukkit.getServer().getClass().getPackage().getName();
|
||||
|
||||
// Step 1: Load the CraftPlayer class
|
||||
craftPlayerClass = Class.forName(bukkitPackage + ".entity.CraftPlayer");
|
||||
// Step 2: Get the getHandle method
|
||||
getHandleMethod = craftPlayerClass.getMethod("getHandle");
|
||||
// Step 3: Get the getAttackStrengthScale method from the EntityPlayer class
|
||||
Class<?> entityPlayerClass = Class.forName(nmsPackage + ".EntityPlayer");
|
||||
String getAttackStrengthScaleMethodName = "";
|
||||
|
||||
// Determine the method name based on the version
|
||||
if (currentVersion.isOlderThan(ServerVersion.V_1_13)) {
|
||||
getAttackStrengthScaleMethodName = "n";
|
||||
} else if (currentVersion.isOlderThan(ServerVersion.V_1_14)) {
|
||||
getAttackStrengthScaleMethodName = "r";
|
||||
} else if (currentVersion.isOlderThan(ServerVersion.V_1_15)) {
|
||||
getAttackStrengthScaleMethodName = "s";
|
||||
}
|
||||
|
||||
// Get the attack strength scale method for EntityPlayer
|
||||
getAttackStrengthScaleMethod = entityPlayerClass.getMethod(getAttackStrengthScaleMethodName, float.class);
|
||||
getAttackStrengthScaleMethod.setAccessible(true);
|
||||
}
|
||||
} catch (ClassNotFoundException | NoSuchMethodException e) {
|
||||
throw new IllegalStateException("Method of Class required to support this version not found via reflection" + e);
|
||||
} catch (InvocationTargetException | IllegalAccessException e) {
|
||||
throw new RuntimeException("Cannot access required methods via reflection to support this version" + e);
|
||||
}
|
||||
}
|
||||
|
||||
public BukkitPlayer(Player player) {
|
||||
Preconditions.checkArgument(player != null);
|
||||
this.bukkitPlayer = player;
|
||||
this.user = PacketEvents.getAPI().getPlayerManager().getUser(bukkitPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -56,12 +117,22 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
|
||||
@Override
|
||||
public boolean isOnGround() {
|
||||
/* Inconsistent with Entity.isOnGround()
|
||||
/ Checks to see if this player is currently standing on a block.
|
||||
/ This information may not be reliable, as it is a state provided by the client, and may therefore not be accurate.
|
||||
/ It can also easily be spoofed. We may want to cast to LivingEntity and call isOnGround() instead
|
||||
*/
|
||||
return bukkitPlayer.isOnGround();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getPing() {
|
||||
return bukkitPlayer.getPing();
|
||||
if (currentVersion.isNewerThanOrEquals(ServerVersion.V_1_16_5)) {
|
||||
return bukkitPlayer.getPing();
|
||||
} else {
|
||||
return PacketEvents.getAPI().getPlayerManager().getPing(bukkitPlayer);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -71,12 +142,12 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
|
||||
@Override
|
||||
public PlatformWorld getWorld() {
|
||||
return new SpigotWorld(bukkitPlayer.getWorld());
|
||||
return BukkitBase.INSTANCE.getPlatform() == Platform.FOLIA ? new FoliaWorld(bukkitPlayer.getWorld()): new SpigotWorld(bukkitPlayer.getWorld());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3d getLocation() {
|
||||
Location location = bukkitPlayer.getLocation();
|
||||
org.bukkit.Location location = bukkitPlayer.getLocation();
|
||||
return new Vector3d(location.getX(), location.getY(), location.getZ());
|
||||
}
|
||||
|
||||
@@ -87,7 +158,19 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
|
||||
@Override
|
||||
public double getAttackCooldown() {
|
||||
return bukkitPlayer.getAttackCooldown();
|
||||
if (currentVersion.isNewerThan(ServerVersion.V_1_14_4)) {
|
||||
return bukkitPlayer.getAttackCooldown();
|
||||
} else {
|
||||
try {
|
||||
// Step 1: Get the CraftPlayer instance
|
||||
// Step 2: Get the handle (NMS EntityPlayer)
|
||||
Object entityPlayer = getHandleMethod.invoke(bukkitPlayer);
|
||||
// Step 3: Invoke the getAttackStrengthScale method
|
||||
return (float) getAttackStrengthScaleMethod.invoke(entityPlayer, 0.5f);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("This plugin will not work. NMS mapping for getAttackCooldown() failed!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -100,6 +183,16 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
return bukkitPlayer.getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.KNOCKBACK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWeaponKnockbackLevel() {
|
||||
// OCM parity: use the main hand item, or the off hand when the main hand is empty.
|
||||
org.bukkit.inventory.ItemStack mainHand = bukkitPlayer.getInventory().getItemInMainHand();
|
||||
org.bukkit.inventory.ItemStack weapon = mainHand.getType() == org.bukkit.Material.AIR
|
||||
? bukkitPlayer.getInventory().getItemInOffHand()
|
||||
: mainHand;
|
||||
return weapon.getEnchantmentLevel(Enchantment.KNOCKBACK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Integer getNoDamageTicks() {
|
||||
return bukkitPlayer.getNoDamageTicks();
|
||||
@@ -109,4 +202,44 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
public void setVelocity(Vector3d adjustedVelocity) {
|
||||
bukkitPlayer.setVelocity(new Vector(adjustedVelocity.x, adjustedVelocity.y, adjustedVelocity.z));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3d getVelocity() {
|
||||
final Vector bukkitVelocity = bukkitPlayer.getVelocity();
|
||||
return new Vector3d(bukkitVelocity.getX(), bukkitVelocity.getY(), bukkitVelocity.getZ());
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getJumpPower() {
|
||||
double jumpVelocity = 0.42;
|
||||
|
||||
PotionEffect jumpEffect = bukkitPlayer.getPotionEffect(PotionEffectType.JUMP);
|
||||
if (jumpEffect != null) {
|
||||
int amplifier = jumpEffect.getAmplifier();
|
||||
jumpVelocity += (amplifier + 1) * 0.1F;
|
||||
}
|
||||
|
||||
return jumpVelocity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BoundingBox getBoundingBox() {
|
||||
org.bukkit.util.BoundingBox boundingBox = bukkitPlayer.getBoundingBox();
|
||||
return new BoundingBox(boundingBox.getMinX(), boundingBox.getMinY(), boundingBox.getMinZ(), boundingBox.getMaxX(), boundingBox.getMaxY(), boundingBox.getMaxZ());
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable User getUser() {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setClientBrand(String brand) {
|
||||
this.clientBrand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getClientBrand() {
|
||||
return this.clientBrand;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import org.bukkit.scheduler.BukkitTask;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class BukkitTaskHandle implements AbstractTaskHandle {
|
||||
private BukkitTask bukkitTask;
|
||||
private final BukkitTask bukkitTask;
|
||||
private boolean cancelled;
|
||||
|
||||
public BukkitTaskHandle(@NotNull BukkitTask bukkitTask) {
|
||||
|
||||
+8
-17
@@ -1,55 +1,46 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
import io.github.retrooper.packetevents.util.folia.FoliaScheduler;
|
||||
import io.github.retrooper.packetevents.util.folia.GlobalRegionScheduler;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class FoliaSchedulerAdapter implements SchedulerAdapter {
|
||||
private final Plugin plugin;
|
||||
private GlobalRegionScheduler scheduler = null;
|
||||
|
||||
public FoliaSchedulerAdapter(Plugin plugin) {
|
||||
this.plugin = plugin;
|
||||
try {
|
||||
// Attempt to find and call the `getGlobalRegionScheduler` method
|
||||
Method getSchedulerMethod = Bukkit.getServer().getClass().getMethod("getGlobalRegionScheduler");
|
||||
scheduler = (GlobalRegionScheduler) getSchedulerMethod.invoke(Bukkit.getServer());
|
||||
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
|
||||
plugin.getLogger().severe("Failed to access GlobalRegionScheduler: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTask(Runnable task) {
|
||||
return new FoliaTaskHandle(scheduler.run(plugin, scheduledTask -> task.run()));
|
||||
return new FoliaTaskHandle(FoliaScheduler.getGlobalRegionScheduler().run(plugin, scheduledTask -> task.run()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskAsynchronously(Runnable task) {
|
||||
return new FoliaTaskHandle(scheduler.run(plugin, scheduledTask -> task.run()));
|
||||
return new FoliaTaskHandle(FoliaScheduler.getAsyncScheduler().runNow(plugin, scheduledTask -> task.run()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskLater(Runnable task, long delayTicks) {
|
||||
return new FoliaTaskHandle(scheduler.runDelayed(plugin, scheduledTask -> task.run(), delayTicks));
|
||||
return new FoliaTaskHandle(FoliaScheduler.getGlobalRegionScheduler().runDelayed(plugin, scheduledTask -> task.run(), delayTicks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskTimer(Runnable task, long delayTicks, long periodTicks) {
|
||||
return new FoliaTaskHandle(scheduler.runAtFixedRate(plugin, scheduledTask -> task.run(), delayTicks, periodTicks));
|
||||
return new FoliaTaskHandle(FoliaScheduler.getGlobalRegionScheduler().runAtFixedRate(plugin, scheduledTask -> task.run(), delayTicks, periodTicks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskLaterAsynchronously(Runnable task, long delay) {
|
||||
return new FoliaTaskHandle(scheduler.runDelayed(plugin, scheduledTask -> task.run(), delay));
|
||||
return new FoliaTaskHandle(FoliaScheduler.getAsyncScheduler().runDelayed(plugin, scheduledTask -> task.run(), delay * 50, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskTimerAsynchronously(Runnable task, long delay, long period) {
|
||||
return new FoliaTaskHandle(scheduler.runAtFixedRate(plugin, scheduledTask -> task.run(), delay, period));
|
||||
return new FoliaTaskHandle(FoliaScheduler.getAsyncScheduler().runAtFixedRate(plugin, scheduledTask -> task.run(), delay, period));
|
||||
}
|
||||
|
||||
// Folia takes care of this
|
||||
|
||||
@@ -1,41 +1,19 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
import io.github.retrooper.packetevents.util.folia.TaskWrapper;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
|
||||
public class FoliaTaskHandle implements AbstractTaskHandle {
|
||||
private static final MethodHandle GET_OWNING_PLUGIN;
|
||||
private static final MethodHandle CANCEL;
|
||||
|
||||
static {
|
||||
try {
|
||||
Class<?> scheduledTaskClass = Class.forName("io.papermc.paper.threadedregions.scheduler.ScheduledTask");
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
GET_OWNING_PLUGIN = lookup.findVirtual(scheduledTaskClass, "getOwningPlugin", MethodType.methodType(Plugin.class));
|
||||
CANCEL = lookup.findVirtual(scheduledTaskClass, "cancel", MethodType.methodType(void.class));
|
||||
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {
|
||||
throw new RuntimeException("Failed to initialize FoliaTaskHandle reflection", e);
|
||||
}
|
||||
}
|
||||
|
||||
private final Object scheduledTask; // Store as Object instead of ScheduledTask
|
||||
private final TaskWrapper scheduledTask; // Store as Object instead of ScheduledTask
|
||||
private boolean cancelled;
|
||||
|
||||
public FoliaTaskHandle(@NotNull Object scheduledTask) {
|
||||
public FoliaTaskHandle(@NotNull TaskWrapper scheduledTask) {
|
||||
this.scheduledTask = scheduledTask;
|
||||
}
|
||||
|
||||
public Plugin getOwner() {
|
||||
try {
|
||||
return (Plugin) GET_OWNING_PLUGIN.invoke(scheduledTask);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Failed to invoke getOwningPlugin", e);
|
||||
}
|
||||
return scheduledTask.getOwner();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -45,11 +23,7 @@ public class FoliaTaskHandle implements AbstractTaskHandle {
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
try {
|
||||
CANCEL.invoke(scheduledTask);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Failed to invoke cancel", e);
|
||||
}
|
||||
scheduledTask.cancel();
|
||||
this.cancelled = true;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
public class BukkitPlayerSelectorAdapter implements PlayerSelector {
|
||||
private final org.incendo.cloud.bukkit.data.SinglePlayerSelector bukkitSelector;
|
||||
|
||||
public BukkitPlayerSelectorAdapter(org.incendo.cloud.bukkit.data.SinglePlayerSelector bukkitSelector) {
|
||||
this.bukkitSelector = bukkitSelector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSingle() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformPlayer getSinglePlayer() {
|
||||
return new BukkitPlayer(bukkitSelector.single());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<PlatformPlayer> getPlayers() {
|
||||
return Collections.singletonList(new BukkitPlayer(bukkitSelector.single()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String inputString() {
|
||||
return bukkitSelector.inputString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.command.generic.AbstractPlayerSelectorParser;
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import org.incendo.cloud.bukkit.parser.selector.SinglePlayerSelectorParser;
|
||||
import org.incendo.cloud.context.CommandContext;
|
||||
import org.incendo.cloud.parser.ParserDescriptor;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class BukkitPlayerSelectorParser<C> extends AbstractPlayerSelectorParser<C> {
|
||||
|
||||
@Override
|
||||
public ParserDescriptor<C, PlayerSelector> descriptor() {
|
||||
return createDescriptor();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ParserDescriptor<C, ?> getPlatformSpecificDescriptor() {
|
||||
return SinglePlayerSelectorParser.singlePlayerSelectorParser();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CompletableFuture<PlayerSelector> adaptToCommonSelector(CommandContext<C> context, Object platformSpecificSelector) {
|
||||
return CompletableFuture.completedFuture(new BukkitPlayerSelectorAdapter((org.incendo.cloud.bukkit.data.SinglePlayerSelector) platformSpecificSelector));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.BukkitBase;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.command.RemoteConsoleCommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.bukkit.permissions.PermissionDefault;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.incendo.cloud.SenderMapper;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class BukkitSenderFactory extends SenderFactory<BukkitBase, CommandSender> implements SenderMapper<CommandSender, Sender> {
|
||||
// private final BukkitAudiences audiences;
|
||||
|
||||
public BukkitSenderFactory(BukkitBase kbSyncBukkitBase) {
|
||||
super(kbSyncBukkitBase);
|
||||
// this.audiences = BukkitAudiences.create(kbSyncBukkitBase.getLoader());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getName(CommandSender sender) {
|
||||
if (sender instanceof Player) {
|
||||
return sender.getName();
|
||||
}
|
||||
return Sender.CONSOLE_NAME;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected UUID getUniqueId(CommandSender sender) {
|
||||
if (sender instanceof Player) {
|
||||
return ((Player) sender).getUniqueId();
|
||||
}
|
||||
return Sender.CONSOLE_UUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void sendMessage(CommandSender sender, String message) {
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
// @Override
|
||||
// protected void sendMessage(CommandSender sender, Component message) {
|
||||
// // we can safely send async for players and the console - otherwise, send it sync
|
||||
// if (sender instanceof Player || sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) {
|
||||
// this.audiences.sender(sender).sendMessage(message);
|
||||
// } else {
|
||||
// getPlugin().getBootstrap().getScheduler().executeSync(() -> this.audiences.sender(sender).sendMessage(message));
|
||||
// }
|
||||
// }
|
||||
|
||||
@Override
|
||||
protected boolean hasPermission(CommandSender sender, String node) {
|
||||
return sender.hasPermission(node);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean hasPermission(CommandSender sender, String node, boolean defaultIfUnset) {
|
||||
return sender.hasPermission(new Permission(node, defaultIfUnset ? PermissionDefault.TRUE : PermissionDefault.FALSE));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void performCommand(CommandSender sender, String command) {
|
||||
//
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isConsole(CommandSender sender) {
|
||||
return sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Sender map(@NonNull CommandSender base) {
|
||||
return this.wrap(base);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull CommandSender reverse(@NonNull Sender mapped) {
|
||||
return this.unwrap(mapped);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
|
||||
}
|
||||
}
|
||||
+4
-10
@@ -1,17 +1,11 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
public class BukkitStatsManager extends StatsManager {
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
KnockbackSyncBase.INSTANCE.getScheduler().runTaskAsynchronously(() -> {
|
||||
BuildTypePie.determineBuildType(); // Function to calculate hash
|
||||
MetricsBukkit metrics = new MetricsBukkit(23568);
|
||||
metrics.addCustomChart(new PlayerVersionsPie());
|
||||
metrics.addCustomChart(new BuildTypePie());
|
||||
super.metrics = metrics;
|
||||
});
|
||||
public BukkitStatsManager(Plugin plugin) {
|
||||
super(new MetricsBukkit(plugin, 23568));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
|
||||
/*
|
||||
* This Metrics class was auto-generated and can be copied into your project if you are
|
||||
* not using a build tool like Gradle or Maven for dependency management.
|
||||
@@ -15,8 +16,8 @@ package me.caseload.knockbacksync.stats.custom;
|
||||
* Violations will result in a ban of your plugin and account from bStats.
|
||||
*/
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.KnockbackSyncPlugin;
|
||||
import me.caseload.knockbacksync.BukkitLoaderPlugin;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.stats.CustomChart;
|
||||
import me.caseload.knockbacksync.stats.JsonObjectBuilder;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -34,12 +35,11 @@ import java.util.logging.Level;
|
||||
public class MetricsBukkit implements Metrics {
|
||||
|
||||
private final Plugin plugin;
|
||||
|
||||
private final MetricsBase metricsBase;
|
||||
|
||||
|
||||
public MetricsBukkit(int serviceId) {
|
||||
this.plugin = KnockbackSyncPlugin.getPlugin(KnockbackSyncPlugin.class);
|
||||
public MetricsBukkit(Plugin plugin, int serviceId) {
|
||||
this.plugin = plugin;
|
||||
// Get the config file
|
||||
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
|
||||
File configFile = new File(bStatsFolder, "config.yml");
|
||||
@@ -91,7 +91,7 @@ public class MetricsBukkit implements Metrics {
|
||||
enabled,
|
||||
this::appendPlatformData,
|
||||
this::appendServiceData,
|
||||
submitDataTask -> KnockbackSyncBase.INSTANCE.getScheduler().runTask(submitDataTask),
|
||||
submitDataTask -> Base.INSTANCE.getScheduler().runTask(submitDataTask),
|
||||
// isFolia
|
||||
// ? null
|
||||
// : submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),
|
||||
|
||||
@@ -3,6 +3,7 @@ package me.caseload.knockbacksync.world;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.UUID;
|
||||
@@ -19,4 +20,9 @@ public class BukkitServer implements PlatformServer {
|
||||
public PlatformPlayer getPlayer(UUID uuid) {
|
||||
return new BukkitPlayer(Bukkit.getPlayer(uuid));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformPlayer getPlayer(Object nativePlatformPlayer) {
|
||||
return new BukkitPlayer((Player) nativePlatformPlayer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package me.caseload.knockbacksync.world;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.BlockState;
|
||||
|
||||
public class FoliaWorld extends SpigotWorld {
|
||||
public FoliaWorld(World world) {
|
||||
super(world);
|
||||
}
|
||||
|
||||
@Override
|
||||
public WrappedBlockState getBlockStateAt(int x, int y, int z) {
|
||||
BlockState block = this.world.getBlockState(x, y, z);
|
||||
return SpigotConversionUtil.fromBukkitBlockData(block.getBlockData());
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,58 @@
|
||||
package me.caseload.knockbacksync.world;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.protocol.world.BlockFace;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import com.github.retrooper.packetevents.util.Vector3i;
|
||||
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
|
||||
import me.caseload.knockbacksync.world.raytrace.FluidHandling;
|
||||
import me.caseload.knockbacksync.world.raytrace.RayTraceResult;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.FluidCollisionMode;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class SpigotWorld implements PlatformWorld {
|
||||
private final World world;
|
||||
protected final World world;
|
||||
|
||||
// Reflection variables
|
||||
private static Class<?> craftWorldClass;
|
||||
private static Class<?> vec3DClass;
|
||||
private static Class<?> movingObjectPositionClass;
|
||||
private static Class<?> enumDirectionClass;
|
||||
private static Method craftWorldGetHandleMethod;
|
||||
private static Method rayTraceMethod;
|
||||
private static Method vec3DAddMethod;
|
||||
|
||||
static {
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_13)) {
|
||||
try {
|
||||
Object server = Bukkit.getServer().getClass().getDeclaredMethod("getServer").invoke(Bukkit.getServer());
|
||||
String nmsPackage = server.getClass().getPackage().getName();
|
||||
String bukkitPackage = Bukkit.getServer().getClass().getPackage().getName();
|
||||
|
||||
// Load necessary classes dynamically for Minecraft 1.12.2
|
||||
craftWorldClass = Class.forName(bukkitPackage + ".CraftWorld");
|
||||
vec3DClass = Class.forName(nmsPackage + ".Vec3D");
|
||||
movingObjectPositionClass = Class.forName(nmsPackage + ".MovingObjectPosition");
|
||||
enumDirectionClass = Class.forName(nmsPackage + ".EnumDirection");
|
||||
|
||||
// CraftWorld
|
||||
|
||||
// Get method
|
||||
craftWorldGetHandleMethod = craftWorldClass.getMethod("getHandle");
|
||||
rayTraceMethod = Class.forName(nmsPackage + ".World").getMethod("rayTrace", vec3DClass, vec3DClass, boolean.class, boolean.class, boolean.class);
|
||||
vec3DAddMethod = vec3DClass.getMethod("add", double.class, double.class, double.class);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public SpigotWorld(World world) {
|
||||
this.world = world;
|
||||
@@ -40,32 +80,90 @@ public class SpigotWorld implements PlatformWorld {
|
||||
@Override
|
||||
public WrappedBlockState getBlockStateAt(int x, int y, int z) {
|
||||
Block block = world.getBlockAt(x, y, z);
|
||||
return WrappedBlockState.getByString(block.getType().name());
|
||||
return SpigotConversionUtil.fromBukkitBlockData(block.getBlockData());
|
||||
}
|
||||
|
||||
@Override
|
||||
public WrappedBlockState getBlockStateAt(Vector3d loc) {
|
||||
return getBlockStateAt((int) Math.floor(loc.x), (int) Math.floor(loc.x), (int) Math.floor(loc.x));
|
||||
return getBlockStateAt((int) Math.floor(loc.x), (int) Math.floor(loc.y), (int) Math.floor(loc.z));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RayTraceResult rayTraceBlocks(Vector3d start, Vector3d direction, double maxDistance, FluidHandling fluidHandling, boolean ignorePassableBlocks) {
|
||||
Vector startVec = new Vector(start.getX(), start.getY(), start.getZ());
|
||||
Vector directionVec = new Vector(direction.getX(), direction.getY(), direction.getZ());
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThan(ServerVersion.V_1_12_2)) {
|
||||
Vector startVec = new Vector(start.getX(), start.getY(), start.getZ());
|
||||
Vector directionVec = new Vector(direction.getX(), direction.getY(), direction.getZ());
|
||||
|
||||
FluidCollisionMode fluidMode = (fluidHandling == FluidHandling.NONE) ? FluidCollisionMode.NEVER :
|
||||
(fluidHandling == FluidHandling.SOURCE_ONLY) ? FluidCollisionMode.SOURCE_ONLY :
|
||||
FluidCollisionMode.ALWAYS;
|
||||
FluidCollisionMode fluidMode = (fluidHandling == FluidHandling.NONE) ? FluidCollisionMode.NEVER :
|
||||
(fluidHandling == FluidHandling.SOURCE_ONLY) ? FluidCollisionMode.SOURCE_ONLY :
|
||||
FluidCollisionMode.ALWAYS;
|
||||
|
||||
org.bukkit.util.RayTraceResult result = world.rayTraceBlocks(startVec.toLocation(world), directionVec, maxDistance, fluidMode, ignorePassableBlocks);
|
||||
org.bukkit.util.RayTraceResult result = world.rayTraceBlocks(startVec.toLocation(world), directionVec, maxDistance, fluidMode, ignorePassableBlocks);
|
||||
|
||||
if (result == null) return null;
|
||||
if (result == null) return null;
|
||||
|
||||
return new RayTraceResult(
|
||||
new Vector3d(result.getHitPosition().getX(), result.getHitPosition().getY(), result.getHitPosition().getZ()),
|
||||
getBlockFaceFrom(result.getHitBlockFace()),
|
||||
new Vector3i(result.getHitBlock().getX(), result.getHitBlock().getY(), result.getHitBlock().getZ()),
|
||||
result.getHitBlock() != null ? WrappedBlockState.getByString(result.getHitBlock().getType().name()) : null
|
||||
);
|
||||
return new RayTraceResult(
|
||||
new Vector3d(result.getHitPosition().getX(), result.getHitPosition().getY(), result.getHitPosition().getZ()),
|
||||
getBlockFaceFrom(result.getHitBlockFace()),
|
||||
new Vector3i(result.getHitBlock().getX(), result.getHitBlock().getY(), result.getHitBlock().getZ()),
|
||||
result.getHitBlock() != null ? SpigotConversionUtil.fromBukkitBlockData(result.getHitBlock().getBlockData()) : null
|
||||
);
|
||||
// Only tested on 1.12.2
|
||||
} else {
|
||||
try {
|
||||
// Create start and end positions
|
||||
Object startPos = vec3DClass.getConstructor(double.class, double.class, double.class)
|
||||
.newInstance(start.getX(), start.getY(), start.getZ());
|
||||
Object endPos = vec3DAddMethod.invoke(startPos, direction.getX(), direction.getY(), direction.getZ());
|
||||
|
||||
// Call rayTrace method
|
||||
Object hitResult = rayTraceMethod.invoke(craftWorldGetHandleMethod.invoke(world), startPos, endPos, false, true, false);
|
||||
if (hitResult == null) return null;
|
||||
|
||||
// Extract hit position and direction
|
||||
Vector3d hitPosition = new Vector3d(
|
||||
(double) hitResult.getClass().getField("pos").get(hitResult),
|
||||
(double) hitResult.getClass().getField("pos").get(hitResult).getClass().getField("y").get(hitResult.getClass().getField("pos").get(hitResult)),
|
||||
(double) hitResult.getClass().getField("pos").get(hitResult).getClass().getField("z").get(hitResult.getClass().getField("pos").get(hitResult))
|
||||
);
|
||||
|
||||
Object hitDirection = hitResult.getClass().getField("direction").get(hitResult);
|
||||
Object hitBlock = hitResult.getClass().getField("e").get(hitResult); // e = BlockHitResult
|
||||
|
||||
return new RayTraceResult(
|
||||
hitPosition,
|
||||
getHitBlockFace(hitDirection),
|
||||
new Vector3i((int) hitBlock.getClass().getField("x").get(hitBlock),
|
||||
(int) hitBlock.getClass().getField("y").get(hitBlock),
|
||||
(int) hitBlock.getClass().getField("z").get(hitBlock)),
|
||||
hitBlock != null ? WrappedBlockState.getByString(hitBlock.getClass().getField("type").get(hitBlock).toString()) : null
|
||||
);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null; // Return null if there was an error during ray tracing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static BlockFace getHitBlockFace(Object enumDirection) {
|
||||
try {
|
||||
// Match the EnumDirection to the corresponding BlockFace
|
||||
if (enumDirection.equals(SpigotWorld.enumDirectionClass.getField("NORTH").get(null))) {
|
||||
return BlockFace.NORTH;
|
||||
} else if (enumDirection.equals(SpigotWorld.enumDirectionClass.getField("SOUTH").get(null))) {
|
||||
return BlockFace.SOUTH;
|
||||
} else if (enumDirection.equals(SpigotWorld.enumDirectionClass.getField("EAST").get(null))) {
|
||||
return BlockFace.EAST;
|
||||
} else if (enumDirection.equals(SpigotWorld.enumDirectionClass.getField("WEST").get(null))) {
|
||||
return BlockFace.WEST;
|
||||
} else if (enumDirection.equals(SpigotWorld.enumDirectionClass.getField("UP").get(null))) {
|
||||
return BlockFace.UP;
|
||||
} else if (enumDirection.equals(SpigotWorld.enumDirectionClass.getField("DOWN").get(null))) {
|
||||
return BlockFace.DOWN;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
throw new IllegalStateException("Unexpected value: " + enumDirection);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
name: KnockbackSync
|
||||
name: KnockbackSync-OG
|
||||
version: ${version}
|
||||
main: me.caseload.knockbacksync.KnockbackSyncPlugin
|
||||
api-version: '1.16'
|
||||
authors: [ Caseload ]
|
||||
main: me.caseload.knockbacksync.BukkitLoaderPlugin
|
||||
api-version: '1.13' # We actually support 1.12.2, api-version was added later though
|
||||
authors: [ Caseload, Axionize ]
|
||||
description: Synchronizes player knockback for smoother gameplay.
|
||||
folia-supported: true
|
||||
depend: ${depend}
|
||||
permissions:
|
||||
knockbacksync.update:
|
||||
default: op
|
||||
@@ -15,4 +16,8 @@ permissions:
|
||||
knockbacksync.toggle.self:
|
||||
default: op
|
||||
knockbacksync.ping:
|
||||
default: op
|
||||
knockbacksync.reload:
|
||||
default: op
|
||||
knockbacksync.toggleoffground:
|
||||
default: op
|
||||
+20
-38
@@ -1,53 +1,35 @@
|
||||
plugins {
|
||||
id("fabric-loom")
|
||||
// id("net.neoforged.moddev") version "1.0.11"
|
||||
id("com.github.gmazzo.buildconfig") version "3.1.0"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
minecraft("com.mojang:minecraft:1.16.5")
|
||||
mappings(loom.layered {
|
||||
officialMojangMappings()
|
||||
parchment("org.parchmentmc.data:parchment-1.16.5:2022.03.06")
|
||||
})
|
||||
val shadePE: Boolean by rootProject.extra
|
||||
|
||||
dependencies {
|
||||
// True compileOnly deps
|
||||
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
|
||||
compileOnly("io.netty:netty-all:4.1.72.Final")
|
||||
compileOnly("org.projectlombok:lombok:1.18.34")
|
||||
annotationProcessor("org.projectlombok:lombok:1.18.34")
|
||||
|
||||
// Shaded in or bundled by platform-specific code
|
||||
implementation("com.github.retrooper:packetevents-api:2.5.0")
|
||||
implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")
|
||||
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")
|
||||
// Upstream 2.11.2 API; runtime impl is the externally installed True-OG fork or the shaded bundle.
|
||||
if (shadePE) {
|
||||
implementation("com.github.retrooper:packetevents-api:2.11.2")
|
||||
} else {
|
||||
compileOnly("com.github.retrooper:packetevents-api:2.11.2")
|
||||
}
|
||||
|
||||
implementation("org.yaml:snakeyaml:2.0")
|
||||
implementation("org.kohsuke:github-api:1.326") {
|
||||
exclude(group = "commons-io", module = "commons-io")
|
||||
exclude(group = "org.apache.commons", module = "commons-lang3")
|
||||
}
|
||||
implementation("dev.jorel:commandapi-bukkit-shade:9.5.3")
|
||||
|
||||
implementation("org.incendo:cloud-core:2.0.0")
|
||||
implementation("org.incendo:cloud-minecraft-extras:2.0.0-beta.10")
|
||||
}
|
||||
|
||||
repositories {
|
||||
maven("https://maven.neoforged.net/releases")
|
||||
}
|
||||
|
||||
tasks.named("remapJar").configure {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
// Using neoforge in vanilla mode so common code compiles
|
||||
//neoForge {
|
||||
// Look for versions on https://projects.neoforged.net/neoforged/neoform
|
||||
// neoFormVersion.set("1.21-20240613.152323")
|
||||
|
||||
// runs {
|
||||
// create("client") {
|
||||
// client()
|
||||
// }
|
||||
// create("server") {
|
||||
// server()
|
||||
// }
|
||||
// create("data") {
|
||||
// data()
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
buildConfig {
|
||||
buildConfigField("String", "GITHUB_REPO", "\"${project.rootProject.ext["githubRepo"]}\"")
|
||||
// Exposes shadePE to source code as a compile-time constant.
|
||||
buildConfigField("boolean", "SHADE_PE", shadePE.toString())
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerCommon;
|
||||
import lombok.Getter;
|
||||
import me.caseload.knockbacksync.command.MainCommand;
|
||||
import me.caseload.knockbacksync.common.BuildConfig;
|
||||
import me.caseload.knockbacksync.command.generic.AbstractPlayerSelectorParser;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.command.subcommand.PingCommand;
|
||||
import me.caseload.knockbacksync.command.subcommand.ReloadCommand;
|
||||
import me.caseload.knockbacksync.command.subcommand.StatusCommand;
|
||||
import me.caseload.knockbacksync.command.subcommand.ToggleCommand;
|
||||
import me.caseload.knockbacksync.command.subcommand.ToggleOffGroundSubcommand;
|
||||
import me.caseload.knockbacksync.event.Event;
|
||||
import me.caseload.knockbacksync.event.EventBus;
|
||||
import me.caseload.knockbacksync.event.OptimizedEventBus;
|
||||
import me.caseload.knockbacksync.listener.packetevents.*;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.scheduler.SchedulerAdapter;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.stats.custom.ClientBrandsPie;
|
||||
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
|
||||
import me.caseload.knockbacksync.stats.custom.StatsManager;
|
||||
import me.caseload.knockbacksync.world.PlatformServer;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.kohsuke.github.GitHub;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
// Base class
|
||||
public abstract class Base {
|
||||
public static Logger LOGGER;
|
||||
public static Base INSTANCE;
|
||||
|
||||
@Getter private final Platform platform;
|
||||
@Getter protected StatsManager statsManager;
|
||||
@Getter protected PlatformServer platformServer;
|
||||
@Getter protected PluginJarHashProvider pluginJarHashProvider;
|
||||
@Getter protected SchedulerAdapter scheduler;
|
||||
@Getter protected ConfigManager configManager;
|
||||
@Getter protected CommandManager<Sender> commandManager;
|
||||
@Getter protected final EventBus eventBus = new OptimizedEventBus();
|
||||
|
||||
@Getter
|
||||
protected AbstractPlayerSelectorParser<Sender> playerSelectorParser;
|
||||
|
||||
// Tracked so onDisable can unregister exactly the listeners registered against the shared provider.
|
||||
private final java.util.List<PacketListenerCommon> peListenerHandles = new java.util.ArrayList<>();
|
||||
|
||||
protected Base() {
|
||||
this.platform = detectPlatform();
|
||||
INSTANCE = this;
|
||||
}
|
||||
|
||||
private Platform detectPlatform() {
|
||||
final Map<String, Platform> platforms = Collections.unmodifiableMap(new HashMap<String, Platform>() {{
|
||||
put("io.papermc.paper.threadedregions.RegionizedServer", Platform.FOLIA);
|
||||
put("org.bukkit.Bukkit", Platform.BUKKIT);
|
||||
put("net.fabricmc.loader.api.FabricLoader", Platform.FABRIC);
|
||||
}});
|
||||
|
||||
return platforms.entrySet().stream()
|
||||
.filter(entry -> isClassPresent(entry.getKey()))
|
||||
.map(Map.Entry::getValue)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("Unknown platform!"));
|
||||
}
|
||||
|
||||
private boolean isClassPresent(String className) {
|
||||
try {
|
||||
Class.forName(className);
|
||||
return true;
|
||||
} catch (ClassNotFoundException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract Logger getLogger();
|
||||
|
||||
public abstract File getDataFolder();
|
||||
|
||||
public abstract InputStream getResource(String filename);
|
||||
|
||||
public abstract void load();
|
||||
|
||||
public void enable() {
|
||||
LOGGER = getLogger();
|
||||
saveDefaultConfig();
|
||||
initializePacketEvents();
|
||||
registerCommonListeners();
|
||||
registerPlatformListeners();
|
||||
registerCommands();
|
||||
initializeScheduler();
|
||||
configManager.loadConfig(false);
|
||||
statsManager.init();
|
||||
checkForUpdates();
|
||||
}
|
||||
|
||||
public abstract void initializeScheduler();
|
||||
|
||||
public void initializePacketEvents() {
|
||||
// External-provider mode skips lifecycle ownership entirely.
|
||||
if (!BuildConfig.SHADE_PE) {
|
||||
return;
|
||||
}
|
||||
PacketEvents.getAPI().getSettings()
|
||||
.checkForUpdates(false)
|
||||
.debug(false);
|
||||
|
||||
PacketEvents.getAPI().init();
|
||||
}
|
||||
|
||||
protected void registerCommonListeners() {
|
||||
registerTrackedPacketListener(new AttributeChangeListener());
|
||||
registerTrackedPacketListener(new PingSendListener());
|
||||
registerTrackedPacketListener(new PingReceiveListener());
|
||||
registerTrackedPacketListener(new PacketPlayerJoinQuit());
|
||||
registerTrackedPacketListener(new ClientBrandListener());
|
||||
Event.setEventBus(eventBus);
|
||||
}
|
||||
|
||||
/** Register a PacketEvents listener and remember its handle for unregister on disable. */
|
||||
protected void registerTrackedPacketListener(PacketListenerCommon listener) {
|
||||
PacketEvents.getAPI().getEventManager().registerListener(listener);
|
||||
peListenerHandles.add(listener);
|
||||
}
|
||||
|
||||
/** Unregister every tracked PacketEvents listener. */
|
||||
public void unregisterPacketListeners() {
|
||||
for (PacketListenerCommon handle : peListenerHandles) {
|
||||
try {
|
||||
PacketEvents.getAPI().getEventManager().unregisterListener(handle);
|
||||
} catch (Throwable t) {
|
||||
if (LOGGER != null) {
|
||||
LOGGER.warning("Failed to unregister PE listener: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
peListenerHandles.clear();
|
||||
}
|
||||
|
||||
protected abstract void registerPlatformListeners();
|
||||
|
||||
protected void registerCommands() {
|
||||
List<BuilderCommand> list = Arrays.asList(
|
||||
new MainCommand(),
|
||||
new ReloadCommand(),
|
||||
new PingCommand(),
|
||||
new StatusCommand(),
|
||||
new ToggleOffGroundSubcommand(),
|
||||
new ToggleCommand()
|
||||
);
|
||||
list.forEach(command -> command.register(commandManager));
|
||||
}
|
||||
|
||||
protected abstract String getVersion();
|
||||
|
||||
protected void checkForUpdates() {
|
||||
getLogger().info("Checking for updates...");
|
||||
|
||||
scheduler.runTaskAsynchronously(() -> {
|
||||
try {
|
||||
GitHub github = GitHub.connectAnonymously();
|
||||
String latestVersion = github.getRepository("CASELOAD7000/knockback-sync")
|
||||
.getLatestRelease()
|
||||
.getTagName();
|
||||
|
||||
String currentVersion = getVersion();
|
||||
|
||||
int comparisonResult = compareVersions(currentVersion, latestVersion);
|
||||
|
||||
if (comparisonResult < 0) {
|
||||
LOGGER.warning("You are running an older version. A new update is available for download at: https://github.com/CASELOAD7000/knockback-sync/releases/latest");
|
||||
configManager.setUpdateAvailable(true);
|
||||
} else if (comparisonResult > 0) {
|
||||
if (currentVersion.contains("-dev"))
|
||||
LOGGER.info("You are running a development build newer than the latest release.");
|
||||
else {
|
||||
LOGGER.info("You are running a version newer than the latest release.");
|
||||
}
|
||||
} else {
|
||||
LOGGER.info("You are running the latest release.");
|
||||
}
|
||||
|
||||
if (configManager.isUpdateAvailable() && configManager.isAutoUpdate()) {
|
||||
LOGGER.info("Updating...");
|
||||
byte[] bytes = downloadLatestRelease(github);
|
||||
updatePlugin(bytes);
|
||||
|
||||
if (hasRestartScript())
|
||||
scheduler.runTask(this::restartServer);
|
||||
else {
|
||||
// Yeah
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to check for updates: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void updatePlugin(byte[] pluginBytes) throws URISyntaxException {
|
||||
File file = new File(getJarURL().toURI());
|
||||
|
||||
try (FileOutputStream outputStream = new FileOutputStream(file)) {
|
||||
outputStream.write(pluginBytes);
|
||||
LOGGER.info("Successfully updated the plugin!");
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to update: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] downloadLatestRelease(GitHub github) {
|
||||
try {
|
||||
return github.getRepository("CASELOAD7000/knockback-sync")
|
||||
.getLatestRelease()
|
||||
.getAssets().stream()
|
||||
.filter(asset -> asset.getName().endsWith(".jar")
|
||||
&& asset.getName().contains(platform.equals(Platform.FABRIC)
|
||||
? "fabric" : "bukkit"))
|
||||
.findFirst()
|
||||
.map(asset -> {
|
||||
try (InputStream inputStream = new URL(asset.getBrowserDownloadUrl()).openStream()) {
|
||||
inputStream.reset();
|
||||
byte[] bytes = new byte[inputStream.available()];
|
||||
DataInputStream dataInputStream = new DataInputStream(inputStream);
|
||||
dataInputStream.readFully(bytes);
|
||||
return bytes;
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to download latest release: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}).orElse(null);
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to locate latest release: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private int compareVersions(String version1, String version2) {
|
||||
String[] v1Parts = version1.split("[-.]");
|
||||
String[] v2Parts = version2.split("[-.]");
|
||||
|
||||
int length = Math.min(v1Parts.length, v2Parts.length);
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
int comparison = compareVersionPart(v1Parts[i], v2Parts[i]);
|
||||
if (comparison != 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
// If we're here, all compared parts are equal
|
||||
if (v1Parts.length != v2Parts.length) {
|
||||
return compareSpecialVersions(v1Parts, v2Parts);
|
||||
}
|
||||
|
||||
return 0; // Versions are equal
|
||||
}
|
||||
|
||||
private int compareVersionPart(String part1, String part2) {
|
||||
try {
|
||||
int v1 = Integer.parseInt(part1);
|
||||
int v2 = Integer.parseInt(part2);
|
||||
return Integer.compare(v1, v2);
|
||||
} catch (NumberFormatException e) {
|
||||
// If parts are not numbers, compare them based on dev < snapshot < release
|
||||
return compareSpecialPart(part1, part2);
|
||||
}
|
||||
}
|
||||
|
||||
private int compareSpecialPart(String part1, String part2) {
|
||||
if (part1.equals(part2)) return 0;
|
||||
if (part1.startsWith("dev")) return part2.startsWith("dev") ? 0 : -1;
|
||||
if (part2.startsWith("dev")) return 1;
|
||||
if (part1.equals("SNAPSHOT")) return part2.equals("SNAPSHOT") ? 0 : -1;
|
||||
if (part2.equals("SNAPSHOT")) return 1;
|
||||
return part1.compareTo(part2);
|
||||
}
|
||||
|
||||
private int compareSpecialVersions(String[] v1Parts, String[] v2Parts) {
|
||||
if (v1Parts.length > v2Parts.length) {
|
||||
String specialPart = v1Parts[v2Parts.length];
|
||||
if (specialPart.startsWith("dev")) return -1;
|
||||
if (specialPart.equals("SNAPSHOT")) return -1;
|
||||
return 1; // Assume it's a release version part
|
||||
} else {
|
||||
String specialPart = v2Parts[v1Parts.length];
|
||||
if (specialPart.startsWith("dev")) return 1;
|
||||
if (specialPart.equals("SNAPSHOT")) return 1;
|
||||
return -1; // Assume it's a release version part
|
||||
}
|
||||
}
|
||||
|
||||
public abstract void saveDefaultConfig();
|
||||
|
||||
public abstract PermissionChecker getPermissionChecker();
|
||||
|
||||
public abstract float getTickRate();
|
||||
|
||||
public abstract URL getJarURL();
|
||||
|
||||
public abstract void restartServer();
|
||||
|
||||
public abstract boolean hasRestartScript();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@ package me.caseload.knockbacksync;
|
||||
import me.caseload.knockbacksync.util.NumberConversions;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class ConfigWrapper {
|
||||
private final Map<String, Object> configMap;
|
||||
@@ -32,6 +34,19 @@ public class ConfigWrapper {
|
||||
return NumberConversions.toLong(value, def);
|
||||
}
|
||||
|
||||
public double getDouble(String path, double def) {
|
||||
Object value = getValue(path);
|
||||
if (value instanceof Number) return ((Number) value).doubleValue();
|
||||
if (value instanceof String) {
|
||||
try {
|
||||
return Double.parseDouble((String) value);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
public void set(String path, Object value) {
|
||||
setValue(path, value);
|
||||
}
|
||||
@@ -61,4 +76,20 @@ public class ConfigWrapper {
|
||||
}
|
||||
current.put(parts[parts.length - 1], value);
|
||||
}
|
||||
|
||||
public boolean contains(String path) {
|
||||
return getValue(path) != null;
|
||||
}
|
||||
|
||||
public Object get(String path) {
|
||||
return getValue(path);
|
||||
}
|
||||
|
||||
public Set<String> getKeys(String path) {
|
||||
Object value = getValue(path);
|
||||
if (value instanceof Map) {
|
||||
return ((Map<String, Object>) value).keySet();
|
||||
}
|
||||
return new HashSet<>();
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import me.caseload.knockbacksync.command.SenderFactory;
|
||||
import me.caseload.knockbacksync.listener.packetevents.AttributeChangeListener;
|
||||
import me.caseload.knockbacksync.listener.packetevents.PingReceiveListener;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.scheduler.SchedulerAdapter;
|
||||
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
|
||||
import me.caseload.knockbacksync.stats.custom.StatsManager;
|
||||
import me.caseload.knockbacksync.world.PlatformServer;
|
||||
import org.kohsuke.github.GitHub;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
// Base class
|
||||
public abstract class KnockbackSyncBase {
|
||||
public static Logger LOGGER;
|
||||
public static KnockbackSyncBase INSTANCE;
|
||||
public Platform platform;
|
||||
public StatsManager statsManager;
|
||||
public PlatformServer platformServer;
|
||||
public PluginJarHashProvider pluginJarHashProvider;
|
||||
@Getter
|
||||
protected SchedulerAdapter scheduler;
|
||||
@Getter
|
||||
protected ConfigManager configManager;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
private SenderFactory<? extends KnockbackSyncBase, ?> senderFactory;
|
||||
|
||||
protected KnockbackSyncBase() {
|
||||
this.platform = getPlatform();
|
||||
INSTANCE = this;
|
||||
configManager = new ConfigManager();
|
||||
}
|
||||
|
||||
private Platform getPlatform() {
|
||||
try {
|
||||
Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
|
||||
return Platform.FOLIA; // Paper (Folia) detected
|
||||
} catch (ClassNotFoundException ignored1) {
|
||||
}
|
||||
|
||||
try {
|
||||
Class.forName("org.bukkit.Bukkit");
|
||||
return Platform.BUKKIT; // Bukkit (Spigot/Paper without Folia) detected
|
||||
} catch (ClassNotFoundException ignored2) {
|
||||
}
|
||||
|
||||
try {
|
||||
Class.forName("net.fabricmc.loader.api.FabricLoader");
|
||||
return Platform.FABRIC; // Fabric detected
|
||||
} catch (ClassNotFoundException ignored3) {
|
||||
}
|
||||
|
||||
throw new IllegalStateException("Unknown platform!");
|
||||
}
|
||||
|
||||
public abstract Logger getLogger();
|
||||
|
||||
public abstract File getDataFolder();
|
||||
|
||||
public abstract InputStream getResource(String filename);
|
||||
|
||||
public abstract void load();
|
||||
|
||||
public void enable() {
|
||||
LOGGER = getLogger();
|
||||
saveDefaultConfig();
|
||||
initializePacketEvents();
|
||||
registerCommonListeners();
|
||||
registerPlatformListeners();
|
||||
registerCommands();
|
||||
}
|
||||
|
||||
public abstract void initializeScheduler();
|
||||
|
||||
public void initializePacketEvents() {
|
||||
PacketEvents.getAPI().getSettings()
|
||||
.checkForUpdates(false)
|
||||
.debug(false);
|
||||
|
||||
PacketEvents.getAPI().init();
|
||||
}
|
||||
|
||||
protected void registerCommonListeners() {
|
||||
PacketEvents.getAPI().getEventManager().registerListeners(
|
||||
new AttributeChangeListener(),
|
||||
new PingReceiveListener()
|
||||
);
|
||||
}
|
||||
|
||||
protected abstract void registerPlatformListeners();
|
||||
|
||||
protected abstract void registerCommands();
|
||||
|
||||
protected abstract String getVersion();
|
||||
|
||||
protected void checkForUpdates() {
|
||||
getLogger().info("Checking for updates...");
|
||||
|
||||
scheduler.runTaskAsynchronously(() -> {
|
||||
try {
|
||||
GitHub github = GitHub.connectAnonymously();
|
||||
String latestVersion = github.getRepository("CASELOAD7000/knockback-sync")
|
||||
.getLatestRelease()
|
||||
.getTagName();
|
||||
|
||||
String currentVersion = getVersion();
|
||||
|
||||
int comparisonResult = compareVersions(currentVersion, latestVersion);
|
||||
|
||||
if (comparisonResult < 0) {
|
||||
LOGGER.warning("You are running an older version. A new update is available for download at: https://github.com/CASELOAD7000/knockback-sync/releases/latest");
|
||||
configManager.setUpdateAvailable(true);
|
||||
} else if (comparisonResult > 0) {
|
||||
if (currentVersion.contains("-dev")) {
|
||||
LOGGER.info("You are running a development build newer than the latest release.");
|
||||
} else {
|
||||
LOGGER.info("You are running a version newer than the latest release.");
|
||||
}
|
||||
configManager.setUpdateAvailable(false);
|
||||
} else {
|
||||
LOGGER.info("You are running the latest release.");
|
||||
configManager.setUpdateAvailable(false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to check for updates: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private int compareVersions(String version1, String version2) {
|
||||
String[] v1Parts = version1.split("[-.]");
|
||||
String[] v2Parts = version2.split("[-.]");
|
||||
|
||||
int length = Math.min(v1Parts.length, v2Parts.length);
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
int comparison = compareVersionPart(v1Parts[i], v2Parts[i]);
|
||||
if (comparison != 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
// If we're here, all compared parts are equal
|
||||
if (v1Parts.length != v2Parts.length) {
|
||||
return compareSpecialVersions(v1Parts, v2Parts);
|
||||
}
|
||||
|
||||
return 0; // Versions are equal
|
||||
}
|
||||
|
||||
private int compareVersionPart(String part1, String part2) {
|
||||
try {
|
||||
int v1 = Integer.parseInt(part1);
|
||||
int v2 = Integer.parseInt(part2);
|
||||
return Integer.compare(v1, v2);
|
||||
} catch (NumberFormatException e) {
|
||||
// If parts are not numbers, compare them based on dev < snapshot < release
|
||||
return compareSpecialPart(part1, part2);
|
||||
}
|
||||
}
|
||||
|
||||
private int compareSpecialPart(String part1, String part2) {
|
||||
if (part1.equals(part2)) return 0;
|
||||
if (part1.startsWith("dev")) return part2.startsWith("dev") ? 0 : -1;
|
||||
if (part2.startsWith("dev")) return 1;
|
||||
if (part1.equals("SNAPSHOT")) return part2.equals("SNAPSHOT") ? 0 : -1;
|
||||
if (part2.equals("SNAPSHOT")) return 1;
|
||||
return part1.compareTo(part2);
|
||||
}
|
||||
|
||||
private int compareSpecialVersions(String[] v1Parts, String[] v2Parts) {
|
||||
if (v1Parts.length > v2Parts.length) {
|
||||
String specialPart = v1Parts[v2Parts.length];
|
||||
if (specialPart.startsWith("dev")) return -1;
|
||||
if (specialPart.equals("SNAPSHOT")) return -1;
|
||||
return 1; // Assume it's a release version part
|
||||
} else {
|
||||
String specialPart = v2Parts[v1Parts.length];
|
||||
if (specialPart.startsWith("dev")) return 1;
|
||||
if (specialPart.equals("SNAPSHOT")) return 1;
|
||||
return -1; // Assume it's a release version part
|
||||
}
|
||||
}
|
||||
|
||||
public abstract void saveDefaultConfig();
|
||||
|
||||
public abstract PermissionChecker getPermissionChecker();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
package me.caseload.knockbacksync.command;
|
||||
|
||||
public interface CommandSource {
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package me.caseload.knockbacksync.command;
|
||||
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
|
||||
public class MainCommand implements BuilderCommand {
|
||||
public void register(CommandManager<Sender> manager) {
|
||||
manager.command(
|
||||
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
|
||||
.handler(context -> {
|
||||
context.sender().sendMessage(
|
||||
ChatUtil.translateAlternateColorCodes(
|
||||
'&',
|
||||
"&6This server is running the &eKnockbackSync &6plugin. &bhttps://github.com/CASELOAD7000/knockback-sync"
|
||||
)
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package me.caseload.knockbacksync.command.generic;
|
||||
|
||||
import org.incendo.cloud.context.CommandContext;
|
||||
import org.incendo.cloud.parser.ParserDescriptor;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public abstract class AbstractPlayerSelectorParser<C> {
|
||||
|
||||
public abstract ParserDescriptor<C, PlayerSelector> descriptor();
|
||||
|
||||
protected abstract ParserDescriptor<C, ?> getPlatformSpecificDescriptor();
|
||||
|
||||
protected abstract CompletableFuture<PlayerSelector> adaptToCommonSelector(CommandContext<C> context, Object platformSpecificSelector);
|
||||
|
||||
// Helper method to create the ParserDescriptor
|
||||
protected ParserDescriptor<C, PlayerSelector> createDescriptor() {
|
||||
return ParserDescriptor.of(
|
||||
getPlatformSpecificDescriptor().parser().mapSuccess(this::adaptToCommonSelector),
|
||||
PlayerSelector.class
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package me.caseload.knockbacksync.command.generic;
|
||||
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
|
||||
public interface BuilderCommand {
|
||||
|
||||
void register(CommandManager<Sender> manager);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package me.caseload.knockbacksync.command.generic;
|
||||
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public interface PlayerSelector {
|
||||
boolean isSingle();
|
||||
|
||||
PlatformPlayer getSinglePlayer(); // Throws an exception if not a single selection
|
||||
|
||||
Collection<PlatformPlayer> getPlayers();
|
||||
|
||||
String inputString();
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package me.caseload.knockbacksync.command.subcommand;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.incendo.cloud.permission.PredicatePermission;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class PingCommand implements BuilderCommand {
|
||||
|
||||
private static final ConfigManager configManager = Base.INSTANCE.getConfigManager();
|
||||
|
||||
private String pingSelfAvailableMessage;
|
||||
private String pingSelfUnavailableMessage;
|
||||
private String pingOtherAvailableMessage;
|
||||
private String pingOtherUnavailableMessage;
|
||||
|
||||
private String mustSpecifyPlayerFromConsoleMessage;
|
||||
private String knockbacksyncDisabledForYouMessage;
|
||||
private String knockbacksyncDisabledForTargetMessage;
|
||||
|
||||
public PingCommand() {
|
||||
loadConfig();
|
||||
}
|
||||
|
||||
public void register(CommandManager<Sender> manager) {
|
||||
manager.command(
|
||||
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
|
||||
.permission((sender -> {
|
||||
final String permission = "knockbacksync.ping";
|
||||
Predicate<Sender> senderPredicate = (s) -> {
|
||||
return s.hasPermission(permission, true);
|
||||
};
|
||||
|
||||
return PredicatePermission.of(senderPredicate).testPermission(sender);
|
||||
}))
|
||||
.literal("ping")
|
||||
.optional("target", Base.INSTANCE.getPlayerSelectorParser().descriptor())
|
||||
.handler(context -> {
|
||||
PlayerSelector targetSelector = context.getOrDefault("target", null);
|
||||
|
||||
if (targetSelector == null) {
|
||||
if (context.sender().isConsole()) {
|
||||
context.sender().sendMessage(ChatUtil.translateAlternateColorCodes('&', mustSpecifyPlayerFromConsoleMessage));
|
||||
} else {
|
||||
context.sender().sendMessage(getPingMessage(context.sender().getUniqueId(), context.sender().getName(), null, null));
|
||||
}
|
||||
} else {
|
||||
context.sender().sendMessage(getPingMessage(context.sender().getUniqueId(), context.sender().getName(), targetSelector.getSinglePlayer().getUUID(), targetSelector.getSinglePlayer().getName()));
|
||||
}
|
||||
})
|
||||
);
|
||||
Base.INSTANCE.getEventBus().registerListeners(this);
|
||||
}
|
||||
private void loadConfig() {
|
||||
ConfigWrapper configWrapper = configManager.getConfigWrapper();
|
||||
pingSelfAvailableMessage = configWrapper.getString("messages.ping.self.available",
|
||||
"Your real ping is &b%ping%&rms. Jitter: &b%jitter%&rms. Spike: &b%spike%&r. Compensated ping: &b%compensated%&rms.");
|
||||
pingSelfUnavailableMessage = configWrapper.getString("messages.ping.self.unavailable",
|
||||
"Accurate ping unavailable. Your estimated ping is &b%ping%&rms.");
|
||||
pingOtherAvailableMessage = configWrapper.getString("messages.ping.other.available",
|
||||
"%player%'s real ping is &b%ping%&rms. Jitter: &b%jitter%&rms. Spike: &b%spike%&r. Compensated ping: &b%compensated%&rms.");
|
||||
pingOtherUnavailableMessage = configWrapper.getString("messages.ping.other.unavailable",
|
||||
"Accurate ping unavailable. %player%'s estimated ping is &b%ping%&rms.");
|
||||
mustSpecifyPlayerFromConsoleMessage = configWrapper.getString("messages.console.must_specify_player",
|
||||
"&cYou must specify a player to use the knockbacksync ping command from the console.");
|
||||
knockbacksyncDisabledForYouMessage = configWrapper.getString("messages.disabled.self",
|
||||
"&cKnockback synchronization is currently disabled for you!");
|
||||
knockbacksyncDisabledForTargetMessage = configWrapper.getString("messages.disabled.target",
|
||||
"&cKnockback synchronization is currently disabled for the target player.");
|
||||
}
|
||||
|
||||
private String getPingMessage(UUID senderUUID, String senderName, UUID targetUUID, String targetName) {
|
||||
boolean isSelf = senderUUID.equals(targetUUID) || targetUUID == null;
|
||||
String message;
|
||||
if (isSelf) {
|
||||
message = knockbacksyncDisabledForYouMessage;
|
||||
targetUUID = senderUUID;
|
||||
targetName = senderName;
|
||||
} else {
|
||||
message = knockbacksyncDisabledForTargetMessage;
|
||||
}
|
||||
|
||||
User targetUser = Base.INSTANCE.getPlatformServer().getPlayer(targetUUID).getUser();
|
||||
if (targetUser == null)
|
||||
return ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerDisconnectedWhileExecutingCommand()
|
||||
).replace("%player%", targetName);
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(targetUser);
|
||||
if (playerData == null)
|
||||
return ChatUtil.translateAlternateColorCodes('&', message);
|
||||
|
||||
String rawReturnString;
|
||||
if (playerData.getPing() == null) {
|
||||
rawReturnString = isSelf ? pingSelfUnavailableMessage : pingOtherUnavailableMessage;
|
||||
} else {
|
||||
rawReturnString = isSelf ? pingSelfAvailableMessage : pingOtherAvailableMessage;
|
||||
}
|
||||
|
||||
rawReturnString = rawReturnString
|
||||
.replace("%player%", playerData.getPlatformPlayer().getName())
|
||||
.replace("%ping%", playerData.getPing() == null ?
|
||||
String.valueOf(playerData.getPlatformPlayer().getPing()) :
|
||||
String.format("%.3f", playerData.getPing()))
|
||||
.replace("%jitter%", String.format("%.3f", playerData.getJitter()))
|
||||
.replace("%spike%", String.valueOf(playerData.isSpike()))
|
||||
.replace("%compensated%", String.format("%.3f", playerData.getCompensatedPing()));
|
||||
|
||||
return ChatUtil.translateAlternateColorCodes('&', rawReturnString);
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onConfigReload(ConfigReloadEvent event) {
|
||||
loadConfig();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package me.caseload.knockbacksync.command.subcommand;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.incendo.cloud.permission.PredicatePermission;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class ReloadCommand implements BuilderCommand {
|
||||
|
||||
private static final ConfigManager configManager = Base.INSTANCE.getConfigManager();
|
||||
private String rawReloadMessage = configManager.getConfigWrapper().getString("messages.reload.success", "&aSuccessfully reloaded KnockbackSync.");
|
||||
|
||||
public void register(CommandManager<Sender> manager) {
|
||||
manager.command(
|
||||
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
|
||||
.literal("reload")
|
||||
.permission((sender -> {
|
||||
final String permission = "knockbacksync.reload";
|
||||
Predicate<Sender> senderPredicate = (s) -> {
|
||||
return s.hasPermission(permission, false);
|
||||
};
|
||||
|
||||
return PredicatePermission.of(senderPredicate).testPermission(sender);
|
||||
}))
|
||||
.handler(context -> {
|
||||
configManager.loadConfig(true);
|
||||
|
||||
// Fire the ConfigReloadEvent
|
||||
new ConfigReloadEvent(configManager).post();
|
||||
|
||||
String reloadMessage = ChatUtil.translateAlternateColorCodes('&', rawReloadMessage);
|
||||
|
||||
context.sender().sendMessage(reloadMessage);
|
||||
})
|
||||
);
|
||||
Base.INSTANCE.getEventBus().registerListeners(this);
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onConfigReload(ConfigReloadEvent event) {
|
||||
rawReloadMessage = event.getConfigManager().getConfigWrapper().getString("messages.reload.success", "&aSuccessfully reloaded KnockbackSync.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package me.caseload.knockbacksync.command.subcommand;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.incendo.cloud.permission.PredicatePermission;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class StatusCommand implements BuilderCommand {
|
||||
|
||||
private static final ConfigManager configManager = Base.INSTANCE.getConfigManager();
|
||||
private static final String STATUS_SELF_PERMISSION = "knockbacksync.status.self";
|
||||
private static final String STATUS_OTHER_PERMISSION = "knockbacksync.status.other";
|
||||
|
||||
private String globalStatusEnabledMessage;
|
||||
private String globalStatusDisabledMessage;
|
||||
private String globalOffGroundStatusEnabledMessage;
|
||||
private String globalOffGroundStatusDisabledMessage;
|
||||
private String playerStatusEnabledMessage;
|
||||
private String playerStatusDisabledMessage;
|
||||
private String playerStatusGlobalDisabledMessage;
|
||||
private String noSelfPermissionMessage;
|
||||
private String noOtherPermissionMessage;
|
||||
|
||||
public StatusCommand() {
|
||||
updateConfigValues();
|
||||
}
|
||||
|
||||
public void register(CommandManager<Sender> manager) {
|
||||
manager.command(
|
||||
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
|
||||
.literal("status")
|
||||
.optional("target", Base.INSTANCE.getPlayerSelectorParser().descriptor())
|
||||
.permission((sender -> {
|
||||
Predicate<Sender> senderPredicate = (s) -> {
|
||||
return s.hasPermission(STATUS_SELF_PERMISSION, true) || sender.hasPermission(STATUS_OTHER_PERMISSION, false);
|
||||
};
|
||||
|
||||
return PredicatePermission.of(senderPredicate).testPermission(sender);
|
||||
}))
|
||||
.handler(context -> {
|
||||
Sender sender = context.sender();
|
||||
PlayerSelector targetSelector = context.getOrDefault("target", null);
|
||||
if (targetSelector == null) {
|
||||
// Show global status
|
||||
boolean globalStatus = configManager.isToggled();
|
||||
sender.sendMessage(
|
||||
ChatUtil.translateAlternateColorCodes('&',
|
||||
(globalStatus ? globalStatusEnabledMessage : globalStatusDisabledMessage))
|
||||
+ "\n"
|
||||
+ ChatUtil.translateAlternateColorCodes('&',
|
||||
ToggleOffGroundSubcommand.offGroundSyncEnabled ? globalOffGroundStatusEnabledMessage : globalOffGroundStatusDisabledMessage)
|
||||
);
|
||||
|
||||
if (sender.hasPermission(STATUS_SELF_PERMISSION, true)) {
|
||||
// Show player status for the sender (no target specified)
|
||||
if (!sender.isConsole()) {
|
||||
showPlayerStatus(sender, Base.INSTANCE.getPlatformServer().getPlayer(sender.getUniqueId()));
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', noSelfPermissionMessage));
|
||||
}
|
||||
} else {
|
||||
if (sender.hasPermission(STATUS_OTHER_PERMISSION, true)) {
|
||||
PlatformPlayer target = targetSelector.getSinglePlayer();
|
||||
showPlayerStatus(sender, target);
|
||||
} else {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', noOtherPermissionMessage));
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
Base.INSTANCE.getEventBus().registerListeners(this);
|
||||
}
|
||||
|
||||
private void showPlayerStatus(Sender sender, PlatformPlayer target) {
|
||||
if (target.getUser() == null) {
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerDisconnectedWhileExecutingCommand()
|
||||
).replace("%player%", target.getName());
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
boolean globalStatus = configManager.isToggled();
|
||||
boolean playerStatus = PlayerDataManager.containsPlayerData(target.getUser());
|
||||
|
||||
String statusMessage;
|
||||
if (!globalStatus) {
|
||||
statusMessage = playerStatusGlobalDisabledMessage.replace("%player%", target.getName());
|
||||
} else {
|
||||
statusMessage = (playerStatus ? this.playerStatusEnabledMessage : this.playerStatusDisabledMessage).replace("%player%", target.getName());
|
||||
}
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', statusMessage));
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onConfigReload(ConfigReloadEvent event) {
|
||||
updateConfigValues();
|
||||
}
|
||||
|
||||
private void updateConfigValues() {
|
||||
ConfigWrapper config = configManager.getConfigWrapper();
|
||||
this.globalStatusEnabledMessage = config.getString("messages.status.global.enabled",
|
||||
"&eKnockbackSync global status: &aEnabled");
|
||||
this.globalStatusDisabledMessage = config.getString("messages.status.global.disabled",
|
||||
"&eKnockbackSync global status: &cDisabled");
|
||||
this.globalOffGroundStatusEnabledMessage = config.getString("messages.status.offground.enabled",
|
||||
"&eKnockbackSync off-ground status: &aEnabled");
|
||||
this.globalOffGroundStatusDisabledMessage = config.getString("messages.status.offground.disabled",
|
||||
"&eKnockbackSync off-ground status: &cDisabled");
|
||||
this.playerStatusEnabledMessage = config.getString("messages.status.player.enabled",
|
||||
"&e%player%'s KnockbackSync status: &aEnabled");
|
||||
this.playerStatusDisabledMessage = config.getString("messages.status.player.disabled",
|
||||
"&e%player%'s KnockbackSync status: &cDisabled");
|
||||
this.playerStatusGlobalDisabledMessage = config.getString("messages.status.player.global_disabled",
|
||||
"&e%player%'s KnockbackSync status: &cDisabled (Global toggle is off)");
|
||||
this.noSelfPermissionMessage = config.getString("messages.status.permission.no_self",
|
||||
"&cYou do not have permission to check your knockbacksync status.");
|
||||
this.noOtherPermissionMessage = config.getString("messages.status.permission.no_other",
|
||||
"&cYou do not have permission to check the status of other players!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package me.caseload.knockbacksync.command.subcommand;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import me.caseload.knockbacksync.event.events.ToggleOnOffEvent;
|
||||
import me.caseload.knockbacksync.manager.CombatManager;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.incendo.cloud.permission.PredicatePermission;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class ToggleCommand implements BuilderCommand {
|
||||
|
||||
private static final ConfigManager configManager = Base.INSTANCE.getConfigManager();
|
||||
private static final PermissionChecker permissionChecker = Base.INSTANCE.getPermissionChecker();
|
||||
private static final String TOGGLE_GLOBAL_PERMISSION = "knockbacksync.toggle.global";
|
||||
private static final String TOGGLE_SELF_PERMISSION = "knockbacksync.toggle.self";
|
||||
private static final String TOGGLE_OTHER_PERMISSION = "knockbacksync.toggle.other";
|
||||
|
||||
private String noGlobalPermissionMessage;
|
||||
private String noSelfPermissionMessage;
|
||||
private String noOtherPermissionMessage;
|
||||
private String serverDisabledMessage;
|
||||
|
||||
public ToggleCommand() {
|
||||
loadConfig();
|
||||
}
|
||||
|
||||
private void loadConfig() {
|
||||
ConfigWrapper configWrapper = configManager.getConfigWrapper();
|
||||
noGlobalPermissionMessage = configWrapper.getString("messages.toggle.permission.no_global",
|
||||
"&cYou don't have permission to toggle the global setting.");
|
||||
noSelfPermissionMessage = configWrapper.getString("messages.toggle.permission.no_self",
|
||||
"&cYou do not have permission to toggle your knockback.");
|
||||
noOtherPermissionMessage = configWrapper.getString("messages.toggle.permission.no_other",
|
||||
"&cYou do not have permission to toggle the knockback of other player's.");
|
||||
serverDisabledMessage = configWrapper.getString("messages.toggle.server_disabled",
|
||||
"&cKnockbacksync is currently disabled on this server. Contact your server administrator for more information.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register(CommandManager<Sender> manager) {
|
||||
manager.command(
|
||||
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
|
||||
.literal("toggle")
|
||||
.optional("target", Base.INSTANCE.getPlayerSelectorParser().descriptor())
|
||||
.permission((sender -> {
|
||||
Predicate<Sender> senderPredicate = (s) -> {
|
||||
return s.hasPermission(TOGGLE_GLOBAL_PERMISSION, false)
|
||||
|| sender.hasPermission(TOGGLE_SELF_PERMISSION, false)
|
||||
|| sender.hasPermission(TOGGLE_OTHER_PERMISSION, false);
|
||||
};
|
||||
|
||||
return PredicatePermission.of(senderPredicate).testPermission(sender);
|
||||
}))
|
||||
.handler(context -> {
|
||||
Sender sender = context.sender();
|
||||
PlayerSelector targetSelector = context.getOrDefault("target", null);
|
||||
if (targetSelector == null) {
|
||||
// Global toggle
|
||||
if (permissionChecker.hasPermission(sender, TOGGLE_GLOBAL_PERMISSION, false)) {
|
||||
toggleGlobalKnockback(sender);
|
||||
} else {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', noGlobalPermissionMessage));
|
||||
}
|
||||
} else {
|
||||
PlatformPlayer target = targetSelector.getSinglePlayer();
|
||||
boolean senderIsTarget = sender.getUniqueId() == target.getUUID();
|
||||
if (!senderIsTarget && !permissionChecker.hasPermission(sender, TOGGLE_OTHER_PERMISSION, false)) {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', noOtherPermissionMessage));
|
||||
return;
|
||||
} else if (senderIsTarget && !permissionChecker.hasPermission(sender, TOGGLE_SELF_PERMISSION, true)) {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', noSelfPermissionMessage));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!configManager.isToggled()) {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', serverDisabledMessage));
|
||||
} else {
|
||||
togglePlayerKnockback(target, sender);
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private static void toggleGlobalKnockback(Sender sender) {
|
||||
boolean toggledState = !configManager.isToggled();
|
||||
ToggleOnOffEvent toggleOnOffEvent = new ToggleOnOffEvent(toggledState);
|
||||
toggleOnOffEvent.post();
|
||||
if (toggleOnOffEvent.isCancelled())
|
||||
return;
|
||||
|
||||
toggledState = toggleOnOffEvent.getStatus();
|
||||
configManager.setToggled(toggledState);
|
||||
|
||||
configManager.getConfigWrapper().set("enabled", toggledState);
|
||||
configManager.saveConfig();
|
||||
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
toggledState ? configManager.getEnableMessage() : configManager.getDisableMessage()
|
||||
);
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', message));
|
||||
}
|
||||
|
||||
private static void togglePlayerKnockback(PlatformPlayer target, Sender sender) {
|
||||
User user = target.getUser();
|
||||
if (user == null) {
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerDisconnectedWhileExecutingCommand()
|
||||
).replace("%player%", target.getName());
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
if (PlayerDataManager.shouldExempt(target.getUUID())) {
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerIneligibleMessage()
|
||||
).replace("%player%", target.getName());
|
||||
|
||||
sender.sendMessage(message);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean hasPlayerData = PlayerDataManager.containsPlayerData(user);
|
||||
if (hasPlayerData) {
|
||||
if (CombatManager.getPlayers().contains(user)) {
|
||||
CombatManager.removePlayer(user);
|
||||
}
|
||||
PlayerDataManager.removePlayerData(user);
|
||||
} else {
|
||||
PlayerDataManager.addPlayerData(user, target);
|
||||
}
|
||||
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
hasPlayerData ? configManager.getPlayerDisableMessage() : configManager.
|
||||
getPlayerEnableMessage()
|
||||
).replace("%player%", target.getName());
|
||||
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package me.caseload.knockbacksync.command.subcommand;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.incendo.cloud.permission.PredicatePermission;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class ToggleOffGroundSubcommand implements BuilderCommand {
|
||||
|
||||
public static boolean offGroundSyncEnabled = true;
|
||||
private String offGroundSyncEnableMessage;
|
||||
private String offGroundSyncDisableMessage;
|
||||
|
||||
public ToggleOffGroundSubcommand() {
|
||||
loadConfigSettings();
|
||||
}
|
||||
|
||||
public void register(CommandManager<Sender> manager) {
|
||||
manager.command(
|
||||
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
|
||||
.literal("toggleoffground")
|
||||
.permission((sender -> {
|
||||
final String permission = "knockbacksync.toggleoffground";
|
||||
Predicate<Sender> senderPredicate = (s) -> {
|
||||
return s.hasPermission(permission, false);
|
||||
};
|
||||
|
||||
return PredicatePermission.of(senderPredicate).testPermission(sender);
|
||||
}))
|
||||
.handler(commandContext -> {
|
||||
offGroundSyncEnabled = !offGroundSyncEnabled;
|
||||
Base.INSTANCE.getConfigManager().getConfigWrapper().set("enable_offground_synchronization", offGroundSyncEnabled);
|
||||
Base.INSTANCE.getConfigManager().saveConfig();
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
offGroundSyncEnabled ? offGroundSyncEnableMessage : offGroundSyncDisableMessage);
|
||||
commandContext.sender().sendMessage(message);
|
||||
}));
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onConfigReloadEvent(ConfigReloadEvent event) {
|
||||
loadConfigSettings();
|
||||
}
|
||||
|
||||
private void loadConfigSettings() {
|
||||
ConfigWrapper configWrapper = Base.INSTANCE.getConfigManager().getConfigWrapper();
|
||||
offGroundSyncEnabled = configWrapper.getBoolean("enable_offground_synchronization", true);
|
||||
this.offGroundSyncEnableMessage = configWrapper.getString("messages.offground.enable",
|
||||
"&aSuccessfully enabled offground synchronization.");
|
||||
this.offGroundSyncDisableMessage = configWrapper.getString("messages.offground.disable",
|
||||
"&cSuccessfully disabled offground synchronization.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package me.caseload.knockbacksync.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.yaml.snakeyaml.DumperOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
|
||||
public class YamlConfiguration {
|
||||
private final File file;
|
||||
private final Yaml yaml;
|
||||
@Getter
|
||||
@Setter
|
||||
private Map<String, Object> data;
|
||||
private String fileContents;
|
||||
|
||||
public YamlConfiguration(File file) {
|
||||
this.file = file;
|
||||
DumperOptions options = new DumperOptions();
|
||||
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
options.setPrettyFlow(true);
|
||||
options.setWidth(Integer.MAX_VALUE);
|
||||
this.yaml = new Yaml(options);
|
||||
}
|
||||
|
||||
public void load() throws IOException {
|
||||
if (!file.exists()) {
|
||||
data = new LinkedHashMap<>();
|
||||
return;
|
||||
}
|
||||
|
||||
fileContents = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
|
||||
data = yaml.load(fileContents);
|
||||
if (data == null) {
|
||||
data = new LinkedHashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
public void save() throws IOException {
|
||||
if (!file.exists()) {
|
||||
file.getParentFile().mkdirs();
|
||||
file.createNewFile();
|
||||
}
|
||||
|
||||
String dump = yaml.dump(data);
|
||||
|
||||
if (fileContents != null) {
|
||||
Map<String, YamlElement> oldElements = parseYaml(fileContents);
|
||||
Map<String, YamlElement> newElements = parseYaml(dump);
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
buildOutput(oldElements, newElements, result);
|
||||
dump = result.toString();
|
||||
}
|
||||
|
||||
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8)) {
|
||||
writer.write(dump);
|
||||
}
|
||||
}
|
||||
|
||||
private static class YamlElement {
|
||||
String key;
|
||||
String value;
|
||||
int indent;
|
||||
boolean isComment;
|
||||
List<YamlElement> children = new ArrayList<>();
|
||||
|
||||
YamlElement(String line, int indent) {
|
||||
this.indent = indent;
|
||||
if (line.trim().startsWith("#")) {
|
||||
this.isComment = true;
|
||||
this.value = line;
|
||||
} else {
|
||||
this.isComment = false;
|
||||
String[] parts = line.split(":", 2);
|
||||
this.key = parts[0].trim();
|
||||
this.value = parts.length > 1 ? parts[1].trim() : "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, YamlElement> parseYaml(String content) {
|
||||
Map<String, YamlElement> elements = new LinkedHashMap<>();
|
||||
Stack<YamlElement> stack = new Stack<>();
|
||||
String[] lines = content.split("\n");
|
||||
|
||||
for (String line : lines) {
|
||||
if (line.trim().isEmpty()) continue;
|
||||
|
||||
int indent = getIndentation(line);
|
||||
YamlElement element = new YamlElement(line, indent);
|
||||
|
||||
while (!stack.isEmpty() && stack.peek().indent >= indent) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
if (stack.isEmpty()) {
|
||||
if (!element.isComment) {
|
||||
elements.put(element.key, element);
|
||||
} else {
|
||||
elements.put("comment" + elements.size(), element);
|
||||
}
|
||||
} else {
|
||||
stack.peek().children.add(element);
|
||||
}
|
||||
|
||||
if (!element.isComment && element.value.isEmpty()) {
|
||||
stack.push(element);
|
||||
}
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
private void buildOutput(Map<String, YamlElement> oldElements, Map<String, YamlElement> newElements, StringBuilder result) {
|
||||
for (YamlElement element : oldElements.values()) {
|
||||
if (element.isComment) {
|
||||
result.append(element.value).append("\n");
|
||||
} else {
|
||||
YamlElement newElement = newElements.get(element.key);
|
||||
if (newElement != null) {
|
||||
String indent = createIndent(element.indent);
|
||||
result.append(indent).append(element.key).append(":");
|
||||
|
||||
if (!newElement.value.isEmpty()) {
|
||||
result.append(" ").append(newElement.value);
|
||||
}
|
||||
result.append("\n");
|
||||
|
||||
if (!element.children.isEmpty()) {
|
||||
Map<String, YamlElement> oldChildren = new LinkedHashMap<>();
|
||||
Map<String, YamlElement> newChildren = new LinkedHashMap<>();
|
||||
|
||||
for (YamlElement child : element.children) {
|
||||
if (!child.isComment) {
|
||||
oldChildren.put(child.key, child);
|
||||
} else {
|
||||
oldChildren.put("comment" + oldChildren.size(), child);
|
||||
}
|
||||
}
|
||||
|
||||
for (YamlElement child : newElement.children) {
|
||||
if (!child.isComment) {
|
||||
newChildren.put(child.key, child);
|
||||
}
|
||||
}
|
||||
|
||||
buildOutput(oldChildren, newChildren, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int getIndentation(String line) {
|
||||
int indent = 0;
|
||||
while (indent < line.length() && line.charAt(indent) == ' ') {
|
||||
indent++;
|
||||
}
|
||||
return indent;
|
||||
}
|
||||
|
||||
private String createIndent(int count) {
|
||||
StringBuilder sb = new StringBuilder(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
sb.append(' ');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package me.caseload.knockbacksync.event;
|
||||
|
||||
import lombok.Setter;
|
||||
import me.caseload.knockbacksync.event.OptimizedEventBus;
|
||||
|
||||
public abstract class Event {
|
||||
@Setter
|
||||
private static EventBus eventBus;
|
||||
@Setter
|
||||
private boolean cancelled = false;
|
||||
|
||||
public void post() {
|
||||
if (eventBus != null) {
|
||||
eventBus.post(this);
|
||||
} else {
|
||||
throw new IllegalStateException("EventBus has not been set");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package me.caseload.knockbacksync.event;
|
||||
|
||||
public interface EventBus {
|
||||
void registerListeners(Object listener);
|
||||
|
||||
void registerStaticListeners(Class<?> clazz);
|
||||
|
||||
void unregisterListeners(Object listener);
|
||||
|
||||
void unregisterStaticListeners(Class<?> clazz);
|
||||
|
||||
void post(Event event);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package me.caseload.knockbacksync.event;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface KBSyncEventHandler {
|
||||
int priority() default 0;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package me.caseload.knockbacksync.event;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
public class OptimizedEventBus implements EventBus {
|
||||
// ordinarily this would just be a hashmap since we don't modify it on different threads, but Folia forces us to make it concurrent
|
||||
private final Map<Class<? extends Event>, List<OptimizedListener>> listenerMap = new ConcurrentHashMap<>();
|
||||
private final MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
@Override
|
||||
public void registerListeners(Object listener) {
|
||||
registerMethods(listener, listener.getClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStaticListeners(Class<?> clazz) {
|
||||
registerMethods(null, clazz);
|
||||
}
|
||||
|
||||
private void registerMethods(Object instance, Class<?> clazz) {
|
||||
for (Method method : clazz.getDeclaredMethods()) {
|
||||
KBSyncEventHandler annotation = method.getAnnotation(KBSyncEventHandler.class);
|
||||
if (annotation != null && method.getParameterCount() == 1) {
|
||||
Class<?> eventType = method.getParameterTypes()[0];
|
||||
if (Event.class.isAssignableFrom(eventType)) {
|
||||
try {
|
||||
// Skip instance methods when registering static listeners
|
||||
if (instance == null && !Modifier.isStatic(method.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
MethodHandle handle = lookup.unreflect(method);
|
||||
OptimizedListener optimizedListener = new OptimizedListener(instance, handle, annotation.priority(), method.getDeclaringClass());
|
||||
// Yes the CopyOnWriteArrayList is slow, yes we need to for thread safety on Folia, we'll replace when performance problems actually crop up
|
||||
listenerMap.computeIfAbsent((Class<? extends Event>) eventType, k -> new CopyOnWriteArrayList<>()).add(optimizedListener);
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sort listeners by priority
|
||||
listenerMap.values().forEach(list -> list.sort((a, b) -> Integer.compare(b.priority, a.priority)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterListeners(Object listener) {
|
||||
listenerMap.values().forEach(list -> list.removeIf(l -> l.instance == listener));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterStaticListeners(Class<?> clazz) {
|
||||
listenerMap.values().forEach(list -> list.removeIf(l -> l.instance == null && l.declaringClass == clazz));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void post(Event event) {
|
||||
List<OptimizedListener> listeners = listenerMap.get(event.getClass());
|
||||
if (listeners != null) {
|
||||
for (OptimizedListener listener : listeners) {
|
||||
try {
|
||||
if (listener.instance != null) {
|
||||
// Instance method
|
||||
listener.handle.invoke(listener.instance, event);
|
||||
} else {
|
||||
// Static method
|
||||
listener.handle.invoke(event);
|
||||
}
|
||||
if (event.isCancelled()) {
|
||||
break;
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class OptimizedListener {
|
||||
final Object instance; // null for static methods
|
||||
final MethodHandle handle;
|
||||
final int priority;
|
||||
final Class<?> declaringClass;
|
||||
|
||||
OptimizedListener(Object instance, MethodHandle handle, int priority, Class<?> declaringClass) {
|
||||
this.instance = instance;
|
||||
this.handle = handle;
|
||||
this.priority = priority;
|
||||
this.declaringClass = declaringClass;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package me.caseload.knockbacksync.event.events;
|
||||
|
||||
import lombok.Getter;
|
||||
import me.caseload.knockbacksync.event.Event;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
|
||||
@Getter
|
||||
public class ConfigReloadEvent extends Event {
|
||||
private final ConfigManager configManager;
|
||||
|
||||
public ConfigReloadEvent(ConfigManager configManager) {
|
||||
this.configManager = configManager;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package me.caseload.knockbacksync.event.events;
|
||||
|
||||
import me.caseload.knockbacksync.event.Event;
|
||||
|
||||
public class ToggleOnOffEvent extends Event {
|
||||
|
||||
private boolean newEnabledState;
|
||||
|
||||
public ToggleOnOffEvent(boolean newEnabledState) {
|
||||
this.newEnabledState = newEnabledState;
|
||||
}
|
||||
|
||||
public boolean getStatus() {
|
||||
return newEnabledState;
|
||||
}
|
||||
|
||||
public void setStatus(boolean newEnabledState) {
|
||||
this.newEnabledState = newEnabledState;
|
||||
}
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
super.setCancelled(cancelled);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,47 @@
|
||||
package me.caseload.knockbacksync.listener;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.LegacyKnockback;
|
||||
|
||||
public abstract class PlayerDamageListener {
|
||||
public void onPlayerDamage(PlatformPlayer victim, PlatformPlayer attacker) {
|
||||
if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled())
|
||||
ConfigManager config = Base.INSTANCE.getConfigManager();
|
||||
if (!config.isToggled())
|
||||
return;
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(victim.getUUID());
|
||||
User user = victim.getUser();
|
||||
if (user == null) return; // Prevent errors with players disconnecting while this is running (or with fake player?)
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData == null)
|
||||
return;
|
||||
|
||||
playerData.setVerticalVelocity(playerData.calculateVerticalVelocity(attacker)); // do not move this calculation
|
||||
if (config.isLegacyKnockbackEnabled()) {
|
||||
if (playerData.isRodKnockbackPending()) {
|
||||
// A fishing-rod (bobber-direction) knockback was already supplied for this hit via
|
||||
// the rod API. Keep it instead of overwriting with the melee formula; the velocity
|
||||
// event still owns + latency-syncs it. Its vertical was set by the API call.
|
||||
} else {
|
||||
// KnockbackSync owns the full 1.8 melee velocity. Compute it now (we have the
|
||||
// attacker here) and store it for the PlayerVelocityEvent to apply + sync.
|
||||
Vector3d legacy = LegacyKnockback.compute(victim, attacker, playerData, config);
|
||||
playerData.setLegacyKnockback(legacy);
|
||||
// On-ground sync should target the legacy vertical value, not the 1.9 one.
|
||||
playerData.setVerticalVelocity(legacy.getY());
|
||||
}
|
||||
} else {
|
||||
playerData.setVerticalVelocity(playerData.calculateVerticalVelocity(attacker)); // do not move this calculation
|
||||
}
|
||||
playerData.setLastDamageTicks(victim.getNoDamageTicks());
|
||||
playerData.updateCombat();
|
||||
|
||||
if (!KnockbackSyncBase.INSTANCE.getConfigManager().isRunnableEnabled())
|
||||
playerData.sendPing(false);
|
||||
if (!Base.INSTANCE.getConfigManager().isRunnableEnabled())
|
||||
playerData.sendPing(true);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package me.caseload.knockbacksync.listener;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class PlayerJoinQuitListener {
|
||||
public void onPlayerJoin(PlayerData player) {
|
||||
PlayerDataManager.addPlayerData(player.getUuid(), player);
|
||||
PlatformPlayer platformPlayer = player.getPlatformPlayer();
|
||||
|
||||
if (KnockbackSyncBase.INSTANCE.getConfigManager().isUpdateAvailable() && KnockbackSyncBase.INSTANCE.getConfigManager().isNotifyUpdate() && KnockbackSyncBase.INSTANCE.getPermissionChecker().hasPermission(platformPlayer, "knockbacksync.update"))
|
||||
platformPlayer.sendMessage(ChatUtil.translateAlternateColorCodes(
|
||||
'&',
|
||||
"&6An updated version of &eKnockbackSync &6is now available for download at: &bhttps://github.com/CASELOAD7000/knockback-sync/releases/latest"
|
||||
));
|
||||
}
|
||||
|
||||
public void onPlayerQuit(UUID uuid) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
if (playerData == null)
|
||||
return;
|
||||
|
||||
if (playerData.isInCombat())
|
||||
playerData.quitCombat(true);
|
||||
|
||||
PlayerDataManager.removePlayerData(uuid);
|
||||
}
|
||||
}
|
||||
+68
-18
@@ -1,32 +1,82 @@
|
||||
package me.caseload.knockbacksync.listener;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public abstract class PlayerKnockbackListener {
|
||||
|
||||
public void onPlayerVelocity(PlatformPlayer victim, Vector3d velocity) {
|
||||
if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled())
|
||||
return;
|
||||
/**
|
||||
* Computes the melee velocity to apply to the victim.
|
||||
*
|
||||
* <p>The returned value, when non-null, MUST be written back by the platform layer.
|
||||
* Bukkit writes it to the {@code PlayerVelocityEvent} (so KnockbackSync is the last,
|
||||
* authoritative writer in the event chain rather than reading/writing the player's
|
||||
* live velocity out-of-band — see issue #7).</p>
|
||||
*
|
||||
* <p>When legacy (1.8) knockback is enabled, the 1.8 vector computed at damage time
|
||||
* replaces vanilla X/Z/Y, and latency Y-correction is applied on top of it. In that
|
||||
* mode this method always returns a velocity (the raw 1.8 vector when no correction
|
||||
* applies), so KnockbackSync owns the final melee velocity.</p>
|
||||
*
|
||||
* @return the velocity to apply, or {@code null} to leave the velocity unchanged.
|
||||
*/
|
||||
@Nullable
|
||||
public Vector3d onPlayerVelocity(PlatformPlayer victim, Vector3d velocity) {
|
||||
ConfigManager config = Base.INSTANCE.getConfigManager();
|
||||
if (!config.isToggled())
|
||||
return null;
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(victim.getUUID());
|
||||
if (playerData == null)
|
||||
return;
|
||||
User user = victim.getUser();
|
||||
if (user == null) return null; // Prevent errors with players disconnecting while this is running (or with fake player?)
|
||||
|
||||
Integer damageTicks = playerData.getLastDamageTicks();
|
||||
if (damageTicks != null && damageTicks > 8)
|
||||
return;
|
||||
PlayerData victimPlayerData = PlayerDataManager.getPlayerData(user);
|
||||
if (victimPlayerData == null)
|
||||
return null;
|
||||
|
||||
Double verticalVelocity = playerData.getVerticalVelocity();
|
||||
if (verticalVelocity == null || !playerData.isOnGround(velocity.getY()))
|
||||
return;
|
||||
// Legacy 1.8 knockback: KnockbackSync owns the melee velocity. The 1.8 vector
|
||||
// (computed at damage time) replaces vanilla X/Z/Y. We still apply latency
|
||||
// Y-correction on top when conditions allow; otherwise the raw 1.8 vector is
|
||||
// applied. legacyKb == null means either legacy is off or none is pending, in
|
||||
// which case behaviour falls back to the original (Y-sync of the event velocity).
|
||||
Vector3d legacyKb = config.isLegacyKnockbackEnabled() ? victimPlayerData.consumeLegacyKnockback() : null;
|
||||
Vector3d base = (legacyKb != null) ? legacyKb : velocity;
|
||||
|
||||
// Since we're already changing types do we need to use withY to get a new object
|
||||
// Or can we just go velcoity.y = verticalVelocity ?
|
||||
Vector3d adjustedVelocity = velocity.withY(verticalVelocity);
|
||||
victim.setVelocity(adjustedVelocity); // Use PlatformPlayer's setVelocity
|
||||
if (victimPlayerData.getNotNullPing() < PlayerData.PING_OFFSET)
|
||||
return legacyKb;
|
||||
|
||||
double distanceToGround = victimPlayerData.getDistanceToGround();
|
||||
if (distanceToGround <= 0)
|
||||
return legacyKb; // minecraft already does the work for us
|
||||
|
||||
WrappedBlockState blockState = victim.getWorld().getBlockStateAt(victim.getLocation());
|
||||
if (victim.isGliding() ||
|
||||
blockState.getType() == StateTypes.WATER ||
|
||||
blockState.getType() == StateTypes.LAVA ||
|
||||
blockState.getType() == StateTypes.COBWEB ||
|
||||
blockState.getType() == StateTypes.SCAFFOLDING)
|
||||
return legacyKb;
|
||||
|
||||
Vector3d adjustedVelocity;
|
||||
if (victimPlayerData.isOnGroundClientSide(base.getY(), distanceToGround)) {
|
||||
Integer damageTicks = victimPlayerData.getLastDamageTicks();
|
||||
if (damageTicks != null && damageTicks > 8)
|
||||
return legacyKb;
|
||||
|
||||
adjustedVelocity = base.withY(victimPlayerData.getVerticalVelocity()); // Should be impossible to produce a NPE in this context
|
||||
}
|
||||
else if (victimPlayerData.isOffGroundSyncEnabled())
|
||||
adjustedVelocity = base.withY(victimPlayerData.getCompensatedOffGroundVelocity());
|
||||
else
|
||||
return legacyKb;
|
||||
|
||||
return adjustedVelocity;
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-12
@@ -5,7 +5,9 @@ import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.attribute.Attributes;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.MathUtil;
|
||||
@@ -18,9 +20,9 @@ public class AttributeChangeListener extends PacketListenerAbstract {
|
||||
public static final UUID SPRINTING_MODIFIER_UUID =
|
||||
UUID.fromString("662A6B8D-DA3E-4C1C-8813-96EA6097278D");
|
||||
|
||||
double minGravity = -1;
|
||||
double maxGravity = 1;
|
||||
double defaultGravity = 0.08;
|
||||
final double minGravity = -1;
|
||||
final double maxGravity = 1;
|
||||
final double defaultGravity = 0.08;
|
||||
double currentGravity;
|
||||
|
||||
public AttributeChangeListener() {
|
||||
@@ -29,21 +31,22 @@ public class AttributeChangeListener extends PacketListenerAbstract {
|
||||
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled()) return;
|
||||
|
||||
if (event.getPacketType() == PacketType.Play.Server.UPDATE_ATTRIBUTES) {
|
||||
|
||||
WrapperPlayServerUpdateAttributes packet = new WrapperPlayServerUpdateAttributes(event);
|
||||
|
||||
UUID uuid = event.getUser().getUUID();
|
||||
if (!PlayerDataManager.containsPlayerData(uuid))
|
||||
return;
|
||||
User user = event.getUser();
|
||||
if (!PlayerDataManager.containsPlayerData(user)) return;
|
||||
|
||||
// Get the attributes from the packet
|
||||
for (WrapperPlayServerUpdateAttributes.Property property : packet.getProperties()) {
|
||||
// You can now check for specific attributes
|
||||
if (property.getAttribute().equals(Attributes.GENERIC_GRAVITY)) {
|
||||
onPlayerGravityChange(uuid, calculateValueWithModifiers(property));
|
||||
onPlayerGravityChange(user, calculateValueWithModifiers(property));
|
||||
} else if (property.getAttribute().equals(Attributes.GENERIC_KNOCKBACK_RESISTANCE)) {
|
||||
onPlayerKnockBackChange(uuid, calculateValueWithModifiers(property));
|
||||
onPlayerKnockBackChange(user, calculateValueWithModifiers(property));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,8 +87,8 @@ public class AttributeChangeListener extends PacketListenerAbstract {
|
||||
|
||||
// Yes this is not properly latency compensated, that would require including a proper simulation engine
|
||||
// Laggy players will just have to deal with being on the wrong gravity for a few hundred ms, too bad!
|
||||
public void onPlayerGravityChange(UUID uuid, double newGravity) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
public void onPlayerGravityChange(User user, double newGravity) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_20_5)) {
|
||||
playerData.setGravityAttribute(newGravity);
|
||||
} else {
|
||||
@@ -93,8 +96,8 @@ public class AttributeChangeListener extends PacketListenerAbstract {
|
||||
}
|
||||
}
|
||||
|
||||
private void onPlayerKnockBackChange(UUID uuid, double newKnockbackResistance) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
private void onPlayerKnockBackChange(User user, double newKnockbackResistance) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
playerData.setKnockbackResistanceAttribute(newKnockbackResistance);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package me.caseload.knockbacksync.listener.packetevents;
|
||||
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPluginMessage;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
|
||||
public class ClientBrandListener extends PacketListenerAbstract {
|
||||
String brand = "vanilla";
|
||||
boolean hasBrand = false;
|
||||
|
||||
@Override
|
||||
public void onPacketReceive(final PacketReceiveEvent event) {
|
||||
if (event.getPacketType() == PacketType.Play.Client.PLUGIN_MESSAGE) {
|
||||
WrapperPlayClientPluginMessage packet = new WrapperPlayClientPluginMessage(event);
|
||||
String channelName = packet.getChannelName();
|
||||
handle(channelName, packet.getData());
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser());
|
||||
if (playerData == null) return;
|
||||
playerData.getPlatformPlayer().setClientBrand(brand);
|
||||
}
|
||||
}
|
||||
|
||||
public void handle(String channel, byte[] data) {
|
||||
if (channel.equalsIgnoreCase("minecraft:brand") || // 1.13+
|
||||
channel.equals("MC|Brand")) { // 1.12
|
||||
if (data.length > 64 || data.length == 0) {
|
||||
brand = "sent " + data.length + " bytes as brand";
|
||||
} else if (!hasBrand) {
|
||||
byte[] minusLength = new byte[data.length - 1];
|
||||
System.arraycopy(data, 1, minusLength, 0, minusLength.length);
|
||||
brand = new String(minusLength).replace(" (Velocity)", ""); //removes velocity's brand suffix
|
||||
}
|
||||
hasBrand = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package me.caseload.knockbacksync.listener.packetevents;
|
||||
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.UserDisconnectEvent;
|
||||
import com.github.retrooper.packetevents.event.UserLoginEvent;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.google.common.base.Preconditions;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PacketPlayerJoinQuit extends PacketListenerAbstract {
|
||||
@Override
|
||||
public void onUserLogin(UserLoginEvent event) {
|
||||
Object nativePlayerObject = event.getPlayer();
|
||||
Preconditions.checkArgument(nativePlayerObject != null);
|
||||
|
||||
@NotNull PlatformPlayer platformPlayer = Base.INSTANCE.getPlatformServer().getPlayer(nativePlayerObject);
|
||||
onPlayerJoin(event.getUser(), platformPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUserDisconnect(UserDisconnectEvent event) {
|
||||
onPlayerQuit(event.getUser());
|
||||
}
|
||||
|
||||
public void onPlayerJoin(User user, PlatformPlayer player) {
|
||||
PlayerDataManager.addPlayerData(user, player);
|
||||
|
||||
if (Base.INSTANCE.getConfigManager().isUpdateAvailable() && Base.INSTANCE.getConfigManager().isNotifyUpdate() && Base.INSTANCE.getPermissionChecker().hasPermission(player, "knockbacksync.update"))
|
||||
player.sendMessage(ChatUtil.translateAlternateColorCodes(
|
||||
'&',
|
||||
"&6An updated version of &eKnockbackSync &6is now available for download at: &bhttps://github.com/CASELOAD7000/knockback-sync/releases/latest"
|
||||
));
|
||||
}
|
||||
|
||||
public void onPlayerQuit(@NotNull User user) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData == null)
|
||||
return;
|
||||
|
||||
playerData.quitCombat(true);
|
||||
PlayerDataManager.removePlayerData(user);
|
||||
}
|
||||
}
|
||||
+77
-23
@@ -1,35 +1,90 @@
|
||||
package me.caseload.knockbacksync.listener.packetevents;
|
||||
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.event.*;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientKeepAlive;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientWindowConfirmation;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PingStrategy;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.data.Pair;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.UUID;
|
||||
|
||||
public class PingReceiveListener extends PacketListenerAbstract {
|
||||
// TODO supplment our own ping calculations with over keepalive sent by the server with
|
||||
// @Override
|
||||
// public void onPacketSend(PacketSendEvent event) {
|
||||
// if (event.getPacketType() == PacketType.Play.Server.KEEP_ALIVE) {
|
||||
// }
|
||||
// }
|
||||
|
||||
public PingReceiveListener() {
|
||||
super(PacketListenerPriority.LOWEST);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketReceive(PacketReceiveEvent event) {
|
||||
if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled()) return;
|
||||
if (event.getPacketType() != PacketType.Play.Client.KEEP_ALIVE) return;
|
||||
|
||||
WrapperPlayClientKeepAlive keepAlive = new WrapperPlayClientKeepAlive(event);
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
|
||||
// Do not immediately return if KB sync is disabled. This is because if we send a packet, disable the plugin
|
||||
// And then receive a response we have to ensure that if the packet was sent by us we cancel it
|
||||
// otherwise the server will likely kick the player
|
||||
PacketTypeCommon packetType = event.getPacketType();
|
||||
User user = event.getUser();
|
||||
if (user == null) return;
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData == null) return;
|
||||
|
||||
long receivedId = keepAlive.getId();
|
||||
// Cancel echoes of injected packets before any strategy check: on 1.20.2+ an unexpected keepalive is an instant "Timed out" kick, so a strategy switch mid-flight must not leak one.
|
||||
if (packetType == PacketType.Play.Client.KEEP_ALIVE) {
|
||||
WrapperPlayClientKeepAlive keepAlive = new WrapperPlayClientKeepAlive(event);
|
||||
long receivedId = keepAlive.getId();
|
||||
|
||||
if (playerData.isKeepAliveIDOurs(receivedId)) {
|
||||
long pingNanos = (System.nanoTime() - receivedId);
|
||||
// Calculate the remainder nanoseconds for fractional milliseconds
|
||||
if (playerData.didWeSendThatPacket(receivedId))
|
||||
event.setCancelled(true);
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.KEEPALIVE)
|
||||
handlePingCalculationPackets(playerData, receivedId, playerData.keepaliveMap);
|
||||
} else if (packetType == PacketType.Play.Client.PONG) {
|
||||
WrapperPlayClientPong pong = new WrapperPlayClientPong(event);
|
||||
int id = pong.getId();
|
||||
|
||||
if (playerData.didWeSendThatPacket(id))
|
||||
event.setCancelled(true);
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.TRANSACTION)
|
||||
handlePingCalculationPackets(playerData, id, playerData.transactionsSent);
|
||||
} else if (packetType == PacketType.Play.Client.WINDOW_CONFIRMATION) {
|
||||
WrapperPlayClientWindowConfirmation windowConfirmation = new WrapperPlayClientWindowConfirmation(event);
|
||||
int id = windowConfirmation.getActionId();
|
||||
|
||||
if (playerData.didWeSendThatPacket(id))
|
||||
event.setCancelled(true);
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.TRANSACTION)
|
||||
handlePingCalculationPackets(playerData, id, playerData.transactionsSent);
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Number> void handlePingCalculationPackets(PlayerData playerData, long id, Queue<Pair<T, Long>> packetSentList) {
|
||||
// System.out.println("Received response ID: " + id + " Queue size before: " + packetSentList.size());
|
||||
// System.out.println("Current queue contents: " + packetSentList.toString());
|
||||
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled()) return;
|
||||
|
||||
Pair<T, Long> data = null;
|
||||
int cleared = 0;
|
||||
// Keep polling until we find the matching ID
|
||||
do {
|
||||
data = packetSentList.poll();
|
||||
cleared++;
|
||||
|
||||
if (data == null) {
|
||||
// System.out.println("No data found in queue!");
|
||||
break;
|
||||
}
|
||||
|
||||
// System.out.println("Cleared entry " + cleared + ": ID=" + data.getFirst() + " Time=" + data.getSecond());
|
||||
|
||||
long pingNanos = (System.nanoTime() - data.getSecond());
|
||||
double diffMillisDouble = pingNanos / 1_000_000.0;
|
||||
|
||||
playerData.setPreviousPing(playerData.getPing());
|
||||
@@ -38,10 +93,9 @@ public class PingReceiveListener extends PacketListenerAbstract {
|
||||
playerData.getJitterCalculator().addPing(pingNanos);
|
||||
double jitter = playerData.getJitterCalculator().calculateJitter();
|
||||
playerData.setJitter(jitter);
|
||||
// Minecraft kicks players that send invalid keepAliveID packets
|
||||
// Since Minecraft doesn't know we just sent a keepalive, we gotta cancel it
|
||||
// To stop MC from processing it and kicking the player
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
} while (data.getFirst().longValue() != id);
|
||||
|
||||
// System.out.println("Finished processing - Cleared " + cleared + " entries. Queue size after: " + packetSentList.size());
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package me.caseload.knockbacksync.listener.packetevents;
|
||||
|
||||
import com.github.retrooper.packetevents.event.*;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientWindowConfirmation;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowConfirmation;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PingStrategy;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.data.Pair;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.UUID;
|
||||
|
||||
public class PingSendListener extends PacketListenerAbstract {
|
||||
|
||||
public PingSendListener() {
|
||||
// See all actually outgoing, not cancelled, ping packets
|
||||
super(PacketListenerPriority.MONITOR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled()) return;
|
||||
if (event.isCancelled()) return;
|
||||
|
||||
PacketTypeCommon packetType = event.getPacketType();
|
||||
UUID playerUUID = event.getUser().getUUID();
|
||||
if (playerUUID == null) return;
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser());
|
||||
if (playerData == null) return;
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.KEEPALIVE && packetType.equals(PacketType.Play.Server.KEEP_ALIVE)) {
|
||||
WrapperPlayServerKeepAlive keepAlive = new WrapperPlayServerKeepAlive(event);
|
||||
long id = keepAlive.getId();
|
||||
|
||||
// System.out.println("Adding ping to queue - ID: " + id + " Time: " + System.nanoTime() + " Queue size before: " + playerData.keepaliveMap.size());
|
||||
playerData.keepaliveMap.add(new Pair<>(id, System.nanoTime()));
|
||||
} else if (playerData.pingStrategy == PingStrategy.TRANSACTION && packetType.equals(PacketType.Play.Server.PING)) {
|
||||
WrapperPlayServerPing ping = new WrapperPlayServerPing(event);
|
||||
int id = ping.getId();
|
||||
|
||||
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
|
||||
} else if (playerData.pingStrategy == PingStrategy.TRANSACTION && packetType.equals(PacketType.Play.Server.WINDOW_CONFIRMATION)) {
|
||||
WrapperPlayServerWindowConfirmation confirmation = new WrapperPlayServerWindowConfirmation(event);
|
||||
int id = confirmation.getActionId();
|
||||
|
||||
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.caseload.knockbacksync.manager;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Set;
|
||||
@@ -8,17 +9,17 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class CombatManager {
|
||||
|
||||
private static final Set<UUID> combatPlayers = ConcurrentHashMap.newKeySet();
|
||||
private static final Set<@NotNull User> combatPlayers = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public static @NotNull Set<UUID> getPlayers() {
|
||||
public static @NotNull Set<@NotNull User> getPlayers() {
|
||||
return combatPlayers;
|
||||
}
|
||||
|
||||
public static void addPlayer(UUID uuid) {
|
||||
combatPlayers.add(uuid);
|
||||
public static void addPlayer(@NotNull User user) {
|
||||
combatPlayers.add(user);
|
||||
}
|
||||
|
||||
public static void removePlayer(UUID uuid) {
|
||||
combatPlayers.remove(uuid);
|
||||
public static void removePlayer(@NotNull User user) {
|
||||
combatPlayers.remove(user);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,17 @@
|
||||
package me.caseload.knockbacksync.manager;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.Platform;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.config.YamlConfiguration;
|
||||
import me.caseload.knockbacksync.runnable.PingRunnable;
|
||||
import me.caseload.knockbacksync.scheduler.AbstractTaskHandle;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -20,10 +19,23 @@ import java.util.Map;
|
||||
@Setter
|
||||
public class ConfigManager {
|
||||
|
||||
public static final long CONFIG_VERSION = 9;
|
||||
|
||||
private boolean toggled;
|
||||
private boolean runnableEnabled;
|
||||
private boolean updateAvailable;
|
||||
private boolean notifyUpdate;
|
||||
private boolean autoUpdate;
|
||||
|
||||
// Legacy (1.8) knockback: makes KnockbackSync the single owner of melee velocity,
|
||||
// reproducing OldCombatMechanics' old-player-knockback values while still latency-syncing.
|
||||
private boolean legacyKnockbackEnabled;
|
||||
private double legacyKnockbackHorizontal;
|
||||
private double legacyKnockbackVertical;
|
||||
private double legacyKnockbackVerticalLimit;
|
||||
private double legacyKnockbackExtraHorizontal;
|
||||
private double legacyKnockbackExtraVertical;
|
||||
private boolean legacyKnockbackResistanceEnabled;
|
||||
|
||||
private long runnableInterval;
|
||||
private long combatTimer;
|
||||
@@ -34,19 +46,19 @@ public class ConfigManager {
|
||||
private String playerEnableMessage;
|
||||
private String playerDisableMessage;
|
||||
private String playerIneligibleMessage;
|
||||
private String reloadMessage;
|
||||
private String playerDisconnectedWhileExecutingCommand;
|
||||
|
||||
private AbstractTaskHandle pingTask;
|
||||
|
||||
private Map<String, Object> config;
|
||||
private File configFile;
|
||||
private ObjectMapper mapper;
|
||||
private ConfigWrapper configWrapper; // Cache the ConfigWrapper instance
|
||||
private YamlConfiguration yamlConfig;
|
||||
|
||||
public ConfigManager() {
|
||||
mapper = new ObjectMapper(new YAMLFactory());
|
||||
KnockbackSyncBase instance = KnockbackSyncBase.INSTANCE;
|
||||
Base instance = Base.INSTANCE;
|
||||
configFile = new File(instance.getDataFolder(), "config.yml");
|
||||
yamlConfig = new YamlConfiguration(configFile);
|
||||
}
|
||||
|
||||
public ConfigWrapper getConfigWrapper() {
|
||||
@@ -59,9 +71,10 @@ public class ConfigManager {
|
||||
public void reloadConfig() {
|
||||
try {
|
||||
if (!configFile.exists()) {
|
||||
KnockbackSyncBase.INSTANCE.saveDefaultConfig();
|
||||
Base.INSTANCE.saveDefaultConfig();
|
||||
}
|
||||
config = mapper.readValue(configFile, Map.class);
|
||||
yamlConfig.load();
|
||||
config = yamlConfig.getData();
|
||||
configWrapper = new ConfigWrapper(config);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
@@ -72,7 +85,8 @@ public class ConfigManager {
|
||||
|
||||
public void saveConfig() {
|
||||
try {
|
||||
mapper.writeValue(configFile, config);
|
||||
yamlConfig.setData(config);
|
||||
yamlConfig.save();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@@ -83,40 +97,103 @@ public class ConfigManager {
|
||||
reloadConfig();
|
||||
}
|
||||
|
||||
ConfigWrapper config = getConfigWrapper(); // Use cached ConfigWrapper
|
||||
ConfigWrapper configWrapper = getConfigWrapper(); // Use cached ConfigWrapper
|
||||
|
||||
toggled = config.getBoolean("enabled", true);
|
||||
updateConfig();
|
||||
|
||||
// Checks to see if the runnable was enabled...
|
||||
// and if we now want to disable it
|
||||
boolean newRunnableEnabled = config.getBoolean("runnable.enabled", true);
|
||||
if (runnableEnabled && newRunnableEnabled && pingTask != null) { // null check for first startup
|
||||
toggled = configWrapper.getBoolean("enabled", true);
|
||||
|
||||
boolean newRunnableEnabled = configWrapper.getBoolean("runnable.enabled", true);
|
||||
// Always stop the previous ping task on reload (reschedule below only if still enabled); gating the cancel on staying enabled leaked the task when disabling via reload.
|
||||
if (pingTask != null) { // null on first startup
|
||||
pingTask.cancel();
|
||||
pingTask = null;
|
||||
}
|
||||
|
||||
runnableEnabled = newRunnableEnabled;
|
||||
runnableInterval = config.getLong("runnable.interval", 5L);
|
||||
runnableInterval = configWrapper.getLong("runnable.interval", 5L);
|
||||
|
||||
if (runnableEnabled) {
|
||||
long initialDelay = 0L;
|
||||
long pingTaskRunnableInterval = runnableInterval;
|
||||
// Folia does not allow 0 ticks of wait time
|
||||
if (KnockbackSyncBase.INSTANCE.platform == Platform.FOLIA) {
|
||||
if (Base.INSTANCE.getPlatform() == Platform.FOLIA) {
|
||||
initialDelay = 1L;
|
||||
pingTaskRunnableInterval = Math.max(pingTaskRunnableInterval, 1L);
|
||||
}
|
||||
pingTask = KnockbackSyncBase.INSTANCE.getScheduler().runTaskTimerAsynchronously(new PingRunnable(), initialDelay, pingTaskRunnableInterval);
|
||||
pingTask = Base.INSTANCE.getScheduler().runTaskTimerAsynchronously(new PingRunnable(), initialDelay, pingTaskRunnableInterval);
|
||||
}
|
||||
|
||||
notifyUpdate = config.getBoolean("notify_updates", true);
|
||||
combatTimer = config.getLong("runnable.timer", 30L);
|
||||
spikeThreshold = config.getLong("spike_threshold", 20L);
|
||||
enableMessage = config.getString("enable_message", "&aSuccessfully enabled KnockbackSync.");
|
||||
disableMessage = config.getString("disable_message", "&cSuccessfully disabled KnockbackSync.");
|
||||
playerEnableMessage = config.getString("player_enable_message", "&aSuccessfully enabled KnockbackSync for %player%.");
|
||||
playerDisableMessage = config.getString("player_disable_message", "&cSuccessfully disabled KnockbackSync for %player%.");
|
||||
playerIneligibleMessage = config.getString("player_ineligible_message", "&c%player% is ineligible for KnockbackSync. If you believe this is an error, please open an issue on the github page.");
|
||||
reloadMessage = config.getString("reload_message", "&aSuccessfully reloaded KnockbackSync.");
|
||||
PlayerData.PING_OFFSET = config.getInt("ping_offset", 25);
|
||||
legacyKnockbackEnabled = configWrapper.getBoolean("legacy_knockback.enabled", false);
|
||||
legacyKnockbackHorizontal = configWrapper.getDouble("legacy_knockback.horizontal", 0.4);
|
||||
legacyKnockbackVertical = configWrapper.getDouble("legacy_knockback.vertical", 0.4);
|
||||
legacyKnockbackVerticalLimit = configWrapper.getDouble("legacy_knockback.vertical_limit", 0.4);
|
||||
legacyKnockbackExtraHorizontal = configWrapper.getDouble("legacy_knockback.extra_horizontal", 0.5);
|
||||
legacyKnockbackExtraVertical = configWrapper.getDouble("legacy_knockback.extra_vertical", 0.1);
|
||||
legacyKnockbackResistanceEnabled = configWrapper.getBoolean("legacy_knockback.enable_knockback_resistance", false);
|
||||
|
||||
notifyUpdate = configWrapper.getBoolean("notify_updates", true);
|
||||
autoUpdate = configWrapper.getBoolean("auto_update", true);
|
||||
combatTimer = configWrapper.getLong("runnable.combat_timer", 30L);
|
||||
spikeThreshold = configWrapper.getLong("spike_threshold", 20L);
|
||||
enableMessage = configWrapper.getString("messages.toggle.global.enable", "&aSuccessfully enabled KnockbackSync.");
|
||||
disableMessage = configWrapper.getString("messages.toggle.global.disable", "&cSuccessfully disabled KnockbackSync.");
|
||||
playerEnableMessage = configWrapper.getString("messages.toggle.player.enable", "&aSuccessfully enabled KnockbackSync for %player%.");
|
||||
playerDisableMessage = configWrapper.getString("messages.toggle.player.disable", "&aSuccessfully &cdisabled &aKnockbackSync for %player%.");
|
||||
playerIneligibleMessage = configWrapper.getString("messages.toggle.player.ineligible", "&c%player% is ineligible for KnockbackSync. If you believe this is in error, please contact your server administrators.");
|
||||
playerDisconnectedWhileExecutingCommand = configWrapper.getString("messages.toggle.player.disconnected-while-executing-command", "&c%player% disconnected while executing command.");
|
||||
}
|
||||
|
||||
public void updateConfig() {
|
||||
ConfigWrapper oldConfig = getConfigWrapper();
|
||||
long oldConfigVersion = oldConfig.getLong("config_version", 0);
|
||||
|
||||
if (oldConfigVersion < CONFIG_VERSION) {
|
||||
// Backup old config with comments
|
||||
File backupFile = new File(configFile.getParentFile(), "config-version-" + oldConfigVersion + ".yml");
|
||||
try {
|
||||
Files.move(configFile.toPath(), backupFile.toPath());
|
||||
Base.INSTANCE.getLogger().info("Backed up old config to " + backupFile.getName());
|
||||
} catch (IOException e) {
|
||||
Base.INSTANCE.getLogger().warning("Failed to backup old config: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Store old values
|
||||
Map<String, Object> oldValues = new HashMap<>(config);
|
||||
|
||||
// Create new config with default values
|
||||
Base.INSTANCE.saveDefaultConfig();
|
||||
reloadConfig();
|
||||
|
||||
// Transfer existing settings
|
||||
ConfigWrapper newConfig = getConfigWrapper();
|
||||
transferAllSettings(oldConfig, newConfig);
|
||||
|
||||
// Set new config version
|
||||
newConfig.set("config_version", CONFIG_VERSION);
|
||||
|
||||
// Save updated config
|
||||
saveConfig();
|
||||
|
||||
Base.INSTANCE.getLogger().info("Config updated to version " + CONFIG_VERSION);
|
||||
}
|
||||
}
|
||||
|
||||
private void transferAllSettings(ConfigWrapper oldConfig, ConfigWrapper newConfig) {
|
||||
transferSettingsRecursive(oldConfig, newConfig, ".");
|
||||
}
|
||||
|
||||
private void transferSettingsRecursive(ConfigWrapper oldConfig, ConfigWrapper newConfig, String currentPath) {
|
||||
for (String key : oldConfig.getKeys(currentPath)) {
|
||||
String fullPath = currentPath.isEmpty() || currentPath.equals(".") ? key : currentPath + "." + key;
|
||||
if (newConfig.contains(fullPath)) {
|
||||
Object value = oldConfig.get(fullPath);
|
||||
if (value instanceof Map) {
|
||||
transferSettingsRecursive(oldConfig, newConfig, fullPath);
|
||||
} else {
|
||||
newConfig.set(fullPath, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
package me.caseload.knockbacksync.manager;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.FloodgateUtil;
|
||||
import me.caseload.knockbacksync.util.GeyserUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -11,23 +15,28 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class PlayerDataManager {
|
||||
|
||||
private static final Map<UUID, PlayerData> playerDataMap = new ConcurrentHashMap<>();
|
||||
private static final Map<User, PlayerData> playerDataMap = new ConcurrentHashMap<>();
|
||||
|
||||
public static PlayerData getPlayerData(@NotNull UUID uuid) {
|
||||
return playerDataMap.get(uuid);
|
||||
public static @Nullable PlayerData getPlayerData(@NotNull User user) {
|
||||
return playerDataMap.get(user);
|
||||
}
|
||||
|
||||
public static void addPlayerData(@NotNull UUID uuid, @NotNull PlayerData playerData) {
|
||||
if (!shouldExempt(uuid))
|
||||
playerDataMap.put(uuid, playerData);
|
||||
public static void addPlayerData(@NotNull User user, @NotNull PlatformPlayer platformPlayer) {
|
||||
if (!shouldExempt(platformPlayer.getUUID())) {
|
||||
PlayerData playerData = new PlayerData(user, platformPlayer);
|
||||
playerDataMap.put(user, playerData);
|
||||
Base.INSTANCE.getEventBus().registerListeners(playerData);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removePlayerData(@NotNull UUID uuid) {
|
||||
playerDataMap.remove(uuid);
|
||||
public static void removePlayerData(@NotNull User user) {
|
||||
PlayerData playerData = playerDataMap.remove(user);
|
||||
if (playerData != null)
|
||||
Base.INSTANCE.getEventBus().unregisterListeners(playerData);
|
||||
}
|
||||
|
||||
public static boolean containsPlayerData(@NotNull UUID uuid) {
|
||||
return playerDataMap.containsKey(uuid);
|
||||
public static boolean containsPlayerData(@NotNull User user) {
|
||||
return playerDataMap.containsKey(user);
|
||||
}
|
||||
|
||||
public static boolean shouldExempt(@NotNull UUID uuid) {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package me.caseload.knockbacksync.permission;
|
||||
|
||||
import me.caseload.knockbacksync.command.PlatformSender;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
|
||||
public interface PermissionChecker {
|
||||
boolean hasPermission(Object CommandSourceStack, String s, boolean defaultIfUnset);
|
||||
boolean hasPermission(Object nativeType, String s, boolean defaultIfUnset);
|
||||
|
||||
boolean hasPermission(PlatformSender source, String s, boolean defaultIfUnset);
|
||||
boolean hasPermission(Sender source, String s, boolean defaultIfUnset);
|
||||
|
||||
boolean hasPermission(PlatformPlayer platform, String s);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package me.caseload.knockbacksync.player;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class JitterCalculator {
|
||||
private final int SAMPLE_SIZE = 15;
|
||||
@@ -31,7 +32,7 @@ public class JitterCalculator {
|
||||
double upperBound = q3 + 1.5 * iqr;
|
||||
List<Long> filteredPings = sortedPings.stream()
|
||||
.filter(p -> p >= lowerBound && p <= upperBound)
|
||||
.toList();
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Calculate standard deviation
|
||||
double mean = filteredPings.stream().mapToLong(Long::longValue).average().orElse(0);
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package me.caseload.knockbacksync.player;
|
||||
|
||||
public enum PingStrategy {
|
||||
KEEPALIVE,
|
||||
TRANSACTION
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package me.caseload.knockbacksync.player;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
|
||||
public interface PlatformBlock {
|
||||
WrappedBlockState getMaterial();
|
||||
// Add more methods as needed
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package me.caseload.knockbacksync.player;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.BoundingBox;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.world.PlatformWorld;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -40,8 +42,35 @@ public interface PlatformPlayer {
|
||||
|
||||
int getMainHandKnockbackLevel();
|
||||
|
||||
/**
|
||||
* Knockback enchant level used for legacy (1.8) knockback bonus calculation.
|
||||
* Mirrors OldCombatMechanics: the main hand item, or the off hand item when the
|
||||
* main hand is empty. Defaults to the main hand level for platforms that do not
|
||||
* override it.
|
||||
*/
|
||||
default int getWeaponKnockbackLevel() {
|
||||
return getMainHandKnockbackLevel();
|
||||
}
|
||||
|
||||
@Nullable Integer getNoDamageTicks();
|
||||
|
||||
void setVelocity(Vector3d adjustedVelocity);
|
||||
|
||||
Vector3d getVelocity();
|
||||
|
||||
double getJumpPower();
|
||||
|
||||
BoundingBox getBoundingBox();
|
||||
|
||||
/**
|
||||
* If a player disconnects while we are running the constructor of a PlatformPlayer
|
||||
* PacketEvents.getAPI().getPlayerManager().getUser(bukkitPlayer) may return null
|
||||
* This will make the internal field null and thus this function may return null.
|
||||
*/
|
||||
@Nullable User getUser();
|
||||
|
||||
void setClientBrand(String brand);
|
||||
|
||||
String getClientBrand();
|
||||
// Add more methods as needed
|
||||
}
|
||||
@@ -2,19 +2,28 @@ package me.caseload.knockbacksync.player;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.player.PlayerManager;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.netty.channel.ChannelHelper;
|
||||
import com.github.retrooper.packetevents.protocol.ConnectionState;
|
||||
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes;
|
||||
import com.github.retrooper.packetevents.protocol.world.BoundingBox;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowConfirmation;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.command.subcommand.ToggleOffGroundSubcommand;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.event.events.ToggleOnOffEvent;
|
||||
import me.caseload.knockbacksync.manager.CombatManager;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.scheduler.AbstractTaskHandle;
|
||||
import me.caseload.knockbacksync.scheduler.NettyTaskHandle;
|
||||
import me.caseload.knockbacksync.util.MathUtil;
|
||||
import me.caseload.knockbacksync.util.data.Pair;
|
||||
import me.caseload.knockbacksync.world.PlatformWorld;
|
||||
@@ -24,22 +33,27 @@ import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import io.netty.channel.Channel;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Getter
|
||||
public class PlayerData {
|
||||
|
||||
// Please read the GitHub FAQ before adjusting.
|
||||
public static long PING_OFFSET;
|
||||
public static float TICK_RATE = 20.0F;
|
||||
private static final short MAIN_THREAD_TRANSACTION_ID = 31407;
|
||||
private static final short NETTY_THREAD_TRANSACTION_ID = 31408;
|
||||
public static final long PING_OFFSET = 25;
|
||||
|
||||
private static Field playerField;
|
||||
|
||||
public final Queue<Pair<Integer, Long>> transactionsSent = new ConcurrentLinkedQueue<>();
|
||||
public final Queue<Pair<Long, Long>> keepaliveMap = new ConcurrentLinkedQueue<>();
|
||||
|
||||
static {
|
||||
try {
|
||||
switch (KnockbackSyncBase.INSTANCE.platform) {
|
||||
switch (Base.INSTANCE.getPlatform()) {
|
||||
case BUKKIT:
|
||||
case FOLIA:
|
||||
Class<?> bukkitPlayerClass = Class.forName("me.caseload.knockbacksync.player.BukkitPlayer");
|
||||
@@ -50,7 +64,7 @@ public class PlayerData {
|
||||
playerField = fabricPlayerClass.getDeclaredField("fabricPlayer");
|
||||
break;
|
||||
default:
|
||||
throw new IllegalStateException("Unexpected platform: " + KnockbackSyncBase.INSTANCE.platform);
|
||||
throw new IllegalStateException("Unexpected platform: " + Base.INSTANCE.getPlatform());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
@@ -61,50 +75,97 @@ public class PlayerData {
|
||||
public final User user;
|
||||
private final PlatformPlayer platformPlayer;
|
||||
private final UUID uuid;
|
||||
@NotNull
|
||||
private final Random random = new Random();
|
||||
public Queue<Pair<Long, Long>> keepaliveMap = new LinkedList<>();
|
||||
@NotNull private final Random random = new Random();
|
||||
public long lastKeepAliveID = 0;
|
||||
@Getter
|
||||
private JitterCalculator jitterCalculator = new JitterCalculator();
|
||||
@Getter
|
||||
@Setter
|
||||
private double jitter;
|
||||
@Nullable
|
||||
private AbstractTaskHandle combatTask;
|
||||
@Nullable
|
||||
@Setter
|
||||
private Double ping, previousPing;
|
||||
@Nullable
|
||||
@Setter
|
||||
private Double verticalVelocity;
|
||||
@Nullable
|
||||
@Setter
|
||||
private Integer lastDamageTicks;
|
||||
@Setter
|
||||
private double gravityAttribute = 0.08;
|
||||
@Setter
|
||||
private double knockbackResistanceAttribute = 0.0;
|
||||
@Getter private final JitterCalculator jitterCalculator = new JitterCalculator();
|
||||
@Setter private double jitter;
|
||||
@Nullable private AbstractTaskHandle combatTask;
|
||||
@NotNull private final Object combatTaskLock = new Object(); // Lock object for synchronization
|
||||
@Nullable @Setter private Double ping, previousPing;
|
||||
@Nullable @Setter private Double verticalVelocity;
|
||||
@Nullable @Setter private Integer lastDamageTicks;
|
||||
// Legacy (1.8) knockback computed at damage time, consumed by the next PlayerVelocityEvent.
|
||||
// Guarded by a short expiry so a stale value never affects an unrelated velocity event.
|
||||
@Nullable private Vector3d legacyKnockback;
|
||||
private long legacyKnockbackExpiryNanos;
|
||||
// True when the pending legacyKnockback is a fishing-rod (bobber-direction) vector supplied
|
||||
// via the rod API rather than the melee formula. Lets the damage listener keep the rod vector
|
||||
// instead of overwriting it with melee, while still latency-syncing it. See api.KnockbackSyncRodApi.
|
||||
private boolean legacyKnockbackIsRod;
|
||||
@Setter private double gravityAttribute = 0.08;
|
||||
@Setter private double knockbackResistanceAttribute = 0.0;
|
||||
public PingStrategy pingStrategy; // this is currently shared between all instances, but can be made per-player later
|
||||
|
||||
public PlayerData(PlatformPlayer platformPlayer) {
|
||||
public PlayerData(User user, PlatformPlayer platformPlayer) {
|
||||
this.uuid = platformPlayer.getUUID();
|
||||
this.user = user;
|
||||
this.platformPlayer = platformPlayer;
|
||||
this.pingStrategy = loadPingStrategy(Base.INSTANCE.getConfigManager());
|
||||
}
|
||||
|
||||
User tempUser = null;
|
||||
/**
|
||||
* Stores the legacy (1.8) knockback to apply on the next PlayerVelocityEvent.
|
||||
* Expires shortly after so it can never be applied to an unrelated velocity event
|
||||
* (explosions, other plugins, etc.) if the expected velocity event never fires.
|
||||
*/
|
||||
public void setLegacyKnockback(@Nullable Vector3d legacyKnockback) {
|
||||
this.legacyKnockback = legacyKnockback;
|
||||
this.legacyKnockbackIsRod = false;
|
||||
// 100ms window: damage and the resulting velocity event fire in the same tick.
|
||||
this.legacyKnockbackExpiryNanos = System.nanoTime() + 100_000_000L;
|
||||
}
|
||||
|
||||
PlayerManager playerManager = PacketEvents.getAPI().getPlayerManager();
|
||||
Object player = null;
|
||||
try {
|
||||
player = playerField.get(platformPlayer);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
/**
|
||||
* Stores a fishing-rod (bobber-direction) knockback to apply + latency-sync on the next
|
||||
* PlayerVelocityEvent, flagged so the damage listener keeps it instead of overwriting it with
|
||||
* the melee formula. Must be set immediately before the rod's damage tick. See
|
||||
* {@code api.KnockbackSyncRodApi}.
|
||||
*/
|
||||
public void setRodKnockback(@NotNull Vector3d rodKnockback) {
|
||||
this.legacyKnockback = rodKnockback;
|
||||
this.legacyKnockbackIsRod = true;
|
||||
this.legacyKnockbackExpiryNanos = System.nanoTime() + 100_000_000L;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if an unexpired fishing-rod knockback is pending (so the damage listener must
|
||||
* not overwrite it with melee knockback).
|
||||
*/
|
||||
public boolean isRodKnockbackPending() {
|
||||
return peekLegacyKnockback() != null && legacyKnockbackIsRod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the pending legacy knockback if present and not expired, otherwise {@code null}.
|
||||
*/
|
||||
@Nullable
|
||||
public Vector3d peekLegacyKnockback() {
|
||||
if (legacyKnockback == null) return null;
|
||||
if (System.nanoTime() > legacyKnockbackExpiryNanos) {
|
||||
legacyKnockback = null;
|
||||
legacyKnockbackIsRod = false;
|
||||
return null;
|
||||
}
|
||||
return legacyKnockback;
|
||||
}
|
||||
|
||||
if (player != null) {
|
||||
tempUser = playerManager.getUser(player);
|
||||
}
|
||||
/**
|
||||
* Returns and clears the pending legacy knockback (if present and not expired).
|
||||
*/
|
||||
@Nullable
|
||||
public Vector3d consumeLegacyKnockback() {
|
||||
Vector3d v = peekLegacyKnockback();
|
||||
legacyKnockback = null;
|
||||
legacyKnockbackIsRod = false;
|
||||
return v;
|
||||
}
|
||||
|
||||
this.user = tempUser;
|
||||
public double getNotNullPing() {
|
||||
return ping != null ? ping : platformPlayer.getPing();
|
||||
}
|
||||
|
||||
public double getNotNullPreviousPing() {
|
||||
return previousPing != null ? previousPing : platformPlayer.getPing();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -114,32 +175,62 @@ public class PlayerData {
|
||||
*
|
||||
* @return The compensated ping, with a minimum of 1.
|
||||
*/
|
||||
public double getEstimatedPing() {
|
||||
double currentPing = (ping != null) ? ping : platformPlayer.getPing();
|
||||
double lastPing = (previousPing != null) ? previousPing : platformPlayer.getPing();
|
||||
double ping = (currentPing - lastPing > KnockbackSyncBase.INSTANCE.getConfigManager().getSpikeThreshold()) ? lastPing : currentPing;
|
||||
public double getCompensatedPing() {
|
||||
double ping = getNotNullPing();
|
||||
double previousPing = getNotNullPreviousPing();
|
||||
double spikeCompensatedPing = (ping - previousPing > Base.INSTANCE.getConfigManager().getSpikeThreshold()) ? previousPing : ping;
|
||||
|
||||
return Math.max(1, ping - PING_OFFSET);
|
||||
return Math.max(1, spikeCompensatedPing - PING_OFFSET);
|
||||
}
|
||||
|
||||
public boolean isKeepAliveIDOurs(long id) {
|
||||
return id == lastKeepAliveID;
|
||||
public int getCompensatedTicks() {
|
||||
return (int) Math.ceil(getCompensatedPing() * Base.INSTANCE.getTickRate() / 1000); // Multiply ping by seconds per tick
|
||||
}
|
||||
|
||||
public int getTicks() {
|
||||
return (int) Math.ceil(getNotNullPing() * Base.INSTANCE.getTickRate() / 1000); // Multiply ping by seconds per tick
|
||||
}
|
||||
|
||||
public boolean isSpike() {
|
||||
return (getNotNullPing() - getNotNullPreviousPing()) > Base.INSTANCE.getConfigManager().getSpikeThreshold();
|
||||
}
|
||||
|
||||
// Doesn't actually send a ping, sends a keepalive, more accurate and processed faster
|
||||
public void sendPing(boolean async) {
|
||||
if (user == null || user.getEncoderState() != ConnectionState.PLAY) return;
|
||||
|
||||
if (async) {
|
||||
ChannelHelper.runInEventLoop(user.getChannel(), () -> {
|
||||
// We call sendPacket instead of writePacket because it flushes immediately
|
||||
// Making our time measurement more accurate since we don't call, System.nanoTime(), wait until flush
|
||||
// And then actually send packet
|
||||
user.sendPacket(new WrapperPlayServerKeepAlive(lastKeepAliveID = System.nanoTime()));
|
||||
});
|
||||
} else {
|
||||
user.sendPacket(new WrapperPlayServerKeepAlive(lastKeepAliveID = System.nanoTime()));
|
||||
}
|
||||
switch (pingStrategy) {
|
||||
case KEEPALIVE:
|
||||
long keepAliveID = async ? NETTY_THREAD_TRANSACTION_ID : MAIN_THREAD_TRANSACTION_ID;
|
||||
if (async) {
|
||||
ChannelHelper.runInEventLoop(user.getChannel(), () -> {
|
||||
// We call sendPacket instead of writePacket because it flushes immediately
|
||||
// Making our time measurement more accurate since we don't call, System.nanoTime(), wait until flush
|
||||
// And then actually send packet
|
||||
user.sendPacket(new WrapperPlayServerKeepAlive(keepAliveID));
|
||||
});
|
||||
} else {
|
||||
user.sendPacket(new WrapperPlayServerKeepAlive(keepAliveID));
|
||||
}
|
||||
break;
|
||||
case TRANSACTION:
|
||||
PacketWrapper<?> packet;
|
||||
short pingTransactionID = async ? NETTY_THREAD_TRANSACTION_ID : MAIN_THREAD_TRANSACTION_ID;
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_17)) {
|
||||
packet = new WrapperPlayServerPing(pingTransactionID);
|
||||
} else {
|
||||
packet = new WrapperPlayServerWindowConfirmation((byte) 0, pingTransactionID, false);
|
||||
}
|
||||
|
||||
// sendPacket (write + flush) rather than writePacket: an unflushed write sits in the channel until the next flush and inflates the measured ping.
|
||||
if (async) {
|
||||
ChannelHelper.runInEventLoop(user.getChannel(), () -> {
|
||||
user.sendPacket(packet);
|
||||
});
|
||||
} else {
|
||||
user.sendPacket(packet);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,32 +249,37 @@ public class PlayerData {
|
||||
* @param verticalVelocity The Player's current vertical velocity.
|
||||
* @return <code>true</code> if the Player is on the ground; <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean isOnGround(double verticalVelocity) {
|
||||
WrappedBlockState blockState = platformPlayer.getWorld().getBlockStateAt(platformPlayer.getLocation());
|
||||
|
||||
if (platformPlayer.isGliding() ||
|
||||
blockState.getType() == StateTypes.WATER ||
|
||||
blockState.getType() == StateTypes.LAVA ||
|
||||
blockState.getType() == StateTypes.COBWEB ||
|
||||
blockState.getType() == StateTypes.SCAFFOLDING) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ping == null || ping < PING_OFFSET)
|
||||
return false;
|
||||
|
||||
double gDist = getDistanceToGround();
|
||||
if (gDist <= 0)
|
||||
return false; // prevent player from taking adjusted knockback when on ground serverside
|
||||
|
||||
public boolean isOnGroundClientSide(double verticalVelocity, double distanceToGround) {
|
||||
int tMax = verticalVelocity > 0 ? MathUtil.calculateTimeToMaxVelocity(verticalVelocity, gravityAttribute) : 0;
|
||||
if (tMax == -1)
|
||||
return false; // reached the max tick limit, not safe to predict
|
||||
|
||||
double mH = verticalVelocity > 0 ? MathUtil.calculateDistanceTraveled(verticalVelocity, tMax, gravityAttribute) : 0;
|
||||
int tFall = MathUtil.calculateFallTime(verticalVelocity, mH + gDist, gravityAttribute);
|
||||
int tFall = MathUtil.calculateFallTime(verticalVelocity, mH + distanceToGround, gravityAttribute);
|
||||
|
||||
if (tFall == -1)
|
||||
return false; // reached the max tick limit, not safe to predict
|
||||
|
||||
return getEstimatedPing() >= tMax + tFall / TICK_RATE * 1000 && gDist <= 1.3;
|
||||
return (tMax + tFall) - getCompensatedTicks() <= 0 && distanceToGround <= 1.3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether or not offGroundSynchronization is enabled for the player.
|
||||
* @return <code>true</code> if enabled; <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean isOffGroundSyncEnabled() {
|
||||
// TODO, per-player offground sync toggles?
|
||||
return ToggleOffGroundSubcommand.offGroundSyncEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the compensated off-ground velocity.
|
||||
* This is used to make knockback feel more accurate off-ground.
|
||||
*
|
||||
* @return Compensated Y axis velocity
|
||||
*/
|
||||
public double getCompensatedOffGroundVelocity() {
|
||||
return MathUtil.getCompensatedVerticalVelocity(platformPlayer.getVelocity().getY(), getGravityAttribute(), getTicks());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -200,10 +296,10 @@ public class PlayerData {
|
||||
for (Vector3d corner : getBBCorners()) {
|
||||
RayTraceResult result = world.rayTraceBlocks(corner, new Vector3d(0, -1, 0), 5, FluidHandling.NONE, true);
|
||||
|
||||
if (result == null || result.getHitPosition() == null)
|
||||
if (result == null || result.getHitBlock() == null)
|
||||
continue;
|
||||
|
||||
collisionDist = Math.min(collisionDist, corner.getY() - result.getHitPosition().getY());
|
||||
collisionDist = Math.min(collisionDist, corner.getY() - result.getHitBlockPosition().getY());
|
||||
}
|
||||
|
||||
return collisionDist - 1;
|
||||
@@ -215,16 +311,16 @@ public class PlayerData {
|
||||
* @return An array of locations representing the corners of the bounding box.
|
||||
*/
|
||||
private Vector3d[] getBBCorners() {
|
||||
Vector3d playerPos = platformPlayer.getLocation();
|
||||
double width = 0.6; // typical player width
|
||||
// double height = 1.8; // typical player height
|
||||
double adjustment = 0.01;
|
||||
BoundingBox boundingBox = platformPlayer.getBoundingBox();
|
||||
Vector3d location = platformPlayer.getLocation();
|
||||
|
||||
return new Vector3d[]{
|
||||
new Vector3d(playerPos.getX() - width / 2 + adjustment, playerPos.getY(), playerPos.getZ() - width / 2 + adjustment),
|
||||
new Vector3d(playerPos.getX() - width / 2 + adjustment, playerPos.getY(), playerPos.getZ() + width / 2 - adjustment),
|
||||
new Vector3d(playerPos.getX() + width / 2 - adjustment, playerPos.getY(), playerPos.getZ() - width / 2 + adjustment),
|
||||
new Vector3d(playerPos.getX() + width / 2 - adjustment, playerPos.getY(), playerPos.getZ() + width / 2 - adjustment)
|
||||
double adjustment = 0.01; // To ensure the bounding box isn't clipping inside a wall
|
||||
|
||||
return new Vector3d[] {
|
||||
new Vector3d(boundingBox.getMinX() + adjustment, location.getY(), boundingBox.getMinZ() + adjustment),
|
||||
new Vector3d(boundingBox.getMinX() + adjustment, location.getY(), boundingBox.getMaxZ() - adjustment),
|
||||
new Vector3d(boundingBox.getMaxX() - adjustment, location.getY(), boundingBox.getMinZ() + adjustment),
|
||||
new Vector3d(boundingBox.getMaxX() - adjustment, location.getY(), boundingBox.getMaxZ() - adjustment)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -240,7 +336,6 @@ public class PlayerData {
|
||||
|
||||
if (!attacker.isSprinting()) {
|
||||
yAxis = 0.36080000519752503;
|
||||
// double knockbackResistance = knockbackResistanceAttribute;
|
||||
double resistanceFactor = 0.04000000119 * knockbackResistanceAttribute * 10;
|
||||
yAxis -= resistanceFactor;
|
||||
}
|
||||
@@ -252,43 +347,41 @@ public class PlayerData {
|
||||
return yAxis;
|
||||
}
|
||||
|
||||
// might need soon
|
||||
// public double calculateJumpVelocity() {
|
||||
// double jumpVelocity = 0.42;
|
||||
//
|
||||
// PotionEffect jumpEffect = player.getPotionEffect(PotionEffectType.JUMP);
|
||||
// if (jumpEffect != null) {
|
||||
// int amplifier = jumpEffect.getAmplifier();
|
||||
// jumpVelocity += (amplifier + 1) * 0.1F;
|
||||
// }
|
||||
//
|
||||
// return jumpVelocity;
|
||||
// }
|
||||
|
||||
public boolean isInCombat() {
|
||||
return combatTask != null;
|
||||
}
|
||||
|
||||
public void updateCombat() {
|
||||
if (isInCombat())
|
||||
combatTask.cancel();
|
||||
|
||||
combatTask = newCombatTask();
|
||||
CombatManager.addPlayer(uuid);
|
||||
Channel channel = (Channel) user.getChannel();
|
||||
channel.eventLoop().execute(() -> {
|
||||
if (combatTask != null) {
|
||||
combatTask.cancel();
|
||||
}
|
||||
combatTask = newCombatTask(channel);
|
||||
CombatManager.addPlayer(user);
|
||||
});
|
||||
}
|
||||
|
||||
public void quitCombat(boolean cancelTask) {
|
||||
if (cancelTask)
|
||||
combatTask.cancel();
|
||||
|
||||
combatTask = null;
|
||||
CombatManager.removePlayer(uuid);
|
||||
/**
|
||||
* Cancels the combatTask quit task. This prevents quitCombat() from being called later against a new combat task
|
||||
* Or against a player that has disconnected already
|
||||
* @param async Whether we are already in the players netty thread
|
||||
*/
|
||||
public void quitCombat(boolean async) {
|
||||
Channel channel = (Channel) user.getChannel();
|
||||
Runnable runnable = () -> {
|
||||
if (combatTask != null) {
|
||||
combatTask.cancel();
|
||||
combatTask = null;
|
||||
}
|
||||
CombatManager.removePlayer(user);
|
||||
};
|
||||
if (async) {
|
||||
channel.eventLoop().execute(runnable);
|
||||
} else {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private AbstractTaskHandle newCombatTask() {
|
||||
return KnockbackSyncBase.INSTANCE.getScheduler().runTaskLaterAsynchronously(
|
||||
() -> quitCombat(false), KnockbackSyncBase.INSTANCE.getConfigManager().getCombatTimer());
|
||||
private AbstractTaskHandle newCombatTask(Channel channel) {
|
||||
return new NettyTaskHandle(channel.eventLoop().schedule(() -> quitCombat(false), convertTicksToMilliseconds(Base.INSTANCE.getConfigManager().getCombatTimer()), TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
public ClientVersion getClientVersion() {
|
||||
@@ -305,4 +398,39 @@ public class PlayerData {
|
||||
public long getKeepAliveSendTime() {
|
||||
return lastKeepAliveID;
|
||||
}
|
||||
|
||||
public boolean didWeSendThatPacket(long receivedId) {
|
||||
return receivedId == NETTY_THREAD_TRANSACTION_ID || receivedId == MAIN_THREAD_TRANSACTION_ID;
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onToggledEvent(ToggleOnOffEvent event) {
|
||||
if (!event.getStatus()) {
|
||||
transactionsSent.clear();
|
||||
keepaliveMap.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onConfigReloadEvent(ConfigReloadEvent event) {
|
||||
this.pingStrategy = loadPingStrategy(event.getConfigManager());
|
||||
}
|
||||
|
||||
private PingStrategy loadPingStrategy(ConfigManager configManager) {
|
||||
// Default PING: vanilla ignores unintercepted pong echoes, while unintercepted keepalive echoes kick ("Timed out") on 1.20.2+.
|
||||
String pingStrategy = configManager.getConfigWrapper().getString("ping_strategy", "PING");
|
||||
switch (pingStrategy) {
|
||||
case "KEEPALIVE":
|
||||
return PingStrategy.KEEPALIVE;
|
||||
case "PING":
|
||||
case "TRANSACTION":
|
||||
return PingStrategy.TRANSACTION;
|
||||
default:
|
||||
throw new IllegalStateException("Unknown ping_strategy: " + pingStrategy);
|
||||
}
|
||||
}
|
||||
|
||||
private long convertTicksToMilliseconds(long ticks) {
|
||||
return ticks * 50;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package me.caseload.knockbacksync.runnable;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.CombatManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
@@ -11,12 +12,13 @@ public class PingRunnable implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled())
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled())
|
||||
return;
|
||||
|
||||
for (UUID uuid : CombatManager.getPlayers()) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
playerData.sendPing(true);
|
||||
for (User user : CombatManager.getPlayers()) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData != null)
|
||||
playerData.sendPing(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
public interface AbstractTaskHandle {
|
||||
|
||||
public boolean getCancelled();
|
||||
boolean getCancelled();
|
||||
|
||||
public void cancel();
|
||||
void cancel();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
import io.netty.util.concurrent.ScheduledFuture;
|
||||
|
||||
public class NettyTaskHandle implements AbstractTaskHandle {
|
||||
|
||||
private final ScheduledFuture scheduledFuture;
|
||||
|
||||
public NettyTaskHandle(ScheduledFuture<?> scheduledFuture) {
|
||||
this.scheduledFuture = scheduledFuture;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getCancelled() {
|
||||
return scheduledFuture.isCancelled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
scheduledFuture.cancel(true);
|
||||
}
|
||||
}
|
||||
+12
-7
@@ -1,16 +1,16 @@
|
||||
package me.caseload.knockbacksync.command;
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Simple implementation of {@link PlatformSender} using a {@link SenderFactory}
|
||||
* Simple implementation of {@link Sender} using a {@link SenderFactory}
|
||||
*
|
||||
* @param <T> the command sender type
|
||||
*/
|
||||
public final class AbstractSender<T> implements PlatformSender {
|
||||
private final KnockbackSyncBase plugin;
|
||||
public final class AbstractSender<T> implements Sender {
|
||||
private final Base plugin;
|
||||
private final SenderFactory<?, T> factory;
|
||||
private final T sender;
|
||||
|
||||
@@ -18,7 +18,7 @@ public final class AbstractSender<T> implements PlatformSender {
|
||||
private final String name;
|
||||
private final boolean isConsole;
|
||||
|
||||
AbstractSender(KnockbackSyncBase plugin, SenderFactory<?, T> factory, T sender) {
|
||||
AbstractSender(Base plugin, SenderFactory<?, T> factory, T sender) {
|
||||
this.plugin = plugin;
|
||||
this.factory = factory;
|
||||
this.sender = sender;
|
||||
@@ -28,7 +28,7 @@ public final class AbstractSender<T> implements PlatformSender {
|
||||
}
|
||||
|
||||
@Override
|
||||
public KnockbackSyncBase getPlugin() {
|
||||
public Base getPlugin() {
|
||||
return this.plugin;
|
||||
}
|
||||
|
||||
@@ -52,6 +52,11 @@ public final class AbstractSender<T> implements PlatformSender {
|
||||
return isConsole() || this.factory.hasPermission(this.sender, permission);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(String permission, boolean defaultIfUnset) {
|
||||
return isConsole() || this.factory.hasPermission(this.sender, permission, defaultIfUnset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void performCommand(String commandLine) {
|
||||
this.factory.performCommand(this.sender, commandLine);
|
||||
+6
-4
@@ -1,13 +1,13 @@
|
||||
package me.caseload.knockbacksync.command;
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Wrapper interface to represent a CommandSender/CommandSource within the common command implementations.
|
||||
*/
|
||||
public interface PlatformSender {
|
||||
public interface Sender {
|
||||
|
||||
/**
|
||||
* The uuid used by the console sender.
|
||||
@@ -23,7 +23,7 @@ public interface PlatformSender {
|
||||
*
|
||||
* @return the plugin
|
||||
*/
|
||||
KnockbackSyncBase getPlugin();
|
||||
Base getPlugin();
|
||||
|
||||
/**
|
||||
* Gets the sender's username
|
||||
@@ -63,6 +63,8 @@ public interface PlatformSender {
|
||||
*/
|
||||
boolean hasPermission(String permission);
|
||||
|
||||
boolean hasPermission(String permission, boolean defaultIfUnset);
|
||||
|
||||
/**
|
||||
* Makes the sender perform a command.
|
||||
*
|
||||
+10
-7
@@ -1,6 +1,6 @@
|
||||
package me.caseload.knockbacksync.command;
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
@@ -11,7 +11,7 @@ import java.util.UUID;
|
||||
* @param <P> the plugin type
|
||||
* @param <T> the command sender type
|
||||
*/
|
||||
public abstract class SenderFactory<P extends KnockbackSyncBase, T> implements AutoCloseable {
|
||||
public abstract class SenderFactory<P extends Base, T> implements AutoCloseable {
|
||||
private final P plugin;
|
||||
|
||||
public SenderFactory(P plugin) {
|
||||
@@ -30,6 +30,8 @@ public abstract class SenderFactory<P extends KnockbackSyncBase, T> implements A
|
||||
|
||||
protected abstract boolean hasPermission(T sender, String node);
|
||||
|
||||
protected abstract boolean hasPermission(T sender, String node, boolean defaultIfUnset);
|
||||
|
||||
protected abstract void performCommand(T sender, String command);
|
||||
|
||||
protected abstract boolean isConsole(T sender);
|
||||
@@ -38,13 +40,14 @@ public abstract class SenderFactory<P extends KnockbackSyncBase, T> implements A
|
||||
return isConsole(sender);
|
||||
}
|
||||
|
||||
public final PlatformSender wrap(T sender) {
|
||||
public final Sender wrap(T sender) {
|
||||
Objects.requireNonNull(sender, "sender");
|
||||
return new AbstractSender<>(this.plugin, this, sender);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final T unwrap(Sender sender) {
|
||||
Objects.requireNonNull(sender, "sender");
|
||||
return (T) sender.getSender();
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,15 @@ package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.common.BuildConfig;
|
||||
import me.caseload.knockbacksync.stats.SimplePie;
|
||||
import org.kohsuke.github.GHAsset;
|
||||
import org.kohsuke.github.GHRelease;
|
||||
import org.kohsuke.github.GitHub;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.*;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
@@ -22,8 +19,7 @@ public class BuildTypePie extends SimplePie {
|
||||
|
||||
private static final String RELEASES_FILE = "releases.txt";
|
||||
private static final String DEV_BUILDS_FILE = "dev-builds.txt";
|
||||
private static final File dataFolder = KnockbackSyncBase.INSTANCE.getDataFolder();
|
||||
public static URL jarUrl;
|
||||
private static final File dataFolder = Base.INSTANCE.getDataFolder();
|
||||
private static String cachedBuildType = null;
|
||||
|
||||
public BuildTypePie() {
|
||||
@@ -39,7 +35,7 @@ public class BuildTypePie extends SimplePie {
|
||||
|
||||
private static String calculateBuildType() {
|
||||
try {
|
||||
String currentHash = KnockbackSyncBase.INSTANCE.pluginJarHashProvider.getPluginJarHash();
|
||||
String currentHash = Base.INSTANCE.getPluginJarHashProvider().getPluginJarHash();
|
||||
downloadBuildFiles();
|
||||
|
||||
if (isHashInFile(currentHash, new File(dataFolder, RELEASES_FILE))) {
|
||||
@@ -57,23 +53,26 @@ public class BuildTypePie extends SimplePie {
|
||||
|
||||
private static void downloadBuildFiles() throws IOException {
|
||||
GitHub gitHub = GitHub.connectAnonymously();
|
||||
GHRelease latestRelease = gitHub.getRepository("Axionize/knockback-sync")
|
||||
GHRelease latestRelease = gitHub.getRepository(BuildConfig.GITHUB_REPO)
|
||||
.getLatestRelease();
|
||||
List<GHAsset> assets = latestRelease.listAssets().toList();
|
||||
for (GHAsset asset : assets) {
|
||||
if (asset.getName().equals(RELEASES_FILE) || asset.getName().equals(DEV_BUILDS_FILE)) {
|
||||
KnockbackSyncBase.INSTANCE.getLogger().info("Downloading: " + asset.getName());
|
||||
Base.INSTANCE.getLogger().info("Downloading: " + asset.getName());
|
||||
|
||||
String jsonContent = readStringFromURL(asset.getUrl().toString());
|
||||
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
|
||||
String downloadUrl = jsonObject.get("browser_download_url").getAsString();
|
||||
|
||||
try (InputStream inputStream = new URL(downloadUrl).openStream();
|
||||
FileOutputStream outputStream = new FileOutputStream(new File(dataFolder, asset.getName()))) {
|
||||
inputStream.transferTo(outputStream);
|
||||
try (InputStream inputStream = new URL(downloadUrl).openStream(); FileOutputStream outputStream = new FileOutputStream(new File(dataFolder, asset.getName()))) {
|
||||
byte[] buffer = new byte[4096];
|
||||
int bytesRead;
|
||||
while ((bytesRead = inputStream.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
|
||||
KnockbackSyncBase.INSTANCE.getLogger().info("Downloaded: " + asset.getName());
|
||||
Base.INSTANCE.getLogger().info("Downloaded: " + asset.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,7 +87,13 @@ public class BuildTypePie extends SimplePie {
|
||||
|
||||
private static String readStringFromURL(String urlString) throws IOException {
|
||||
try (InputStream inputStream = new URL(urlString).openStream()) {
|
||||
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
|
||||
ByteArrayOutputStream result = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[4096];
|
||||
int bytesRead;
|
||||
while ((bytesRead = inputStream.read(buffer)) != -1) {
|
||||
result.write(buffer, 0, bytesRead);
|
||||
}
|
||||
return result.toString("UTF-8");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.stats.AdvancedPie;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ClientBrandsPie extends AdvancedPie {
|
||||
|
||||
// Gets the client versions of players online
|
||||
public ClientBrandsPie() {
|
||||
super("client_brands", () -> {
|
||||
Map<String, Integer> valueMap = new HashMap<>();
|
||||
for (PlatformPlayer player : Base.INSTANCE.getPlatformServer().getOnlinePlayers()) {
|
||||
User user = player.getUser();
|
||||
if (user == null || user.getClientVersion() == null) {
|
||||
valueMap.put("vanilla", valueMap.getOrDefault("vanilla", 0) + 1);
|
||||
} else {
|
||||
valueMap.put(player.getClientBrand(), valueMap.getOrDefault(player.getClientBrand(), 0) + 1);
|
||||
}
|
||||
}
|
||||
return valueMap;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import me.caseload.knockbacksync.stats.CustomChart;
|
||||
|
||||
public interface Metrics {
|
||||
public void shutdown();
|
||||
|
||||
void addCustomChart(CustomChart chart);
|
||||
void shutdown();
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import me.caseload.knockbacksync.stats.CustomChart;
|
||||
import me.caseload.knockbacksync.stats.JsonObjectBuilder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import java.io.*;
|
||||
@@ -94,20 +95,7 @@ public class MetricsBase {
|
||||
boolean logSentData,
|
||||
boolean logResponseStatusText,
|
||||
boolean skipRelocateCheck) {
|
||||
ScheduledThreadPoolExecutor scheduler =
|
||||
new ScheduledThreadPoolExecutor(
|
||||
1,
|
||||
task -> {
|
||||
Thread thread = new Thread(task, "bStats-Metrics");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
// We want delayed tasks (non-periodic) that will execute in the future to be
|
||||
// cancelled when the scheduler is shutdown.
|
||||
// Otherwise, we risk preventing the server from shutting down even when
|
||||
// MetricsBase#shutdown() is called
|
||||
scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
|
||||
this.scheduler = scheduler;
|
||||
this.scheduler = getScheduledThreadPoolExecutor();
|
||||
this.platform = platform;
|
||||
this.serverUuid = serverUuid;
|
||||
this.serviceId = serviceId;
|
||||
@@ -131,6 +119,23 @@ public class MetricsBase {
|
||||
}
|
||||
}
|
||||
|
||||
private static @NotNull ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor() {
|
||||
ScheduledThreadPoolExecutor scheduler =
|
||||
new ScheduledThreadPoolExecutor(
|
||||
1,
|
||||
task -> {
|
||||
Thread thread = new Thread(task, "bStats-Metrics");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
// We want delayed tasks (non-periodic) that will execute in the future to be
|
||||
// cancelled when the scheduler is shutdown.
|
||||
// Otherwise, we risk preventing the server from shutting down even when
|
||||
// MetricsBase#shutdown() is called
|
||||
scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gzips the given string.
|
||||
*
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
@@ -15,9 +17,13 @@ public class PlayerVersionsPie extends AdvancedPie {
|
||||
public PlayerVersionsPie() {
|
||||
super("player_version", () -> {
|
||||
Map<String, Integer> valueMap = new HashMap<>();
|
||||
for (PlatformPlayer player : KnockbackSyncBase.INSTANCE.platformServer.getOnlinePlayers()) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(player.getUUID());
|
||||
valueMap.put(playerData.getClientVersion().toString(), valueMap.getOrDefault(playerData.getClientVersion().toString(), 0) + 1);
|
||||
for (PlatformPlayer player : Base.INSTANCE.getPlatformServer().getOnlinePlayers()) {
|
||||
User user = player.getUser();
|
||||
if (user == null || user.getClientVersion() == null) {
|
||||
valueMap.put(ClientVersion.UNKNOWN.toString(), valueMap.getOrDefault(ClientVersion.UNKNOWN.toString(), 0) + 1);
|
||||
} else {
|
||||
valueMap.put(user.getClientVersion().toString(), valueMap.getOrDefault(user.getClientVersion().toString(), 0) + 1);
|
||||
}
|
||||
}
|
||||
return valueMap;
|
||||
});
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import java.security.MessageDigest;
|
||||
|
||||
public class PluginJarHashProvider {
|
||||
|
||||
protected URL jarURL;
|
||||
protected final URL jarURL;
|
||||
|
||||
public PluginJarHashProvider(URL jarURL) {
|
||||
this.jarURL = jarURL;
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import lombok.Getter;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
|
||||
@Getter
|
||||
public abstract class StatsManager {
|
||||
|
||||
Metrics metrics;
|
||||
|
||||
public Metrics getMetrics() {
|
||||
return metrics;
|
||||
public StatsManager(Metrics metrics) {
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
public void init() {
|
||||
throw new IllegalStateException("Empty stats class!");
|
||||
Base.INSTANCE.getScheduler().runTaskAsynchronously(() -> {
|
||||
BuildTypePie.determineBuildType(); // Function to calculate hash
|
||||
metrics.addCustomChart(new PlayerVersionsPie());
|
||||
metrics.addCustomChart(new BuildTypePie());
|
||||
metrics.addCustomChart(new ClientBrandsPie());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
package me.caseload.knockbacksync.util;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class ChatUtil {
|
||||
|
||||
public static @NotNull String translateAlternateColorCodes(char altColorChar, @NotNull String textToTranslate) {
|
||||
Preconditions.checkArgument(textToTranslate != null, "Cannot translate null text");
|
||||
char[] b = textToTranslate.toCharArray();
|
||||
@@ -21,36 +18,4 @@ public class ChatUtil {
|
||||
|
||||
return new String(b);
|
||||
}
|
||||
|
||||
public static String getPingMessage(UUID senderUUID, UUID targetUUID) {
|
||||
|
||||
String noun = "";
|
||||
PlayerData playerData = null;
|
||||
if (senderUUID == null) {
|
||||
senderUUID = targetUUID;
|
||||
}
|
||||
|
||||
if (senderUUID.equals(targetUUID) || targetUUID == null) {
|
||||
playerData = PlayerDataManager.getPlayerData(senderUUID);
|
||||
if (playerData == null) {
|
||||
return ChatUtil.translateAlternateColorCodes('&', "&cKnockback synchronization is currently disabled for you!");
|
||||
}
|
||||
noun = "Your";
|
||||
} else {
|
||||
playerData = PlayerDataManager.getPlayerData(targetUUID);
|
||||
if (playerData == null) {
|
||||
return ChatUtil.translateAlternateColorCodes('&', "&cKnockback synchronization is currently disabled for the target player.");
|
||||
}
|
||||
noun = playerData.getPlatformPlayer().getName() + "'s";
|
||||
}
|
||||
|
||||
|
||||
String rawReturnString = null;
|
||||
if (playerData.getPing() == null) {
|
||||
rawReturnString = String.format("Pong not received. %s estimated ping is &b" + playerData.getPlatformPlayer().getPing() + "&rms.", noun);
|
||||
} else {
|
||||
rawReturnString = String.format("%s last ping packet took &b %.3f&rms. Jitter: &b%.3f&rms.", noun, playerData.getPing(), playerData.getJitter());
|
||||
}
|
||||
return ChatUtil.translateAlternateColorCodes('&', rawReturnString);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package me.caseload.knockbacksync.util;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.util.reflection.Reflection;
|
||||
import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
@@ -19,18 +19,9 @@ public class GeyserUtil {
|
||||
public static boolean isGeyserPlayer(UUID uuid) {
|
||||
if (!CHECKED_FOR_GEYSER) {
|
||||
try {
|
||||
switch (KnockbackSyncBase.INSTANCE.platform) {
|
||||
case BUKKIT:
|
||||
case FOLIA:
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_CLASS = classLoader.loadClass("org.geysermc.api.Geyser");
|
||||
break;
|
||||
case FABRIC:
|
||||
GEYSER_CLASS = Class.forName("org.geysermc.api.Geyser");
|
||||
GEYSER_PRESENT = true;
|
||||
break;
|
||||
}
|
||||
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_CLASS = classLoader.loadClass("org.geysermc.api.Geyser");
|
||||
GEYSER_PRESENT = true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
GEYSER_PRESENT = false;
|
||||
}
|
||||
@@ -40,17 +31,8 @@ public class GeyserUtil {
|
||||
if (GEYSER_PRESENT) {
|
||||
if (GEYSER_API_CLASS == null) {
|
||||
try {
|
||||
switch (KnockbackSyncBase.INSTANCE.platform) {
|
||||
case BUKKIT:
|
||||
case FOLIA:
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_API_CLASS = classLoader.loadClass("org.geysermc.api.GeyserApiBase");
|
||||
break;
|
||||
case FABRIC:
|
||||
GEYSER_CLASS = Class.forName("org.geysermc.api.GeyserApiBase");
|
||||
GEYSER_PRESENT = true;
|
||||
break;
|
||||
}
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_API_CLASS = classLoader.loadClass("org.geysermc.api.GeyserApiBase");
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Legacy (Minecraft 1.8) melee knockback formula.
|
||||
*
|
||||
* This file is a port of the knockback calculation from BukkitOldCombatMechanics
|
||||
* (kernitus/BukkitOldCombatMechanics), module ModulePlayerKnockback, which is
|
||||
* licensed under the Mozilla Public License, v. 2.0:
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*
|
||||
* The MPL-2.0 does not carry the "Incompatible With Secondary Licenses" notice
|
||||
* (Exhibit B), so per MPL-2.0 §3.3 this Covered Software may be distributed as
|
||||
* part of a Larger Work under the GNU General Public License v3.0-or-later that
|
||||
* governs the rest of KnockbackSync. The terms of the MPL continue to apply to
|
||||
* this file. See the NOTICE file at the project root for attribution details.
|
||||
*/
|
||||
package me.caseload.knockbacksync.util;
|
||||
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
|
||||
/**
|
||||
* Computes the exact 1.8-style melee knockback vector applied to a victim, so that
|
||||
* KnockbackSync can own the final melee velocity (horizontal + vertical) and then
|
||||
* latency-correct it, rather than letting vanilla knockback win.
|
||||
*
|
||||
* <p>The math is a faithful reproduction of OldCombatMechanics' legacy player
|
||||
* knockback so that values are identical to running OCM's old-player-knockback
|
||||
* module, while KnockbackSync remains the single writer of the velocity.</p>
|
||||
*/
|
||||
public final class LegacyKnockback {
|
||||
|
||||
private LegacyKnockback() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param victim the player receiving knockback
|
||||
* @param attacker the attacking player
|
||||
* @param victimData the victim's tracked data (for knockback resistance attribute)
|
||||
* @param config the plugin configuration (legacy knockback tunables)
|
||||
* @return the 1.8-style velocity to apply to the victim, before latency Y-correction
|
||||
*/
|
||||
public static Vector3d compute(PlatformPlayer victim, PlatformPlayer attacker,
|
||||
PlayerData victimData, ConfigManager config) {
|
||||
final double knockbackHorizontal = config.getLegacyKnockbackHorizontal();
|
||||
final double knockbackVertical = config.getLegacyKnockbackVertical();
|
||||
final double knockbackVerticalLimit = config.getLegacyKnockbackVerticalLimit();
|
||||
final double knockbackExtraHorizontal = config.getLegacyKnockbackExtraHorizontal();
|
||||
final double knockbackExtraVertical = config.getLegacyKnockbackExtraVertical();
|
||||
final boolean netheriteKnockbackResistance = config.isLegacyKnockbackResistanceEnabled();
|
||||
|
||||
// Figure out base knockback direction (attacker -> victim) with vanilla jitter
|
||||
// when the two are stacked on the exact same column.
|
||||
double d0 = attacker.getX() - victim.getX();
|
||||
double d1;
|
||||
for (d1 = attacker.getZ() - victim.getZ(); d0 * d0 + d1 * d1 < 1.0E-4D;
|
||||
d1 = (Math.random() - Math.random()) * 0.01D) {
|
||||
d0 = (Math.random() - Math.random()) * 0.01D;
|
||||
}
|
||||
|
||||
final double magnitude = Math.sqrt(d0 * d0 + d1 * d1);
|
||||
|
||||
// Player velocity before any friction is applied (pre-knockback motion).
|
||||
final Vector3d v = victim.getVelocity();
|
||||
|
||||
// Apply friction (halve), then add base knockback.
|
||||
double vx = (v.getX() / 2) - (d0 / magnitude * knockbackHorizontal);
|
||||
double vy = (v.getY() / 2) + knockbackVertical;
|
||||
double vz = (v.getZ() / 2) - (d1 / magnitude * knockbackHorizontal);
|
||||
|
||||
// Bonus knockback for sprinting and the Knockback enchantment.
|
||||
int bonusKnockback = attacker.getWeaponKnockbackLevel();
|
||||
if (attacker.isSprinting()) {
|
||||
bonusKnockback++;
|
||||
}
|
||||
|
||||
// NOTE: vanilla caps vertical BEFORE adding the sprint/enchant bonus vertical.
|
||||
if (vy > knockbackVerticalLimit) {
|
||||
vy = knockbackVerticalLimit;
|
||||
}
|
||||
|
||||
if (bonusKnockback > 0) {
|
||||
final float yaw = attacker.getYaw();
|
||||
vx += -Math.sin(yaw * 3.1415927F / 180.0F) * (float) bonusKnockback * knockbackExtraHorizontal;
|
||||
vy += knockbackExtraVertical;
|
||||
vz += Math.cos(yaw * 3.1415927F / 180.0F) * (float) bonusKnockback * knockbackExtraHorizontal;
|
||||
}
|
||||
|
||||
if (netheriteKnockbackResistance) {
|
||||
// Each piece of netherite armour yields 10% horizontal resistance.
|
||||
final double resistance = 1 - victimData.getKnockbackResistanceAttribute();
|
||||
vx *= resistance;
|
||||
vz *= resistance;
|
||||
}
|
||||
|
||||
return new Vector3d(vx, vy, vz);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,24 @@
|
||||
package me.caseload.knockbacksync.util;
|
||||
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
|
||||
public class MathUtil {
|
||||
|
||||
private static final double TERMINAL_VELOCITY = 3.92;
|
||||
private static final double MULTIPLIER = 0.98;
|
||||
private static final int MAX_TICKS = 20;
|
||||
private static final int MAX_TICKS = 30;
|
||||
|
||||
public static double getCompensatedVerticalVelocity(double velocity, double acceleration, int ticks) {
|
||||
while (ticks > 0) {
|
||||
velocity -= acceleration;
|
||||
velocity *= MULTIPLIER;
|
||||
ticks--;
|
||||
}
|
||||
|
||||
return velocity;
|
||||
}
|
||||
|
||||
public static double calculateDistanceTraveled(double velocity, int time, double acceleration) {
|
||||
double totalDistance = 0;
|
||||
@@ -36,17 +50,20 @@ public class MathUtil {
|
||||
return ticks;
|
||||
}
|
||||
|
||||
public static int calculateTimeToMaxVelocity(double targetVerticalVelocity, double acceleration) {
|
||||
double a = -acceleration * MULTIPLIER;
|
||||
double b = acceleration + TERMINAL_VELOCITY * MULTIPLIER;
|
||||
double c = -2 * targetVerticalVelocity;
|
||||
public static int calculateTimeToMaxVelocity(double velocity, double acceleration) {
|
||||
int ticks = 0;
|
||||
|
||||
double discriminant = b * b - 4 * a * c;
|
||||
if (discriminant < 0)
|
||||
return 0;
|
||||
while (velocity > 0) {
|
||||
if (ticks > MAX_TICKS)
|
||||
return -1;
|
||||
|
||||
double positiveRoot = (-b + Math.sqrt(discriminant)) / (2 * a);
|
||||
return (int) Math.ceil(positiveRoot * 20);
|
||||
velocity -= acceleration;
|
||||
velocity = Math.min(velocity, TERMINAL_VELOCITY);
|
||||
velocity *= MULTIPLIER;
|
||||
ticks++;
|
||||
}
|
||||
|
||||
return ticks;
|
||||
}
|
||||
|
||||
public static double clamp(double num, double min, double max) {
|
||||
|
||||
@@ -9,8 +9,7 @@ public class NumberConversions {
|
||||
} else {
|
||||
try {
|
||||
return Long.parseLong(object.toString());
|
||||
} catch (NumberFormatException var2) {
|
||||
} catch (NullPointerException var3) {
|
||||
} catch (NumberFormatException | NullPointerException ignored) {
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
@@ -23,8 +22,7 @@ public class NumberConversions {
|
||||
} else {
|
||||
try {
|
||||
return Integer.parseInt(object.toString());
|
||||
} catch (NumberFormatException var2) {
|
||||
} catch (NullPointerException var3) {
|
||||
} catch (NumberFormatException | NullPointerException ignored) {
|
||||
}
|
||||
|
||||
return def;
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package me.caseload.knockbacksync.util.data;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
public class Pair<A, B> {
|
||||
private final A first;
|
||||
private final B second;
|
||||
@@ -15,14 +18,6 @@ public class Pair<A, B> {
|
||||
return new Pair<T, K>(a, b);
|
||||
}
|
||||
|
||||
public A getFirst() {
|
||||
return first;
|
||||
}
|
||||
|
||||
public B getSecond() {
|
||||
return second;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof Pair)) {
|
||||
|
||||
@@ -10,18 +10,5 @@ public interface PlatformServer {
|
||||
|
||||
PlatformPlayer getPlayer(UUID uuid);
|
||||
|
||||
// switch (KnockbackSyncBase.INSTANCE.platform) {
|
||||
// case BUKKIT:
|
||||
// case FOLIA:
|
||||
// return Bukkit.getOnlinePlayers().stream()
|
||||
// .map(BukkitPlayer::new)
|
||||
// .collect(Collectors.toList());
|
||||
// case FABRIC:
|
||||
// MinecraftServer server = (MinecraftServer) FabricLoader.getInstance().getGameInstance();
|
||||
// return server.getPlayerList().getPlayers().stream()
|
||||
// .map(FabricPlayer::new)
|
||||
// .collect(Collectors.toList());
|
||||
// default:
|
||||
// throw new IllegalStateException("Unexpected platform: " + KnockbackSyncBase.INSTANCE.platform);
|
||||
// }
|
||||
PlatformPlayer getPlayer(Object nativePlatformPlayer);
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
# KnockbackSync Configuration #
|
||||
#########################################
|
||||
|
||||
# Do not modify!
|
||||
config_version: 9
|
||||
|
||||
# Plugin enabled state
|
||||
# Toggleable using /knockbacksync toggle
|
||||
# Required permission: knockbacksync.toggle
|
||||
@@ -11,6 +14,10 @@ enabled: true
|
||||
# Required permission: knockbacksync.update
|
||||
notify_updates: true
|
||||
|
||||
# Automatically updates the plugin
|
||||
# Only servers with restart compatibility can use this feature
|
||||
auto_update: false
|
||||
|
||||
# Grabs the ping of combat-tagged players every x ticks
|
||||
# Disabling this may lead to inaccuracies in calculations
|
||||
runnable:
|
||||
@@ -23,19 +30,236 @@ runnable:
|
||||
# the threshold, the previous ping value is used to avoid calculation inaccuracies.
|
||||
spike_threshold: 20
|
||||
|
||||
enable_experimental_offground: false
|
||||
# OPTIONS: PING, TRANSACTION (aliases), KEEPALIVE. PING is safe (vanilla ignores unexpected pongs, ViaVersion translates for 1.8-1.16, ± 5ms); KEEPALIVE is slightly more precise but any unintercepted echo kicks ("Timed out") on 1.20.2+ and anticheat NET checks may kick for the extra traffic.
|
||||
ping_strategy: "PING"
|
||||
|
||||
enable_message: "&aSuccessfully enabled KnockbackSync."
|
||||
disable_message: "&cSuccessfully disabled KnockbackSync."
|
||||
player_enable_message: "&aSuccessfully enabled KnockbackSync for %player%."
|
||||
player_disable_message: "&aSuccessfully &cdisabled &aKnockbackSync for %player%."
|
||||
player_ineligible_message: "&c%player% is ineligible for KnockbackSync. If you believe this is an error, please open an issue on the github page."
|
||||
reload_message: "&aSuccessfully reloaded KnockbackSync config."
|
||||
global_status_message: "&eGlobal KnockbackSync status: "
|
||||
player_status_message: "&e%player%'s KnockbackSync status: "
|
||||
player_disabled_global_message: "&cDisabled (Global toggle is off)"
|
||||
enable_experimental_offground_message: "&aSuccessfully enabled offground experiment."
|
||||
disable_experimental_offground_message: "&cSuccessfully disabled offground experiment."
|
||||
# Whether to try to detect when player is offground and apply less kb
|
||||
enable_offground_synchronization: true
|
||||
|
||||
# Read FAQ!
|
||||
ping_offset: 25
|
||||
# Legacy (1.8) melee knockback.
|
||||
# When enabled, KnockbackSync computes the exact 1.8 player-vs-player knockback
|
||||
# (horizontal + vertical) itself and becomes the single owner of melee velocity,
|
||||
# then latency-syncs it as usual. This reproduces OldCombatMechanics'
|
||||
# old-player-knockback values for ALL clients 1.8+ while keeping them synced.
|
||||
#
|
||||
# IMPORTANT: if you enable this, DISABLE OldCombatMechanics' old-player-knockback
|
||||
# module (remove it from the active modeset). Running both at once makes two
|
||||
# plugins fight over PlayerVelocityEvent. KnockbackSync owns the velocity here.
|
||||
# OCM can still provide its other features (attack cooldown removal, etc.).
|
||||
legacy_knockback:
|
||||
enabled: true # Master toggle for legacy knockback
|
||||
horizontal: 0.4 # Base horizontal knockback (OCM: knockback-horizontal)
|
||||
vertical: 0.4 # Base vertical knockback (OCM: knockback-vertical)
|
||||
vertical_limit: 0.4 # Vertical cap before sprint/enchant bonus (OCM: knockback-vertical-limit)
|
||||
extra_horizontal: 0.5 # Bonus horizontal per sprint/Knockback level (OCM: knockback-extra-horizontal)
|
||||
extra_vertical: 0.1 # Bonus vertical when sprint/Knockback applies (OCM: knockback-extra-vertical)
|
||||
# When false (default, matching OCM), netherite/armour knockback resistance is
|
||||
# ignored so the velocity event always fires and full 1.8 knockback is applied.
|
||||
# When true, horizontal knockback is reduced by the victim's resistance attribute.
|
||||
#
|
||||
# Scope of the false setting:
|
||||
# - Melee PvP: LegacyKnockback already ignores resistance (it owns the velocity).
|
||||
# - Projectile PvP (bow/arrow, trident, and snowball/egg/ender pearl once
|
||||
# OldCombatMechanics' projectile-knockback gives them damage): KnockbackSync
|
||||
# temporarily nullifies the victim's knockback-resistance attribute for the hit
|
||||
# so vanilla applies full knockback, then restores it (PvE is unaffected).
|
||||
# - Fishing-rod PvP: owned by OCM old-fishing-knockback + the rod API (already 1.8).
|
||||
# - Explosions are NOT affected by knockback resistance on 1.19.4, so they are
|
||||
# out of scope here.
|
||||
# Ownership: KnockbackSync owns player knockback; keep OCM's old-player-knockback
|
||||
# module DISABLED (see the IMPORTANT note above).
|
||||
enable_knockback_resistance: false
|
||||
|
||||
# This is the rate the server will use for (amongst other things) sending packets about entities to players
|
||||
# In other words it defines how often clients get updated velocity for other entities in the world
|
||||
# Note that certain events mark velocity as dirty and causes it to be immediately updated for 1 tick regardless of the tick interval
|
||||
# These include but are not limited to jumping, taking knockback, swimming, and a target entity being affected by a special mob attack
|
||||
# Such as the Ender Dragon's knockback attacks
|
||||
# If an entity below doesn't exist in the version of the game your server is running in, changing the config for it will do nothing
|
||||
# Currently only modifying the player's tick interval is supported on Bukkit/Spigot/Paper + Folia
|
||||
# Modifying the tick interval of any entity is supported on Fabric.
|
||||
entity_tick_intervals:
|
||||
player: 2 # This is 2 by default in vanilla and paper, change to 1 to test out the new feature
|
||||
allay: 2
|
||||
area_effect_cloud: Integer.MAX_VALUE
|
||||
armadillo: 3
|
||||
armor_stand: 3
|
||||
arrow: 20
|
||||
axolotl: 3
|
||||
bat: 3
|
||||
bee: 3
|
||||
blaze: 3
|
||||
block_display: 1
|
||||
boat: 3
|
||||
bogged: 3
|
||||
breeze: 3
|
||||
breeze_wind_charge: 10
|
||||
camel: 3
|
||||
cat: 3
|
||||
cave_spider: 3
|
||||
chest_boat: 3
|
||||
chest_minecart: 3
|
||||
chicken: 3
|
||||
cod: 3
|
||||
command_block_minecart: 3
|
||||
cow: 3
|
||||
creeper: 3
|
||||
dolphin: 3
|
||||
donkey: 3
|
||||
dragon_fireball: 10
|
||||
drowned: 3
|
||||
egg: 10
|
||||
elder_guardian: 3
|
||||
end_crystal: Integer.MAX_VALUE
|
||||
ender_dragon: 3
|
||||
ender_pearl: 10
|
||||
enderman: 3
|
||||
endermite: 3
|
||||
evoker: 3
|
||||
evoker_fangs: 2
|
||||
experience_bottle: 10
|
||||
experience_orb: 20
|
||||
eye_of_ender: 4
|
||||
falling_block: 20
|
||||
firework_rocket: 10
|
||||
fox: 3
|
||||
frog: 3
|
||||
furnace_minecart: 3
|
||||
ghast: 3
|
||||
giant: 3
|
||||
glow_item_frame: Integer.MAX_VALUE
|
||||
glow_squid: 3
|
||||
goat: 3
|
||||
guardian: 3
|
||||
hoglin: 3
|
||||
hopper_minecart: 3
|
||||
horse: 3
|
||||
husk: 3
|
||||
illusioner: 3
|
||||
interaction: 3
|
||||
iron_golem: 3
|
||||
item: 20
|
||||
item_display: 1
|
||||
item_frame: Integer.MAX_VALUE
|
||||
ominous_item_spawner: 3
|
||||
fireball: 10
|
||||
leash_knot: Integer.MAX_VALUE
|
||||
lightning_bolt: Integer.MAX_VALUE
|
||||
llama: 3
|
||||
llama_spit: 10
|
||||
magma_cube: 3
|
||||
marker: 3
|
||||
minecart: 3
|
||||
mooshroom: 3
|
||||
mule: 3
|
||||
ocelot: 3
|
||||
painting: Integer.MAX_VALUE
|
||||
panda: 3
|
||||
parrot: 3
|
||||
phantom: 3
|
||||
pig: 3
|
||||
piglin: 3
|
||||
piglin_brute: 3
|
||||
pillager: 3
|
||||
polar_bear: 3
|
||||
potion: 10
|
||||
pufferfish: 3
|
||||
rabbit: 3
|
||||
ravager: 3
|
||||
salmon: 3
|
||||
sheep: 3
|
||||
shulker: 3
|
||||
shulker_bullet: 3
|
||||
silverfish: 3
|
||||
skeleton: 3
|
||||
skeleton_horse: 3
|
||||
slime: 3
|
||||
small_fireball: 10
|
||||
sniffer: 3
|
||||
snow_golem: 3
|
||||
snowball: 10
|
||||
spawner_minecart: 3
|
||||
spectral_arrow: 20
|
||||
spider: 3
|
||||
squid: 3
|
||||
stray: 3
|
||||
strider: 3
|
||||
tadpole: 3
|
||||
text_display: 1
|
||||
tnt: 10
|
||||
tnt_minecart: 3
|
||||
trader_llama: 3
|
||||
trident: 20
|
||||
tropical_fish: 3
|
||||
turtle: 3
|
||||
vex: 3
|
||||
villager: 3
|
||||
vindicator: 3
|
||||
wandering_trader: 3
|
||||
warden: 3
|
||||
wind_charge: 10
|
||||
witch: 3
|
||||
wither: 3
|
||||
wither_skeleton: 3
|
||||
wither_skull: 10
|
||||
wolf: 3
|
||||
zoglin: 3
|
||||
zombie: 3
|
||||
zombie_horse: 3
|
||||
zombie_villager: 3
|
||||
zombified_piglin: 3
|
||||
fishing_bobber: 5
|
||||
|
||||
messages:
|
||||
toggle:
|
||||
global:
|
||||
enable: "&aSuccessfully enabled KnockbackSync."
|
||||
disable: "&cSuccessfully disabled KnockbackSync."
|
||||
player:
|
||||
enable: "&aSuccessfully enabled KnockbackSync for %player%."
|
||||
disable: "&aSuccessfully &cdisabled &aKnockbackSync for %player%."
|
||||
ineligible: "&c%player% is ineligible for KnockbackSync. If you believe this is in error, please contact your server administrators."
|
||||
disconnected-while-executing-command: "&c%player% disconnected while executing command."
|
||||
permission:
|
||||
no_global: "&cYou don't have permission to toggle the global setting."
|
||||
no_self: "&cYou do not have permission to toggle your knockback."
|
||||
no_other: "&cYou do not have permission to toggle the knockback of other player's."
|
||||
self:
|
||||
enable: "&aSuccessfully enabled KnockbackSync."
|
||||
disable: "&cSuccessfully disabled KnockbackSync."
|
||||
other:
|
||||
enable: "&aSuccessfully enabled KnockbackSync for %player%."
|
||||
disable: "&aSuccessfully &cdisabled &aKnockbackSync for %player%."
|
||||
ineligible: "&c%player% is ineligible for KnockbackSync. If you believe this is in error, please contact your server administrators."
|
||||
server_disabled: "&cKnockbacksync is currently disabled on this server. Contact your server administrator for more information."
|
||||
offground:
|
||||
enable: "&aSuccessfully enabled offground synchronization."
|
||||
disable: "&cSuccessfully disabled offground synchronization."
|
||||
reload:
|
||||
success: "&aSuccessfully reloaded KnockbackSync."
|
||||
status:
|
||||
global:
|
||||
enabled: "&eKnockbackSync global status: &aEnabled"
|
||||
disabled: "&eKnockbackSync global status: &cDisabled"
|
||||
offground:
|
||||
enabled: "&eKnockbackSync off-ground status: &aEnabled"
|
||||
disabled: "&eKnockbackSync off-ground status: &cDisabled"
|
||||
player:
|
||||
enabled: "&e%player%'s KnockbackSync status: &aEnabled"
|
||||
disabled: "&e%player%'s KnockbackSync status: &cDisabled"
|
||||
global_disabled: "&e%player%'s KnockbackSync status: &cDisabled (Global toggle is off)"
|
||||
permission:
|
||||
no_self: "&cYou do not have permission to check your knockbacksync status."
|
||||
no_other: "&cYou do not have permission to check the status of other players!"
|
||||
console:
|
||||
must_specify_player: "&cYou must specify a player to use the knockbacksync ping command from the console."
|
||||
disabled:
|
||||
self: "&cKnockback synchronization is currently disabled for you!"
|
||||
target: "&cKnockback synchronization is currently disabled for the target player."
|
||||
ping:
|
||||
self:
|
||||
unavailable: "Accurate ping unavailable. Your estimated ping is &b%ping%&rms."
|
||||
available: "Your real ping is &b%ping%&rms. Jitter: &b%jitter%&rms. Spike: &b%spike%&r. Compensated ping: &b%compensated%&rms."
|
||||
other:
|
||||
unavailable: "Accurate ping unavailable. %player%'s estimated ping is &b%ping%&rms."
|
||||
available: "%player%'s real ping is &b%ping%&rms. Jitter: &b%jitter%&rms. Spike: &b%spike%&r. Compensated ping: &b%compensated%&rms."
|
||||
@@ -1,118 +0,0 @@
|
||||
plugins {
|
||||
id("fabric-loom")
|
||||
id("com.gradleup.shadow")
|
||||
}
|
||||
|
||||
base {
|
||||
archivesName.set("${rootProject.property("archives_base_name")}-fabric")
|
||||
}
|
||||
|
||||
val shadeThisThing: Configuration by configurations.creating {
|
||||
isCanBeConsumed = true
|
||||
isTransitive = true
|
||||
}
|
||||
|
||||
//sourceSets {
|
||||
// main {
|
||||
// java {
|
||||
// srcDir(project(":common").sourceSets.main.get().java.srcDirs)
|
||||
// }
|
||||
// resources {
|
||||
// srcDir(project(":common").sourceSets.main.get().resources.srcDirs)
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
// TODO migrate to only including sourceset for compile, test and javadoc tasks
|
||||
// Currently must build with gradle build -x test to skip test
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
source(project(":common").sourceSets.main.get().allSource)
|
||||
}
|
||||
|
||||
tasks.withType<Javadoc>().configureEach {
|
||||
source(project(":common").sourceSets.main.get().allJava)
|
||||
}
|
||||
|
||||
tasks.named<JavaCompile>("compileTestJava") {
|
||||
exclude("**/*")
|
||||
}
|
||||
|
||||
//tasks.withType<Test>().configureEach {
|
||||
// classpath += project(":common").sourceSets["main"].output + configurations["testRuntimeClasspath"]
|
||||
//}
|
||||
|
||||
//tasks.named<Jar>("sourcesJar") {
|
||||
// from(project(":common").sourceSets.main.get().allSource)
|
||||
//}
|
||||
|
||||
tasks.jar {
|
||||
// from(project(":common").sourceSets.named("main").get().output)
|
||||
// from(project(":common").sourceSets.main.get().resources)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":common"))
|
||||
|
||||
minecraft("com.mojang:minecraft:${rootProject.property("minecraft_version")}")
|
||||
mappings(loom.layered {
|
||||
officialMojangMappings()
|
||||
parchment("org.parchmentmc.data:parchment-1.21:${rootProject.property("parchment_mappings")}")
|
||||
})
|
||||
modImplementation("net.fabricmc:fabric-loader:${rootProject.property("loader_version")}")
|
||||
modImplementation("net.fabricmc.fabric-api:fabric-api:${rootProject.property("fabric_version")}")
|
||||
|
||||
include(modImplementation("me.lucko:fabric-permissions-api:0.3.1")!!)
|
||||
include(modImplementation("com.github.retrooper:packetevents-fabric:2.5.8-SNAPSHOT")!!)
|
||||
|
||||
shadeThisThing(implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")!!)
|
||||
shadeThisThing(implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")!!)
|
||||
shadeThisThing(implementation("org.kohsuke:github-api:1.326")!!)
|
||||
|
||||
// include(implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")!!)
|
||||
// include(implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")!!)
|
||||
// include(implementation("org.kohsuke:github-api:1.326")!!)
|
||||
|
||||
// include(implementation("org.kohsuke:github-api:1.326") {
|
||||
// exclude(group = "commons-io", module = "commons-io")
|
||||
// exclude(group = "org.apache.commons", module = "commons-lang3")
|
||||
// })
|
||||
|
||||
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
|
||||
compileOnly("org.projectlombok:lombok:1.18.34")
|
||||
annotationProcessor("org.projectlombok:lombok:1.18.34")
|
||||
}
|
||||
|
||||
tasks.shadowJar {
|
||||
archiveClassifier.set("dev")
|
||||
configurations = listOf(shadeThisThing)
|
||||
isEnableRelocation = true
|
||||
relocationPrefix = "${project.property("maven_group")}.${project.property("archives_base_name")}.shaded"
|
||||
finalizedBy(tasks.remapJar)
|
||||
}
|
||||
tasks.remapJar {
|
||||
archiveClassifier.set(null as String?)
|
||||
dependsOn(tasks.shadowJar)
|
||||
inputFile = tasks.shadowJar.get().archiveFile
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
from(project(":common").sourceSets.main.get().resources)
|
||||
|
||||
inputs.property("version", project.version)
|
||||
inputs.property("minecraft_version", rootProject.property("minecraft_version"))
|
||||
inputs.property("loader_version", rootProject.property("loader_version"))
|
||||
filteringCharset = "UTF-8"
|
||||
|
||||
filesMatching("fabric.mod.json") {
|
||||
expand(
|
||||
"version" to project.version,
|
||||
"minecraft_version" to rootProject.property("minecraft_version"),
|
||||
"loader_version" to rootProject.property("loader_version")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import me.caseload.knockbacksync.world.KBSyncFabricBase;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
public class KBSyncFabricLoaderMod implements PreLaunchEntrypoint, ModInitializer {
|
||||
|
||||
// private static MinecraftServer SERVER;
|
||||
|
||||
private final KnockbackSyncBase core = new KBSyncFabricBase();
|
||||
|
||||
public static MinecraftServer getServer() {
|
||||
return (MinecraftServer) FabricLoader.getInstance().getGameInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPreLaunch() {
|
||||
core.load();
|
||||
// ServerLifecycleEvents.SERVER_STARTING.register((minecraftServer -> {
|
||||
// SERVER = minecraftServer;
|
||||
// core.initializeScheduler();
|
||||
// core.configManager.loadConfig(false);
|
||||
// core.statsManager.init();
|
||||
// core.checkForUpdates();
|
||||
// }));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInitialize() {
|
||||
core.enable();
|
||||
core.initializeScheduler();
|
||||
core.configManager.loadConfig(false);
|
||||
core.statsManager.init();
|
||||
core.checkForUpdates();
|
||||
ServerLifecycleEvents.SERVER_STOPPING.register((server) -> {
|
||||
core.scheduler.shutdown();
|
||||
core.statsManager.getMetrics().shutdown();
|
||||
});
|
||||
|
||||
// SenderFactory<KnockbackSyncBase, FabricCommandSource> fabricSenderFactory = new FabricSenderFactory(null);
|
||||
// LiteralArgumentBuilder<FabricCommandSource> fabricCommand = ReloadSubCommand.build(fabricSenderFactory);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package me.caseload.knockbacksync.callback;
|
||||
|
||||
import net.fabricmc.fabric.api.event.Event;
|
||||
import net.fabricmc.fabric.api.event.EventFactory;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public interface PlayerVelocityEvent {
|
||||
Event<PlayerVelocityEvent> EVENT = EventFactory.createArrayBacked(PlayerVelocityEvent.class,
|
||||
(listeners) -> (player, velocity) -> {
|
||||
for (PlayerVelocityEvent listener : listeners) {
|
||||
InteractionResult result = listener.onVelocityChange(player, velocity);
|
||||
|
||||
if (result != InteractionResult.PASS) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return InteractionResult.PASS;
|
||||
});
|
||||
|
||||
InteractionResult onVelocityChange(ServerPlayer player, Vec3 velocity);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package me.caseload.knockbacksync.callback;
|
||||
|
||||
import net.fabricmc.fabric.api.event.Event;
|
||||
import net.fabricmc.fabric.api.event.EventFactory;
|
||||
|
||||
public interface TickRateChangeEvent {
|
||||
Event<TickRateChangeEvent> EVENT = EventFactory.createArrayBacked(TickRateChangeEvent.class,
|
||||
(listeners) -> (oldTickRate, newTickRate) -> {
|
||||
for (TickRateChangeEvent listener : listeners) {
|
||||
listener.onTickRateChange(oldTickRate, newTickRate);
|
||||
}
|
||||
});
|
||||
|
||||
void onTickRateChange(float oldTickRate, float newTickRate);
|
||||
}
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user