BlueGit

timfa birdcourier

Initial import of BirdCourier 1.1.3

Paper 26.2 plugin source plus Gradle and BlueGit CI, following the
copperfarmer/containerpipes layout.

timfa Grok Bot · pushed by timfa

Authored 2026-11-17 · 8 hours ago

Hash
2a19b3da63c57609470f004558ab1bd6c29f5ae5
Pipeline
Passed
14 files changed +2030 −0
.gitignore added +7 −0
@@ -0,0 +1,7 @@
1 version.env
2 package.env
3 .gradle/
4 build/
5 *.iml
6 .idea/
7 out/
@@ -0,0 +1,7 @@
1version.env
2package.env
3.gradle/
4build/
5*.iml
6.idea/
7out/
.gitlab-ci.yml added +117 −0
@@ -0,0 +1,117 @@
1 # Release pipeline: runs when a version tag is created (e.g. v1.8.0 or 1.8.0).
2 #
3 # Required CI/CD variable:
4 # CI_PUSH_TOKEN — Project Access Token (Maintainer) with scopes:
5 # `write_repository`, `self_rotate` (or `api`), and `api`
6 # (api is required to write the rotated token back to this variable).
7 #
8 # Flow:
9 # 1. validate — reject invalid or non-increasing versions
10 # 2. bump — update version in project files and push commit (ci.skip; tag unchanged)
11 # 3. build — produce BirdCourier-<version>.jar and upload to Package Registry
12 # 4. release — publish a GitLab Release with the jar attached
13 # 5. rotate-token — self-rotate CI_PUSH_TOKEN and update the CI/CD variable
14
15 workflow:
16 rules:
17 - if: $CI_COMMIT_TAG
18
19 variables:
20 GIT_DEPTH: "0"
21 GIT_FETCH_EXTRA_FLAGS: "--tags"
22 GRADLE_OPTS: "-Dorg.gradle.daemon=false"
23
24 stages:
25 - validate
26 - bump
27 - build
28 - release
29 - rotate
30
31 .validate_image:
32 image: alpine:3.20
33 before_script:
34 - apk add --no-cache bash git grep coreutils
35 - git fetch --tags --force origin
36 - chmod +x scripts/release.sh
37
38 validate:version:
39 extends: .validate_image
40 stage: validate
41 script:
42 - ./scripts/release.sh validate
43 artifacts:
44 reports:
45 dotenv: version.env
46 paths:
47 - version.env
48
49 bump:version:
50 extends: .validate_image
51 stage: bump
52 needs:
53 - job: validate:version
54 artifacts: true
55 script:
56 - ./scripts/release.sh bump
57 artifacts:
58 reports:
59 dotenv: version.env
60 paths:
61 - version.env
62 - build.gradle.kts
63 - src/main/resources/plugin.yml
64 - README.md
65 - src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
66
67 build:jar:
68 stage: build
69 image: gradle:jdk25
70 needs:
71 - job: bump:version
72 artifacts: true
73 before_script:
74 - apt-get update -qq && apt-get install -y -qq curl >/dev/null
75 - chmod +x scripts/release.sh
76 script:
77 - test -n "${VERSION}"
78 - gradle --no-daemon clean jar
79 - test -f "build/libs/BirdCourier-${VERSION}.jar"
80 - ls -la "build/libs/BirdCourier-${VERSION}.jar"
81 - ./scripts/release.sh upload
82 artifacts:
83 reports:
84 dotenv: version.env
85 paths:
86 - "build/libs/BirdCourier-*.jar"
87 - version.env
88 expire_in: 30 days
89
90 release:gitlab:
91 stage: release
92 image: registry.gitlab.com/gitlab-org/release-cli:latest
93 needs:
94 - job: build:jar
95 artifacts: true
96 script:
97 - echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"
98 release:
99 name: "BirdCourier $VERSION"
100 tag_name: "$TAG"
101 description: "Release $VERSION of BirdCourier."
102 assets:
103 links:
104 - name: "BirdCourier-$VERSION.jar"
105 url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/birdcourier/$VERSION/BirdCourier-$VERSION.jar"
106 link_type: package
107
108 rotate:push-token:
109 image: alpine:3.20
110 stage: rotate
111 needs:
112 - job: release:gitlab
113 before_script:
114 - apk add --no-cache bash curl jq coreutils
115 - chmod +x scripts/release.sh
116 script:
117 - ./scripts/release.sh rotate-token
@@ -0,0 +1,117 @@
1# Release pipeline: runs when a version tag is created (e.g. v1.8.0 or 1.8.0).
2#
3# Required CI/CD variable:
4# CI_PUSH_TOKEN — Project Access Token (Maintainer) with scopes:
5# `write_repository`, `self_rotate` (or `api`), and `api`
6# (api is required to write the rotated token back to this variable).
7#
8# Flow:
9# 1. validate — reject invalid or non-increasing versions
10# 2. bump — update version in project files and push commit (ci.skip; tag unchanged)
11# 3. build — produce BirdCourier-<version>.jar and upload to Package Registry
12# 4. release — publish a GitLab Release with the jar attached
13# 5. rotate-token — self-rotate CI_PUSH_TOKEN and update the CI/CD variable
14
15workflow:
16 rules:
17 - if: $CI_COMMIT_TAG
18
19variables:
20 GIT_DEPTH: "0"
21 GIT_FETCH_EXTRA_FLAGS: "--tags"
22 GRADLE_OPTS: "-Dorg.gradle.daemon=false"
23
24stages:
25 - validate
26 - bump
27 - build
28 - release
29 - rotate
30
31.validate_image:
32 image: alpine:3.20
33 before_script:
34 - apk add --no-cache bash git grep coreutils
35 - git fetch --tags --force origin
36 - chmod +x scripts/release.sh
37
38validate:version:
39 extends: .validate_image
40 stage: validate
41 script:
42 - ./scripts/release.sh validate
43 artifacts:
44 reports:
45 dotenv: version.env
46 paths:
47 - version.env
48
49bump:version:
50 extends: .validate_image
51 stage: bump
52 needs:
53 - job: validate:version
54 artifacts: true
55 script:
56 - ./scripts/release.sh bump
57 artifacts:
58 reports:
59 dotenv: version.env
60 paths:
61 - version.env
62 - build.gradle.kts
63 - src/main/resources/plugin.yml
64 - README.md
65 - src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
66
67build:jar:
68 stage: build
69 image: gradle:jdk25
70 needs:
71 - job: bump:version
72 artifacts: true
73 before_script:
74 - apt-get update -qq && apt-get install -y -qq curl >/dev/null
75 - chmod +x scripts/release.sh
76 script:
77 - test -n "${VERSION}"
78 - gradle --no-daemon clean jar
79 - test -f "build/libs/BirdCourier-${VERSION}.jar"
80 - ls -la "build/libs/BirdCourier-${VERSION}.jar"
81 - ./scripts/release.sh upload
82 artifacts:
83 reports:
84 dotenv: version.env
85 paths:
86 - "build/libs/BirdCourier-*.jar"
87 - version.env
88 expire_in: 30 days
89
90release:gitlab:
91 stage: release
92 image: registry.gitlab.com/gitlab-org/release-cli:latest
93 needs:
94 - job: build:jar
95 artifacts: true
96 script:
97 - echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"
98 release:
99 name: "BirdCourier $VERSION"
100 tag_name: "$TAG"
101 description: "Release $VERSION of BirdCourier."
102 assets:
103 links:
104 - name: "BirdCourier-$VERSION.jar"
105 url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/birdcourier/$VERSION/BirdCourier-$VERSION.jar"
106 link_type: package
107
108rotate:push-token:
109 image: alpine:3.20
110 stage: rotate
111 needs:
112 - job: release:gitlab
113 before_script:
114 - apk add --no-cache bash curl jq coreutils
115 - chmod +x scripts/release.sh
116 script:
117 - ./scripts/release.sh rotate-token
README.md added +92 −0
@@ -0,0 +1,92 @@
1 # BirdCourier 1.1.3
2
3 Paper 26.2 plugin that sends the item stack in your hand to another online player with a flying courier mob.
4
5 ## Requirements
6
7 - Paper **26.2** (Java **25**)
8 - No other plugins required
9
10 ## Install
11
12 1. Build the plugin (see [Build](#build)) or take the `BirdCourier-<version>.jar` from a BlueGit pipeline artifact.
13 2. Place the jar in the server `plugins/` folder.
14 3. Start or restart the Paper server.
15 4. Optional: edit `plugins/BirdCourier/config.yml`, then run `/birdcourier reload`.
16
17 ## Playing
18
19 1. Hold the stack you want to send in your main hand.
20 2. Run `/send <player>`. The other player must be online; you cannot send to yourself.
21 3. A courier spawns near you and flies to the recipient (including through unloaded chunks, and through Nether/End portals when enabled).
22 4. On arrival the stack is delivered into the recipient's inventory. If nobody can receive it, the courier returns or the shipment is lost after the configured wait.
23
24 Pick a personal courier with `/courier <type>` (tab completion). The choice is stored per player in `plugins/BirdCourier/couriers.properties`. If you have not chosen one, the default from `visual.entity-type` is used (parrot).
25
26 Allowed types: `allay`, `bat`, `bee`, `blaze`, `chicken`, `baby_chicken`, `ghast`, `parrot`, `vex`.
27
28 - `ghast` uses a baby `HAPPY_GHAST` (Ghastling).
29 - Visual mobs with a usable main-hand equipment slot show a visual copy of the shipment item.
30 - Bats are kept awake so they do not hang upside down mid-flight.
31
32 ## Commands
33
34 | Command | Permission | Default | Description |
35 |---|---|---|---|
36 | `/send <player>` | `birdcourier.send` | everyone | Send the held stack to an online player. |
37 | `/courier <type>` | `birdcourier.courier` | everyone | Set your personal courier mob. |
38 | `/birdcourier status` | `birdcourier.admin` | op | Show the number of active shipments. |
39 | `/birdcourier reload` | `birdcourier.admin` | op | Reload `config.yml`. |
40
41 ## Configuration
42
43 Defaults live in `config.yml` (copied to `plugins/BirdCourier/` on first run):
44
45 - **visual** — default entity type (`PARROT`) and whether the courier is silent
46 - **flight** — visible speed (default 10 blocks/s), unloaded-chunk speed multiplier (5×), preferred height (10), direct-approach distance (15), delivery range, pathfinding limits
47 - **unreachable** — how long to wait and retry when the recipient cannot be reached
48 - **portals** — follow Nether/End portals (enabled by default)
49 - **persistence** — autosave interval for `shipments.tsv`
50 - **messages** — player-facing chat text
51 - **cleanup** — delayed cleanup of leftover courier visuals after chunk load; BirdCourier tags are authoritative, so ordinary invulnerable or no-gravity mobs are not removed
52
53 Active shipments are stored in `plugins/BirdCourier/shipments.tsv`. Courier choices are stored in `plugins/BirdCourier/couriers.properties`.
54
55 ## Build
56
57 The project targets the official Paper 26.2 API build `26.2.build.112-stable` and Java 25.
58
59 With Gradle installed:
60
61 ```bash
62 gradle build
63 ```
64
65 The resulting JAR is `build/libs/BirdCourier-<version>.jar`.
66
67 ## Changelog
68
69 ### 1.1.3
70
71 - Cleanup no longer removes legitimate courier-capable mobs merely for being invulnerable or gravity-disabled.
72 - Legacy ghost fallback now requires AI to be explicitly disabled.
73 - BirdCourier tags remain authoritative for cleanup.
74
75 ### 1.1.2
76
77 - Phantom removed; chicken and baby_chicken added; bats forced awake.
78
79 ### 1.1.1 / 1.1.0
80
81 - Adds `/courier <type>` with tab completion for allay, bat, bee, blaze, ghast, parrot, phantom and vex (phantom later removed in 1.1.2).
82 - Courier choice is stored per player in `couriers.properties`.
83 - `ghast` uses a baby `HAPPY_GHAST` (Ghastling).
84 - Visual mobs with a usable main-hand equipment slot receive a visual copy of the shipment item.
85
86 ### 1.0.15
87
88 - Default visible speed: 10 blocks/second.
89 - Default unloaded travel multiplier: 5x.
90 - Default preferred flight height: 10 blocks.
91 - Default direct-approach distance: 15 blocks.
92 - Visual courier entities are non-persistent, so they are not saved into chunk data and later return as ghosts.
@@ -0,0 +1,92 @@
1# BirdCourier 1.1.3
2
3Paper 26.2 plugin that sends the item stack in your hand to another online player with a flying courier mob.
4
5## Requirements
6
7- Paper **26.2** (Java **25**)
8- No other plugins required
9
10## Install
11
121. Build the plugin (see [Build](#build)) or take the `BirdCourier-<version>.jar` from a BlueGit pipeline artifact.
132. Place the jar in the server `plugins/` folder.
143. Start or restart the Paper server.
154. Optional: edit `plugins/BirdCourier/config.yml`, then run `/birdcourier reload`.
16
17## Playing
18
191. Hold the stack you want to send in your main hand.
202. Run `/send <player>`. The other player must be online; you cannot send to yourself.
213. A courier spawns near you and flies to the recipient (including through unloaded chunks, and through Nether/End portals when enabled).
224. On arrival the stack is delivered into the recipient's inventory. If nobody can receive it, the courier returns or the shipment is lost after the configured wait.
23
24Pick a personal courier with `/courier <type>` (tab completion). The choice is stored per player in `plugins/BirdCourier/couriers.properties`. If you have not chosen one, the default from `visual.entity-type` is used (parrot).
25
26Allowed types: `allay`, `bat`, `bee`, `blaze`, `chicken`, `baby_chicken`, `ghast`, `parrot`, `vex`.
27
28- `ghast` uses a baby `HAPPY_GHAST` (Ghastling).
29- Visual mobs with a usable main-hand equipment slot show a visual copy of the shipment item.
30- Bats are kept awake so they do not hang upside down mid-flight.
31
32## Commands
33
34| Command | Permission | Default | Description |
35|---|---|---|---|
36| `/send <player>` | `birdcourier.send` | everyone | Send the held stack to an online player. |
37| `/courier <type>` | `birdcourier.courier` | everyone | Set your personal courier mob. |
38| `/birdcourier status` | `birdcourier.admin` | op | Show the number of active shipments. |
39| `/birdcourier reload` | `birdcourier.admin` | op | Reload `config.yml`. |
40
41## Configuration
42
43Defaults live in `config.yml` (copied to `plugins/BirdCourier/` on first run):
44
45- **visual** — default entity type (`PARROT`) and whether the courier is silent
46- **flight** — visible speed (default 10 blocks/s), unloaded-chunk speed multiplier (5×), preferred height (10), direct-approach distance (15), delivery range, pathfinding limits
47- **unreachable** — how long to wait and retry when the recipient cannot be reached
48- **portals** — follow Nether/End portals (enabled by default)
49- **persistence** — autosave interval for `shipments.tsv`
50- **messages** — player-facing chat text
51- **cleanup** — delayed cleanup of leftover courier visuals after chunk load; BirdCourier tags are authoritative, so ordinary invulnerable or no-gravity mobs are not removed
52
53Active shipments are stored in `plugins/BirdCourier/shipments.tsv`. Courier choices are stored in `plugins/BirdCourier/couriers.properties`.
54
55## Build
56
57The project targets the official Paper 26.2 API build `26.2.build.112-stable` and Java 25.
58
59With Gradle installed:
60
61```bash
62gradle build
63```
64
65The resulting JAR is `build/libs/BirdCourier-<version>.jar`.
66
67## Changelog
68
69### 1.1.3
70
71- Cleanup no longer removes legitimate courier-capable mobs merely for being invulnerable or gravity-disabled.
72- Legacy ghost fallback now requires AI to be explicitly disabled.
73- BirdCourier tags remain authoritative for cleanup.
74
75### 1.1.2
76
77- Phantom removed; chicken and baby_chicken added; bats forced awake.
78
79### 1.1.1 / 1.1.0
80
81- Adds `/courier <type>` with tab completion for allay, bat, bee, blaze, ghast, parrot, phantom and vex (phantom later removed in 1.1.2).
82- Courier choice is stored per player in `couriers.properties`.
83- `ghast` uses a baby `HAPPY_GHAST` (Ghastling).
84- Visual mobs with a usable main-hand equipment slot receive a visual copy of the shipment item.
85
86### 1.0.15
87
88- Default visible speed: 10 blocks/second.
89- Default unloaded travel multiplier: 5x.
90- Default preferred flight height: 10 blocks.
91- Default direct-approach distance: 15 blocks.
92- Visual courier entities are non-persistent, so they are not saved into chunk data and later return as ghosts.
blue-ci-cd.yml added +46 −0
@@ -0,0 +1,46 @@
1 # BlueGit CI (vertaald uit .gitlab-ci.yml; GitLab is alleen nog backup).
2 #
3 # Op GitLab startte een nieuwe tag de release (validate, bump-commit terug naar
4 # master met CI_PUSH_TOKEN, build, GitLab-release, token roteren). Op BlueGit
5 # maakt de release-API de tag zelf, dus:
6 # master-push: version (hoogste tag + 1 patch, of RELEASE_VERSION) en build.
7 # Zonder tags blijft de versie die al in de projectbestanden staat (1.1.3).
8 # release: HANDMATIG (zoals op GitLab een bewuste tag), maakt tag + release
9 # met de jar. Nooit automatisch, nooit dubbel.
10 # De versie wordt alleen in de build gezet (zelfde bump als scripts/release.sh),
11 # er wordt geen bump-commit teruggepusht; CI_PUSH_TOKEN is niet meer nodig.
12 # Tag-pushes starten geen pipeline.
13
14 workflow:
15 rules:
16 - if: $CI_COMMIT_TAG != ""
17 when: never
18 - if: $CI_COMMIT_BRANCH == "master"
19 - if: $CI_PIPELINE_SOURCE == "web"
20 - if: $CI_PIPELINE_SOURCE == "api"
21
22 variables:
23 GRADLE_OPTS: "-Dorg.gradle.daemon=false"
24
25 stages: [build, release]
26
27 build:artifacts:
28 stage: build
29 image: gradle:jdk25
30 script:
31 - bash scripts/ci/build.sh
32 artifacts:
33 paths: [build/out/BirdCourier.jar, build/version.txt]
34 expire_in: 30d
35
36 release:
37 stage: release
38 image: bluegit/base
39 needs: [build:artifacts]
40 when: manual
41 resource_group: release
42 rules:
43 - if: $CI_COMMIT_BRANCH == "master"
44 when: manual
45 script:
46 - bash scripts/ci/bluegit-release.sh
@@ -0,0 +1,46 @@
1# BlueGit CI (vertaald uit .gitlab-ci.yml; GitLab is alleen nog backup).
2#
3# Op GitLab startte een nieuwe tag de release (validate, bump-commit terug naar
4# master met CI_PUSH_TOKEN, build, GitLab-release, token roteren). Op BlueGit
5# maakt de release-API de tag zelf, dus:
6# master-push: version (hoogste tag + 1 patch, of RELEASE_VERSION) en build.
7# Zonder tags blijft de versie die al in de projectbestanden staat (1.1.3).
8# release: HANDMATIG (zoals op GitLab een bewuste tag), maakt tag + release
9# met de jar. Nooit automatisch, nooit dubbel.
10# De versie wordt alleen in de build gezet (zelfde bump als scripts/release.sh),
11# er wordt geen bump-commit teruggepusht; CI_PUSH_TOKEN is niet meer nodig.
12# Tag-pushes starten geen pipeline.
13
14workflow:
15 rules:
16 - if: $CI_COMMIT_TAG != ""
17 when: never
18 - if: $CI_COMMIT_BRANCH == "master"
19 - if: $CI_PIPELINE_SOURCE == "web"
20 - if: $CI_PIPELINE_SOURCE == "api"
21
22variables:
23 GRADLE_OPTS: "-Dorg.gradle.daemon=false"
24
25stages: [build, release]
26
27build:artifacts:
28 stage: build
29 image: gradle:jdk25
30 script:
31 - bash scripts/ci/build.sh
32 artifacts:
33 paths: [build/out/BirdCourier.jar, build/version.txt]
34 expire_in: 30d
35
36release:
37 stage: release
38 image: bluegit/base
39 needs: [build:artifacts]
40 when: manual
41 resource_group: release
42 rules:
43 - if: $CI_COMMIT_BRANCH == "master"
44 when: manual
45 script:
46 - bash scripts/ci/bluegit-release.sh
build.gradle.kts added +27 −0
@@ -0,0 +1,27 @@
1 plugins {
2 java
3 }
4
5 group = "nl.timfalken"
6 version = "1.1.3"
7
8 repositories {
9 mavenCentral()
10 maven {
11 name = "papermc"
12 url = uri("https://repo.papermc.io/repository/maven-public/")
13 }
14 }
15
16 dependencies {
17 compileOnly("io.papermc.paper:paper-api:26.2.build.112-stable")
18 }
19
20 java {
21 toolchain.languageVersion.set(JavaLanguageVersion.of(25))
22 }
23
24 tasks.withType<JavaCompile>().configureEach {
25 options.encoding = "UTF-8"
26 options.release.set(25)
27 }
@@ -0,0 +1,27 @@
1plugins {
2 java
3}
4
5group = "nl.timfalken"
6version = "1.1.3"
7
8repositories {
9 mavenCentral()
10 maven {
11 name = "papermc"
12 url = uri("https://repo.papermc.io/repository/maven-public/")
13 }
14}
15
16dependencies {
17 compileOnly("io.papermc.paper:paper-api:26.2.build.112-stable")
18}
19
20java {
21 toolchain.languageVersion.set(JavaLanguageVersion.of(25))
22}
23
24tasks.withType<JavaCompile>().configureEach {
25 options.encoding = "UTF-8"
26 options.release.set(25)
27}
scripts/ci/bluegit-release.sh added +15 −0
@@ -0,0 +1,15 @@
1 #!/usr/bin/env bash
2 # BlueGit: release maken met de jar als asset.
3 # De release-API maakt de tag zelf aan en weigert een bestaande tag, dus een
4 # release kan nooit twee keer ontstaan. Overslaan als HEAD al een tag heeft.
5 set -euo pipefail
6 : "${CI_API_URL:?}" "${CI_JOB_TOKEN:?}" "${CI_COMMIT_SHA:?}" "${CI_PROJECT_PATH:?}"
7 v="$(cat build/version.txt)"
8 git fetch -q --tags origin 2>/dev/null || true
9 if [[ -n "$(git tag --points-at HEAD)" ]]; then echo "Geen release: HEAD heeft al een tag."; exit 0; fi
10 if git rev-parse -q --verify "refs/tags/$v" >/dev/null; then echo "Tag $v bestaat al" >&2; exit 1; fi
11 body="$(printf '{"tag":"%s","commit":"%s","name":"BirdCourier %s","body":"Release %s of BirdCourier.","assets":[{"job":"build:artifacts","path":"build/out/BirdCourier.jar","name":"BirdCourier-%s.jar"}]}' "$v" "$CI_COMMIT_SHA" "$v" "$v" "$v")"
12 resp="$(mktemp)"
13 code="$(curl -sS -o "$resp" -w '%{http_code}' -X POST "$CI_API_URL/repos/$CI_PROJECT_PATH/releases" -H "Authorization: Bearer $CI_JOB_TOKEN" -H "Content-Type: application/json" -d "$body")" || code=000
14 cat "$resp"; echo
15 [[ "$code" == 2* ]] || { echo "Release-API gaf HTTP $code" >&2; exit 1; }
@@ -0,0 +1,15 @@
1#!/usr/bin/env bash
2# BlueGit: release maken met de jar als asset.
3# De release-API maakt de tag zelf aan en weigert een bestaande tag, dus een
4# release kan nooit twee keer ontstaan. Overslaan als HEAD al een tag heeft.
5set -euo pipefail
6: "${CI_API_URL:?}" "${CI_JOB_TOKEN:?}" "${CI_COMMIT_SHA:?}" "${CI_PROJECT_PATH:?}"
7v="$(cat build/version.txt)"
8git fetch -q --tags origin 2>/dev/null || true
9if [[ -n "$(git tag --points-at HEAD)" ]]; then echo "Geen release: HEAD heeft al een tag."; exit 0; fi
10if git rev-parse -q --verify "refs/tags/$v" >/dev/null; then echo "Tag $v bestaat al" >&2; exit 1; fi
11body="$(printf '{"tag":"%s","commit":"%s","name":"BirdCourier %s","body":"Release %s of BirdCourier.","assets":[{"job":"build:artifacts","path":"build/out/BirdCourier.jar","name":"BirdCourier-%s.jar"}]}' "$v" "$CI_COMMIT_SHA" "$v" "$v" "$v")"
12resp="$(mktemp)"
13code="$(curl -sS -o "$resp" -w '%{http_code}' -X POST "$CI_API_URL/repos/$CI_PROJECT_PATH/releases" -H "Authorization: Bearer $CI_JOB_TOKEN" -H "Content-Type: application/json" -d "$body")" || code=000
14cat "$resp"; echo
15[[ "$code" == 2* ]] || { echo "Release-API gaf HTTP $code" >&2; exit 1; }
scripts/ci/build.sh added +23 −0
@@ -0,0 +1,23 @@
1 #!/usr/bin/env bash
2 # Versie bepalen (hoogste tag + 1 patch of RELEASE_VERSION), zelfde bump als
3 # scripts/release.sh (alleen lokaal in de build, geen commit), jar bouwen.
4 # Zonder tags: de versie die al in build.gradle.kts staat, zodat de eerste
5 # import van 1.1.3 niet als 0.0.1 wordt gebouwd.
6 set -euo pipefail
7 if [ -n "${RELEASE_VERSION:-}" ]; then v="${RELEASE_VERSION#v}"; else
8 last="$(git tag -l | grep -E '^v?[0-9]+\.[0-9]+\.[0-9]+$' | sed 's/^v//' | sort -V | tail -n1 || true)"
9 if [ -z "$last" ]; then
10 v="$(sed -n 's/^version = "\(.*\)"/\1/p' build.gradle.kts)"
11 else
12 IFS=. read -r a b c <<<"$last"; v="$a.$b.$((c+1))"
13 fi
14 fi
15 echo "Versie voor deze build: $v"
16 sed -i "s/^version = \".*\"/version = \"${v}\"/" build.gradle.kts
17 sed -i -E "s/^version: ['\"]?[0-9]+\.[0-9]+\.[0-9]+['\"]?/version: ${v}/" src/main/resources/plugin.yml
18 sed -i -E "s/BirdCourier [0-9]+\.[0-9]+\.[0-9]+ enabled/BirdCourier ${v} enabled/" src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
19 gradle --no-daemon clean jar
20 mkdir -p build/out
21 cp "build/libs/BirdCourier-${v}.jar" build/out/BirdCourier.jar
22 echo "$v" > build/version.txt
23 ls -la build/out
@@ -0,0 +1,23 @@
1#!/usr/bin/env bash
2# Versie bepalen (hoogste tag + 1 patch of RELEASE_VERSION), zelfde bump als
3# scripts/release.sh (alleen lokaal in de build, geen commit), jar bouwen.
4# Zonder tags: de versie die al in build.gradle.kts staat, zodat de eerste
5# import van 1.1.3 niet als 0.0.1 wordt gebouwd.
6set -euo pipefail
7if [ -n "${RELEASE_VERSION:-}" ]; then v="${RELEASE_VERSION#v}"; else
8 last="$(git tag -l | grep -E '^v?[0-9]+\.[0-9]+\.[0-9]+$' | sed 's/^v//' | sort -V | tail -n1 || true)"
9 if [ -z "$last" ]; then
10 v="$(sed -n 's/^version = "\(.*\)"/\1/p' build.gradle.kts)"
11 else
12 IFS=. read -r a b c <<<"$last"; v="$a.$b.$((c+1))"
13 fi
14fi
15echo "Versie voor deze build: $v"
16sed -i "s/^version = \".*\"/version = \"${v}\"/" build.gradle.kts
17sed -i -E "s/^version: ['\"]?[0-9]+\.[0-9]+\.[0-9]+['\"]?/version: ${v}/" src/main/resources/plugin.yml
18sed -i -E "s/BirdCourier [0-9]+\.[0-9]+\.[0-9]+ enabled/BirdCourier ${v} enabled/" src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
19gradle --no-daemon clean jar
20mkdir -p build/out
21cp "build/libs/BirdCourier-${v}.jar" build/out/BirdCourier.jar
22echo "$v" > build/version.txt
23ls -la build/out
scripts/release.sh added +222 −0
@@ -0,0 +1,222 @@
1 #!/usr/bin/env bash
2 # Release helpers for GitLab CI.
3 set -euo pipefail
4
5 VERSION_REGEX='^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'
6
7 normalize_version() {
8 echo "${1#v}"
9 }
10
11 is_valid_version_tag() {
12 [[ "$1" =~ $VERSION_REGEX ]]
13 }
14
15 # True if $1 is strictly greater than $2 (semver X.Y.Z).
16 is_newer_version() {
17 local a b
18 a="$(normalize_version "$1")"
19 b="$(normalize_version "$2")"
20 [[ "$a" != "$b" ]] && [[ "$(printf '%s\n' "$a" "$b" | sort -V | tail -n1)" == "$a" ]]
21 }
22
23 write_version_env() {
24 local version="$1"
25 local tag="$2"
26 {
27 echo "VERSION=${version}"
28 echo "TAG=${tag}"
29 } > version.env
30 }
31
32 validate() {
33 local tag="${CI_COMMIT_TAG:?CI_COMMIT_TAG is required}"
34 local version newest
35
36 if ! is_valid_version_tag "$tag"; then
37 echo "ERROR: Tag '${tag}' has an invalid format."
38 echo "Expected: v1.7.0, 1.7.10, 1.8.0, ..."
39 exit 1
40 fi
41
42 version="$(normalize_version "$tag")"
43 echo "Validated release tag: ${tag} (version ${version})"
44
45 mapfile -t tags < <(
46 git tag -l \
47 | grep -E "$VERSION_REGEX" \
48 | grep -vxF "$tag" \
49 || true
50 )
51
52 if ((${#tags[@]} == 0)); then
53 echo "No previous release tags found; accepting ${version} as first release."
54 write_version_env "$version" "$tag"
55 return 0
56 fi
57
58 newest="$(printf '%s\n' "${tags[@]}" | sed 's/^v//' | sort -V | tail -n1)"
59 echo "Previous release version: ${newest}"
60
61 if ! is_newer_version "$version" "$newest"; then
62 echo "ERROR: Release version ${version} is not greater than previous release ${newest}."
63 exit 1
64 fi
65
66 write_version_env "$version" "$tag"
67 echo "Version check passed: ${version} > ${newest}"
68 }
69
70 bump_files() {
71 local version="${1:?version required}"
72
73 sed -i "s/^version = \".*\"/version = \"${version}\"/" build.gradle.kts
74 sed -i -E "s/^version: ['\"]?[0-9]+\.[0-9]+\.[0-9]+['\"]?/version: ${version}/" \
75 src/main/resources/plugin.yml
76 sed -i "1s/.*/# BirdCourier ${version}/" README.md
77 sed -i -E "s/BirdCourier [0-9]+\.[0-9]+\.[0-9]+ enabled/BirdCourier ${version} enabled/" \
78 src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
79
80 echo "Updated project files to version ${version}"
81 }
82
83 require_push_token() {
84 if [[ -n "${CI_PUSH_TOKEN:-}" ]]; then
85 return 0
86 fi
87
88 cat <<'EOF' >&2
89 ERROR: CI_PUSH_TOKEN is not available in this job.
90
91 The variable may exist in Settings → CI/CD → Variables but still be hidden here if:
92 1. It is Protected, while this tag/branch is not protected
93 → Protect tag pattern (e.g. *) or uncheck Protected on the variable
94 2. Its Environment scope is not "*"
95 3. The key is misspelled (must be exactly CI_PUSH_TOKEN)
96
97 EOF
98 exit 1
99 }
100
101 bump_and_push() {
102 local version="${1:?version required}"
103 local tag="${2:?tag required}"
104 local token branch
105
106 require_push_token
107 token="${CI_PUSH_TOKEN}"
108 branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"
109
110 git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"
111 git config user.name "GitLab CI"
112
113 bump_files "$version"
114
115 # Stage only versioned project files (never CI artifacts like version.env).
116 git add -- \
117 build.gradle.kts \
118 src/main/resources/plugin.yml \
119 README.md \
120 src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
121
122 if git diff --cached --quiet; then
123 echo "No version file changes to commit (already at ${version})."
124 else
125 git commit -m "chore: bump version to ${version}"
126 fi
127
128 git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
129
130 # Push version bump only. Protected tags cannot be moved/updated.
131 git push origin "HEAD:refs/heads/${branch}" -o ci.skip
132
133 echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."
134 }
135
136 upload_package() {
137 local version="${1:?version required}"
138 local jar="build/libs/BirdCourier-${version}.jar"
139 local package_url
140
141 if [[ ! -f "$jar" ]]; then
142 echo "ERROR: Expected jar not found: ${jar}"
143 ls -la build/libs/ || true
144 exit 1
145 fi
146
147 package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/birdcourier/${version}/BirdCourier-${version}.jar"
148 curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
149 --upload-file "$jar" \
150 "$package_url"
151
152 echo "Uploaded ${jar}"
153 echo "PACKAGE_URL=${package_url}" > package.env
154 }
155
156 # Self-rotate CI_PUSH_TOKEN and write the new value back to the CI/CD variable.
157 # Requires scopes: write_repository + self_rotate (or api), and api to update variables.
158 # Project access token role should be Maintainer (needed to edit CI/CD variables).
159 rotate_push_token() {
160 local old_token expires_at response new_token var_meta protected masked raw scope
161
162 require_push_token
163 old_token="${CI_PUSH_TOKEN}"
164
165 expires_at="$(date -u -d '+365 days' +%Y-%m-%d)"
166 echo "Rotating CI_PUSH_TOKEN (new expiry ${expires_at})..."
167
168 response="$(curl --fail --silent --show-error \
169 --request POST \
170 --header "PRIVATE-TOKEN: ${old_token}" \
171 --header "Content-Type: application/json" \
172 --data "{\"expires_at\":\"${expires_at}\"}" \
173 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/access_tokens/self/rotate")"
174
175 new_token="$(jq -er '.token' <<<"${response}")"
176 if [[ -z "${new_token}" || "${new_token}" == "null" ]]; then
177 echo "ERROR: Token rotation response did not include a new token."
178 echo "${response}"
179 exit 1
180 fi
181
182 var_meta="$(curl --fail --silent --show-error \
183 --header "PRIVATE-TOKEN: ${new_token}" \
184 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN")"
185
186 protected="$(jq -r '.protected' <<<"${var_meta}")"
187 masked="$(jq -r '.masked' <<<"${var_meta}")"
188 raw="$(jq -r '.raw // false' <<<"${var_meta}")"
189 scope="$(jq -r '.environment_scope // "*"' <<<"${var_meta}")"
190
191 curl --fail --silent --show-error \
192 --request PUT \
193 --header "PRIVATE-TOKEN: ${new_token}" \
194 --form "value=${new_token}" \
195 --form "protected=${protected}" \
196 --form "masked=${masked}" \
197 --form "raw=${raw}" \
198 --form "environment_scope=${scope}" \
199 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN" \
200 >/dev/null
201
202 echo "CI_PUSH_TOKEN rotated and CI/CD variable updated."
203 }
204
205 case "${1:-}" in
206 validate) validate ;;
207 bump)
208 # shellcheck disable=SC1091
209 source version.env
210 bump_and_push "$VERSION" "$TAG"
211 ;;
212 upload)
213 # shellcheck disable=SC1091
214 source version.env
215 upload_package "$VERSION"
216 ;;
217 rotate-token) rotate_push_token ;;
218 *)
219 echo "Usage: $0 {validate|bump|upload|rotate-token}"
220 exit 1
221 ;;
222 esac
@@ -0,0 +1,222 @@
1#!/usr/bin/env bash
2# Release helpers for GitLab CI.
3set -euo pipefail
4
5VERSION_REGEX='^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'
6
7normalize_version() {
8 echo "${1#v}"
9}
10
11is_valid_version_tag() {
12 [[ "$1" =~ $VERSION_REGEX ]]
13}
14
15# True if $1 is strictly greater than $2 (semver X.Y.Z).
16is_newer_version() {
17 local a b
18 a="$(normalize_version "$1")"
19 b="$(normalize_version "$2")"
20 [[ "$a" != "$b" ]] && [[ "$(printf '%s\n' "$a" "$b" | sort -V | tail -n1)" == "$a" ]]
21}
22
23write_version_env() {
24 local version="$1"
25 local tag="$2"
26 {
27 echo "VERSION=${version}"
28 echo "TAG=${tag}"
29 } > version.env
30}
31
32validate() {
33 local tag="${CI_COMMIT_TAG:?CI_COMMIT_TAG is required}"
34 local version newest
35
36 if ! is_valid_version_tag "$tag"; then
37 echo "ERROR: Tag '${tag}' has an invalid format."
38 echo "Expected: v1.7.0, 1.7.10, 1.8.0, ..."
39 exit 1
40 fi
41
42 version="$(normalize_version "$tag")"
43 echo "Validated release tag: ${tag} (version ${version})"
44
45 mapfile -t tags < <(
46 git tag -l \
47 | grep -E "$VERSION_REGEX" \
48 | grep -vxF "$tag" \
49 || true
50 )
51
52 if ((${#tags[@]} == 0)); then
53 echo "No previous release tags found; accepting ${version} as first release."
54 write_version_env "$version" "$tag"
55 return 0
56 fi
57
58 newest="$(printf '%s\n' "${tags[@]}" | sed 's/^v//' | sort -V | tail -n1)"
59 echo "Previous release version: ${newest}"
60
61 if ! is_newer_version "$version" "$newest"; then
62 echo "ERROR: Release version ${version} is not greater than previous release ${newest}."
63 exit 1
64 fi
65
66 write_version_env "$version" "$tag"
67 echo "Version check passed: ${version} > ${newest}"
68}
69
70bump_files() {
71 local version="${1:?version required}"
72
73 sed -i "s/^version = \".*\"/version = \"${version}\"/" build.gradle.kts
74 sed -i -E "s/^version: ['\"]?[0-9]+\.[0-9]+\.[0-9]+['\"]?/version: ${version}/" \
75 src/main/resources/plugin.yml
76 sed -i "1s/.*/# BirdCourier ${version}/" README.md
77 sed -i -E "s/BirdCourier [0-9]+\.[0-9]+\.[0-9]+ enabled/BirdCourier ${version} enabled/" \
78 src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
79
80 echo "Updated project files to version ${version}"
81}
82
83require_push_token() {
84 if [[ -n "${CI_PUSH_TOKEN:-}" ]]; then
85 return 0
86 fi
87
88 cat <<'EOF' >&2
89ERROR: CI_PUSH_TOKEN is not available in this job.
90
91The variable may exist in Settings → CI/CD → Variables but still be hidden here if:
92 1. It is Protected, while this tag/branch is not protected
93 → Protect tag pattern (e.g. *) or uncheck Protected on the variable
94 2. Its Environment scope is not "*"
95 3. The key is misspelled (must be exactly CI_PUSH_TOKEN)
96
97EOF
98 exit 1
99}
100
101bump_and_push() {
102 local version="${1:?version required}"
103 local tag="${2:?tag required}"
104 local token branch
105
106 require_push_token
107 token="${CI_PUSH_TOKEN}"
108 branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"
109
110 git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"
111 git config user.name "GitLab CI"
112
113 bump_files "$version"
114
115 # Stage only versioned project files (never CI artifacts like version.env).
116 git add -- \
117 build.gradle.kts \
118 src/main/resources/plugin.yml \
119 README.md \
120 src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java
121
122 if git diff --cached --quiet; then
123 echo "No version file changes to commit (already at ${version})."
124 else
125 git commit -m "chore: bump version to ${version}"
126 fi
127
128 git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
129
130 # Push version bump only. Protected tags cannot be moved/updated.
131 git push origin "HEAD:refs/heads/${branch}" -o ci.skip
132
133 echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."
134}
135
136upload_package() {
137 local version="${1:?version required}"
138 local jar="build/libs/BirdCourier-${version}.jar"
139 local package_url
140
141 if [[ ! -f "$jar" ]]; then
142 echo "ERROR: Expected jar not found: ${jar}"
143 ls -la build/libs/ || true
144 exit 1
145 fi
146
147 package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/birdcourier/${version}/BirdCourier-${version}.jar"
148 curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
149 --upload-file "$jar" \
150 "$package_url"
151
152 echo "Uploaded ${jar}"
153 echo "PACKAGE_URL=${package_url}" > package.env
154}
155
156# Self-rotate CI_PUSH_TOKEN and write the new value back to the CI/CD variable.
157# Requires scopes: write_repository + self_rotate (or api), and api to update variables.
158# Project access token role should be Maintainer (needed to edit CI/CD variables).
159rotate_push_token() {
160 local old_token expires_at response new_token var_meta protected masked raw scope
161
162 require_push_token
163 old_token="${CI_PUSH_TOKEN}"
164
165 expires_at="$(date -u -d '+365 days' +%Y-%m-%d)"
166 echo "Rotating CI_PUSH_TOKEN (new expiry ${expires_at})..."
167
168 response="$(curl --fail --silent --show-error \
169 --request POST \
170 --header "PRIVATE-TOKEN: ${old_token}" \
171 --header "Content-Type: application/json" \
172 --data "{\"expires_at\":\"${expires_at}\"}" \
173 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/access_tokens/self/rotate")"
174
175 new_token="$(jq -er '.token' <<<"${response}")"
176 if [[ -z "${new_token}" || "${new_token}" == "null" ]]; then
177 echo "ERROR: Token rotation response did not include a new token."
178 echo "${response}"
179 exit 1
180 fi
181
182 var_meta="$(curl --fail --silent --show-error \
183 --header "PRIVATE-TOKEN: ${new_token}" \
184 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN")"
185
186 protected="$(jq -r '.protected' <<<"${var_meta}")"
187 masked="$(jq -r '.masked' <<<"${var_meta}")"
188 raw="$(jq -r '.raw // false' <<<"${var_meta}")"
189 scope="$(jq -r '.environment_scope // "*"' <<<"${var_meta}")"
190
191 curl --fail --silent --show-error \
192 --request PUT \
193 --header "PRIVATE-TOKEN: ${new_token}" \
194 --form "value=${new_token}" \
195 --form "protected=${protected}" \
196 --form "masked=${masked}" \
197 --form "raw=${raw}" \
198 --form "environment_scope=${scope}" \
199 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN" \
200 >/dev/null
201
202 echo "CI_PUSH_TOKEN rotated and CI/CD variable updated."
203}
204
205case "${1:-}" in
206 validate) validate ;;
207 bump)
208 # shellcheck disable=SC1091
209 source version.env
210 bump_and_push "$VERSION" "$TAG"
211 ;;
212 upload)
213 # shellcheck disable=SC1091
214 source version.env
215 upload_package "$VERSION"
216 ;;
217 rotate-token) rotate_push_token ;;
218 *)
219 echo "Usage: $0 {validate|bump|upload|rotate-token}"
220 exit 1
221 ;;
222esac
settings.gradle.kts added +1 −0
@@ -0,0 +1 @@
1 rootProject.name = "BirdCourier"
@@ -0,0 +1 @@
1rootProject.name = "BirdCourier"
src/main/java/nl/timfalken/birdcourier/BirdCourierPlugin.java added +851 −0
@@ -0,0 +1,851 @@
1 package nl.timfalken.birdcourier;
2
3 import org.bukkit.*;
4 import org.bukkit.block.Block;
5 import org.bukkit.command.*;
6 import org.bukkit.entity.*;
7 import org.bukkit.event.*;
8 import org.bukkit.event.player.PlayerQuitEvent;
9 import org.bukkit.event.world.ChunkLoadEvent;
10 import org.bukkit.inventory.*;
11 import org.bukkit.plugin.java.JavaPlugin;
12 import org.bukkit.scheduler.BukkitTask;
13 import org.bukkit.util.Vector;
14
15 import java.io.*;
16 import java.nio.charset.StandardCharsets;
17 import java.nio.file.*;
18 import java.util.*;
19 import java.util.concurrent.atomic.AtomicLong;
20 import java.util.concurrent.ThreadLocalRandom;
21 import java.lang.reflect.Method;
22
23 public final class BirdCourierPlugin extends JavaPlugin implements Listener, CommandExecutor {
24 private final Map<Long, Shipment> shipments = new LinkedHashMap<>();
25 private final AtomicLong nextId = new AtomicLong(1);
26 private BukkitTask tickTask, saveTask;
27 private File saveFile;
28 private int pathfindsThisTick;
29 private int shipmentTickCursor;
30
31 @Override public void onEnable() {
32 saveDefaultConfig();
33 saveFile = new File(getDataFolder(), "shipments.tsv");
34 Objects.requireNonNull(getCommand("send")).setExecutor(this);
35 Objects.requireNonNull(getCommand("birdcourier")).setExecutor(this);
36 CourierChoicePatch.install(this);
37 getServer().getPluginManager().registerEvents(this, this);
38 cleanupAllTaggedVisuals();
39 loadShipments();
40 startTasks();
41 getLogger().info("BirdCourier 1.1.3 enabled with " + shipments.size() + " active shipment(s).");
42 }
43
44 @Override public void onDisable() {
45 if (tickTask != null) tickTask.cancel();
46 if (saveTask != null) saveTask.cancel();
47 for (Shipment s : shipments.values()) removeVisual(s);
48 saveShipments();
49 }
50
51 private void startTasks() {
52 if (tickTask != null) tickTask.cancel();
53 if (saveTask != null) saveTask.cancel();
54 tickTask = Bukkit.getScheduler().runTaskTimer(this, this::tickAll, 1L, 1L);
55 long saveEvery = Math.max(20L, getConfig().getLong("persistence.autosave-interval-ticks", 100L));
56 saveTask = Bukkit.getScheduler().runTaskTimer(this, this::saveShipments, saveEvery, saveEvery);
57 }
58
59 @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
60 return CourierChoicePatch.onCommand(this, sender, command, label, args);
61 }
62
63 @EventHandler public void onChunkLoad(ChunkLoadEvent event) {
64 CleanupPatch.onChunkLoad(this, event);
65 }
66
67 private Long taggedShipmentId(Entity entity) {
68 for (String tag : entity.getScoreboardTags()) {
69 if (!tag.startsWith("birdcourier-shipment:")) continue;
70 try { return Long.parseLong(tag.substring("birdcourier-shipment:".length())); }
71 catch (NumberFormatException ignored) { return null; }
72 }
73 return null;
74 }
75
76 @EventHandler public void onQuit(PlayerQuitEvent event) {
77 UUID id = event.getPlayer().getUniqueId();
78 for (Shipment s : List.copyOf(shipments.values())) {
79 if (s.state == State.TO_TARGET && s.recipient.equals(id)) {
80 s.state = State.RETURNING;
81 s.waitTicks = 0;
82 removeVisual(s);
83 Player sender = Bukkit.getPlayer(s.sender);
84 if (sender != null) sender.sendMessage(msg("returned"));
85 } else if (s.state == State.RETURNING && s.sender.equals(id)) {
86 lose(s);
87 }
88 }
89 }
90
91 private void tickAll() {
92 pathfindsThisTick = 0;
93 List<Shipment> active = new ArrayList<>(shipments.values());
94 if (active.isEmpty()) return;
95 if (shipmentTickCursor >= active.size()) shipmentTickCursor = 0;
96 for (int i = 0; i < active.size(); i++) {
97 tickShipment(active.get((shipmentTickCursor + i) % active.size()));
98 }
99 shipmentTickCursor = (shipmentTickCursor + 1) % Math.max(1, active.size());
100 }
101
102 private boolean acquirePathfindingBudget() {
103 int maximum = Math.max(1, getConfig().getInt("flight.maximum-pathfinds-per-tick", 1));
104 if (pathfindsThisTick >= maximum) return false;
105 pathfindsThisTick++;
106 return true;
107 }
108
109 private void tickShipment(Shipment s) {
110 Player destination = Bukkit.getPlayer(s.state == State.RETURNING ? s.sender : s.recipient);
111 if (destination == null || !destination.isOnline()) {
112 if (s.state == State.TO_TARGET) {
113 s.state = State.RETURNING;
114 s.waitTicks = 0;
115 removeVisual(s);
116 destination = Bukkit.getPlayer(s.sender);
117 if (destination == null || !destination.isOnline()) { lose(s); return; }
118 } else { lose(s); return; }
119 }
120
121 Location goal = destination.getLocation().add(0, 1.0, 0);
122 if (!goal.getWorld().getUID().equals(s.worldId)) {
123 handleDimensionChange(s, destination, goal);
124 return;
125 }
126
127 World world = Bukkit.getWorld(s.worldId);
128 if (world == null) { lose(s); return; }
129 Location current = s.location(world);
130 double speed = Math.max(0.05, getConfig().getDouble("flight.speed-blocks-per-second", 8.0) / 20.0);
131
132 boolean chunkLoaded = world.isChunkLoaded(current.getBlockX() >> 4, current.getBlockZ() >> 4);
133 if (!chunkLoaded) {
134 removeVisual(s);
135 s.wasVirtual = true;
136 Location beforeMove = current.clone();
137 moveStraight(s, current, goal, speed * virtualSpeedMultiplier());
138 Location afterMove = s.location(world);
139
140 // The target player keeps their own chunk loaded. If a moving target meets or
141 // crosses the virtual courier, immediately transfer the shipment into that
142 // loaded arrival region instead of letting the virtual point pass by.
143 if (shouldEnterDestinationRegion(beforeMove, afterMove, goal, world)) {
144 Location arrival = chooseArrivalBoundary(goal);
145 s.x = arrival.getX(); s.y = arrival.getY(); s.z = arrival.getZ();
146 s.route.clear(); s.routeIndex = 0; s.pathAge = 0;
147 s.pathRetryCooldown = 0;
148 return;
149 }
150
151 if (world.isChunkLoaded(((int)Math.floor(s.x)) >> 4, ((int)Math.floor(s.z)) >> 4)) {
152 s.route.clear(); s.routeIndex = 0;
153 }
154 return;
155 }
156
157 if (canDeliverAtSameLevel(current, destination)) {
158 deliver(s, destination, current);
159 return;
160 }
161
162 if (s.wasVirtual) {
163 int routeRadius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
164 double arrivalTrigger = Math.max(routeRadius,
165 getConfig().getDouble("flight.virtual-arrival-trigger-distance", routeRadius * 1.5));
166 if (current.distanceSquared(goal) <= arrivalTrigger * arrivalTrigger) {
167 if (!acquirePathfindingBudget()) return;
168 List<Vec3> arrivalRoute = findArrivalRoute(world, goal, current);
169 if (arrivalRoute != null && !arrivalRoute.isEmpty()) {
170 Vec3 entry = arrivalRoute.get(0);
171 s.x = entry.x(); s.y = entry.y(); s.z = entry.z();
172 s.route = arrivalRoute;
173 s.routeIndex = 0;
174 s.pathAge = 0;
175 s.waitTicks = 0;
176 s.wasVirtual = false;
177 Location entryLocation = s.location(world);
178 ensureVisual(s, world, entryLocation);
179 followRoute(s, world, speed);
180 return;
181 }
182
183 // We are already inside a loaded chunk. Stay visible here instead of
184 // falling back to invisible travel beside the destination. A local partial
185 // route will move the courier to the closest reachable point.
186 Location visible = nearestFreeLocation(world, current, 6);
187 if (visible != null) {
188 s.x = visible.getX(); s.y = visible.getY(); s.z = visible.getZ();
189 s.wasVirtual = false;
190 s.route.clear(); s.routeIndex = 0; s.pathAge = 0;
191 s.pathRetryCooldown = 0;
192 ensureVisual(s, world, visible);
193 randomReachableMovement(s, world, visible, goal, speed);
194 return;
195 }
196 // Only remain virtual if there is genuinely no free visible position.
197 removeVisual(s);
198 moveStraight(s, current, goal, speed * virtualSpeedMultiplier());
199 return;
200 }
201 }
202
203 ensureVisual(s, world, current);
204 s.pathAge++;
205 if (s.pathRetryCooldown > 0) s.pathRetryCooldown--;
206 boolean needRoute = s.route.isEmpty() || s.routeIndex >= s.route.size()
207 || s.pathAge >= Math.max(1, getConfig().getInt("flight.path-recalculate-ticks", 10));
208 if (needRoute) {
209 int routeRadius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
210 double localApproach = Math.max(8.0, getConfig().getDouble("flight.local-approach-distance", routeRadius * 0.75));
211 boolean closeEnoughForFinalRoute = current.distanceSquared(goal) <= localApproach * localApproach;
212 Location routeGoal;
213 List<Vec3> route;
214
215 routeGoal = closeEnoughForFinalRoute ? goal : chooseLocalStage(world, current, goal, routeRadius);
216 if (routeGoal == null) {
217 // We reached the edge of the currently loaded region. Continue virtually
218 // instead of treating a long-distance journey as an unreachable target.
219 removeVisual(s);
220 s.wasVirtual = true;
221 moveStraight(s, current, goal, speed * virtualSpeedMultiplier());
222 s.route.clear();
223 s.routeIndex = 0;
224 s.pathAge = 0;
225 return;
226 }
227 if (s.pathRetryCooldown > 0) {
228 if (!s.route.isEmpty() && s.routeIndex < s.route.size()) followRoute(s, world, speed);
229 else randomReachableMovement(s, world, current, goal, speed);
230 return;
231 }
232 if (!acquirePathfindingBudget()) {
233 // Keep following an existing route, or move harmlessly while another courier
234 // uses this tick's pathfinding budget.
235 if (!s.route.isEmpty() && s.routeIndex < s.route.size()) followRoute(s, world, speed);
236 else randomReachableMovement(s, world, current, goal, speed);
237 return;
238 }
239 route = findLocalRoute(world, current, routeGoal);
240 s.wasVirtual = false;
241 s.pathAge = 0;
242
243 if (route == null || route.isEmpty()) {
244 // A failed route inside a loaded chunk must never make the courier invisible.
245 // Stay visible, move among reachable nearby cells, and retry later. The
246 // cooldown prevents this courier from monopolising the global path budget.
247 s.waitTicks++;
248 s.pathRetryCooldown = Math.max(1, getConfig().getInt("unreachable.retry-interval-ticks", 20));
249 randomReachableMovement(s, world, current, goal, speed);
250 int maxWait = Math.max(1, getConfig().getInt("unreachable.wait-seconds", 20)) * 20;
251 if (s.waitTicks >= maxWait) {
252 if (s.state == State.TO_TARGET) {
253 s.state = State.RETURNING; s.waitTicks = 0; s.pathRetryCooldown = 0;
254 s.route.clear(); s.routeIndex = 0;
255 } else lose(s);
256 }
257 return;
258 }
259 s.route = route; s.routeIndex = 0; s.waitTicks = 0;
260 }
261
262 followRoute(s, world, speed);
263 }
264
265 private boolean shouldEnterDestinationRegion(Location before, Location after, Location goal, World world) {
266 if (!world.isChunkLoaded(goal.getBlockX() >> 4, goal.getBlockZ() >> 4)) return false;
267 int routeRadius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
268 double trigger = Math.max(routeRadius,
269 getConfig().getDouble("flight.virtual-arrival-trigger-distance", routeRadius * 1.5));
270 if (after.distanceSquared(goal) <= trigger * trigger) return true;
271
272 // Detect crossing a moving goal between ticks. This avoids overshooting when the
273 // recipient flies toward the courier faster than the courier itself moves.
274 Vector segment = after.toVector().subtract(before.toVector());
275 double lengthSquared = segment.lengthSquared();
276 if (lengthSquared < 1.0e-9) return false;
277 Vector towardGoal = goal.toVector().subtract(before.toVector());
278 double t = Math.max(0.0, Math.min(1.0, towardGoal.dot(segment) / lengthSquared));
279 Vector closest = before.toVector().add(segment.multiply(t));
280 double crossingDistance = Math.max(2.0, getConfig().getDouble("flight.delivery-distance", 2.0));
281 return closest.distanceSquared(goal.toVector()) <= crossingDistance * crossingDistance;
282 }
283
284 private void handleDimensionChange(Shipment s, Player destination, Location goal) {
285 World currentWorld = Bukkit.getWorld(s.worldId);
286 if (currentWorld == null) { transitionToDimension(s, goal); return; }
287
288 UUID destinationWorld = goal.getWorld().getUID();
289 if (!destinationWorld.equals(s.portalDestinationWorld)) {
290 s.portalDestinationWorld = destinationWorld;
291 s.portalX = s.portalY = s.portalZ = Integer.MIN_VALUE;
292 s.portalSearchDone = false;
293 s.route.clear(); s.routeIndex = 0; s.pathAge = 0;
294 }
295
296 if (getConfig().getBoolean("portals.enabled", true)) {
297 if (!s.portalSearchDone) {
298 Location found = findNearbyPortal(currentWorld, s.location(currentWorld),
299 Math.max(1, getConfig().getInt("portals.search-radius", 100)));
300 s.portalSearchDone = true;
301 if (found != null) {
302 s.portalX = found.getBlockX(); s.portalY = found.getBlockY(); s.portalZ = found.getBlockZ();
303 }
304 }
305
306 Location portal = s.portalLocation(currentWorld);
307 if (portal != null && currentWorld.isChunkLoaded(portal.getBlockX() >> 4, portal.getBlockZ() >> 4)) {
308 Location current = s.location(currentWorld);
309 double enterDistance = Math.max(0.5, getConfig().getDouble("portals.enter-distance", 3.0));
310 if (current.distanceSquared(portal) <= enterDistance * enterDistance) {
311 currentWorld.spawnParticle(Particle.SMOKE, portal, 12, .25, .35, .25, .01);
312 transitionToDimension(s, goal);
313 return;
314 }
315
316 if (!currentWorld.isChunkLoaded(current.getBlockX() >> 4, current.getBlockZ() >> 4)) {
317 removeVisual(s);
318 moveStraight(s, current, portal, Math.max(0.05, getConfig().getDouble("flight.speed-blocks-per-second", 8.0) / 20.0) * virtualSpeedMultiplier());
319 return;
320 }
321
322 ensureVisual(s, currentWorld, current);
323 s.pathAge++;
324 if (s.route.isEmpty() || s.routeIndex >= s.route.size()
325 || s.pathAge >= Math.max(1, getConfig().getInt("flight.path-recalculate-ticks", 10))) {
326 int radius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
327 double approach = Math.max(8.0, getConfig().getDouble("flight.local-approach-distance", radius * 0.75));
328 boolean finalLeg = current.distanceSquared(portal) <= approach * approach;
329 Location stage = finalLeg ? portal : chooseLocalStage(currentWorld, current, portal, radius);
330 if (stage == null) {
331 // No visible continuation is possible: continue the transition virtually.
332 transitionToDimension(s, goal);
333 return;
334 }
335 if (!acquirePathfindingBudget()) return;
336 List<Vec3> route = findLocalRoute(currentWorld, current, stage);
337 if (route == null || route.isEmpty()) {
338 transitionToDimension(s, goal);
339 return;
340 }
341 s.route = route; s.routeIndex = 0; s.pathAge = 0;
342 }
343 followRoute(s, currentWorld, Math.max(0.05,
344 getConfig().getDouble("flight.speed-blocks-per-second", 8.0) / 20.0));
345 return;
346 }
347 }
348
349 // No usable portal exists. The rest of the dimension crossing is virtual.
350 transitionToDimension(s, goal);
351 }
352
353 private void transitionToDimension(Shipment s, Location goal) {
354 removeVisual(s);
355 s.worldId = goal.getWorld().getUID();
356 Location arrival = chooseArrivalBoundary(goal);
357 s.x = arrival.getX(); s.y = arrival.getY(); s.z = arrival.getZ();
358 s.route.clear(); s.routeIndex = 0; s.pathAge = 0; s.wasVirtual = true;
359 s.portalDestinationWorld = null;
360 s.portalX = s.portalY = s.portalZ = Integer.MIN_VALUE;
361 s.portalSearchDone = false;
362 }
363
364 private Location chooseArrivalBoundary(Location goal) {
365 World w = goal.getWorld();
366 int cx = goal.getBlockX() >> 4, cz = goal.getBlockZ() >> 4;
367 List<Location> candidates = new ArrayList<>();
368 for (int i=0;i<16;i++) {
369 candidates.add(new Location(w, cx*16+0.5, goal.getY(), cz*16+i+0.5));
370 candidates.add(new Location(w, cx*16+15.5, goal.getY(), cz*16+i+0.5));
371 candidates.add(new Location(w, cx*16+i+0.5, goal.getY(), cz*16+0.5));
372 candidates.add(new Location(w, cx*16+i+0.5, goal.getY(), cz*16+15.5));
373 }
374 for (Location c : candidates) if (isFree(w,c)) return c;
375 return goal.clone().add(0, Math.min(5, Math.max(0, w.getMaxHeight()-goal.getBlockY()-2)), 0);
376 }
377
378
379 private Location chooseLocalStage(World world, Location current, Location goal, int routeRadius) {
380 Vector direction = goal.toVector().subtract(current.toVector());
381 double distance = direction.length();
382 if (distance < 1.0e-6) return goal.clone();
383 direction.normalize();
384
385 double configured = Math.max(8.0, getConfig().getDouble("flight.local-stage-distance", 28.0));
386 double maximum = Math.min(configured, Math.max(6.0, routeRadius - 4.0));
387 maximum = Math.min(maximum, distance);
388
389 Location best = null;
390 for (double step = 2.0; step <= maximum + 0.001; step += 2.0) {
391 Location candidate = current.clone().add(direction.clone().multiply(step));
392 int chunkX = candidate.getBlockX() >> 4;
393 int chunkZ = candidate.getBlockZ() >> 4;
394 if (!world.isChunkLoaded(chunkX, chunkZ)) break;
395
396 Location adjusted = choosePreferredAirPosition(world, candidate);
397 if (adjusted != null) best = adjusted;
398 }
399 return best;
400 }
401
402 private Location choosePreferredAirPosition(World world, Location candidate) {
403 int preferred = Math.max(0, getConfig().getInt("flight.preferred-height-above-ground", 5));
404 int x = candidate.getBlockX();
405 int z = candidate.getBlockZ();
406 int baseY = Math.max(world.getMinHeight() + 1, Math.min(world.getMaxHeight() - 2, candidate.getBlockY()));
407
408 int floor = findFloor(world, x, baseY, z, Math.max(12, preferred + 8));
409 if (floor >= 0) {
410 int wantedY = Math.min(world.getMaxHeight() - 2, floor + preferred);
411 for (int delta = 0; delta <= 8; delta++) {
412 int[] ys = delta == 0 ? new int[]{wantedY} : new int[]{wantedY - delta, wantedY + delta};
413 for (int y : ys) {
414 if (y <= world.getMinHeight() || y >= world.getMaxHeight() - 1) continue;
415 Location location = new Location(world, x + 0.5, y + 0.5, z + 0.5);
416 if (isFree(world, location)) return location;
417 }
418 }
419 }
420
421 for (int delta = 0; delta <= 12; delta++) {
422 int[] ys = delta == 0 ? new int[]{baseY} : new int[]{baseY + delta, baseY - delta};
423 for (int y : ys) {
424 if (y <= world.getMinHeight() || y >= world.getMaxHeight() - 1) continue;
425 Location location = new Location(world, x + 0.5, y + 0.5, z + 0.5);
426 if (isFree(world, location)) return location;
427 }
428 }
429 return null;
430 }
431
432 private List<Vec3> findLocalRoute(World world, Location start, Location goal) {
433 int radius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
434 int maxNodes = Math.max(1000, getConfig().getInt("flight.maximum-path-nodes", 35000));
435 GridPos from = GridPos.of(start), to = GridPos.of(goal);
436 record Node(GridPos p, double g, double f) {}
437 PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingDouble(Node::f));
438 Map<GridPos,Double> cost = new HashMap<>();
439 Map<GridPos,GridPos> prev = new HashMap<>();
440 double heuristicWeight = Math.max(1.0, getConfig().getDouble("flight.weighted-a-star", 1.35));
441 open.add(new Node(from,0,from.distance(to) * heuristicWeight)); cost.put(from,0.0);
442 GridPos best = from;
443 double bestDistance = from.distance(to);
444 int visited=0;
445 while(!open.isEmpty() && visited++ < maxNodes) {
446 Node n=open.poll();
447 if (n.g()!=cost.getOrDefault(n.p(),Double.MAX_VALUE)) continue;
448 double distanceToGoal = n.p().distance(to);
449 if (distanceToGoal < bestDistance) { bestDistance = distanceToGoal; best = n.p(); }
450 if (distanceToGoal <= 1.5) return reverse(prev,n.p(),world);
451 for (GridPos q : n.p().neighbors()) {
452 if (Math.abs(q.x-from.x)>radius || Math.abs(q.y-from.y)>radius || Math.abs(q.z-from.z)>radius) continue;
453 if (q.y<world.getMinHeight()+1 || q.y>=world.getMaxHeight()-1) continue;
454 if (!world.isChunkLoaded(q.x>>4,q.z>>4)) continue;
455 if (!passable(world,q) || !transitionClear(world, n.p(), q)) continue;
456 double step = movementCost(world,q,goal);
457 double ng=n.g()+step;
458 if(ng<cost.getOrDefault(q,Double.MAX_VALUE)){cost.put(q,ng);prev.put(q,n.p());open.add(new Node(q,ng,ng+q.distance(to)*heuristicWeight));}
459 }
460 }
461 // Return the best partial route if it made meaningful progress. This keeps
462 // an unreachable courier visible at the closest reachable location.
463 if (!best.equals(from) && bestDistance + 0.5 < from.distance(to)) return reverse(prev,best,world);
464 return null;
465 }
466
467 private List<Vec3> findArrivalRoute(World world, Location destination, Location virtualPosition) {
468 int radius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
469 int maxNodes = Math.max(1000, getConfig().getInt("flight.maximum-path-nodes", 35000));
470 GridPos from = GridPos.of(destination);
471 record Node(GridPos p, double g, double f) {}
472 PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingDouble(Node::f));
473 Map<GridPos,Double> cost = new HashMap<>();
474 Map<GridPos,GridPos> prev = new HashMap<>();
475 double heuristicWeight = Math.max(1.0, getConfig().getDouble("flight.weighted-a-star", 1.35));
476 open.add(new Node(from,0,0)); cost.put(from,0.0);
477 GridPos best = null;
478 double bestScore = Double.MAX_VALUE;
479 int visited = 0;
480
481 while(!open.isEmpty() && visited++ < maxNodes) {
482 Node n = open.poll();
483 if (n.g()!=cost.getOrDefault(n.p(),Double.MAX_VALUE)) continue;
484 GridPos p = n.p();
485
486 if (isLoadedRegionBoundary(world,p)) {
487 Location candidate = new Location(world,p.x+.5,p.y+.5,p.z+.5);
488 double score = candidate.distanceSquared(virtualPosition) + n.g()*0.20;
489 if (score < bestScore) { bestScore = score; best = p; }
490 if (score <= 9.0) break;
491 }
492
493 for (GridPos q : p.neighbors()) {
494 if (Math.abs(q.x-from.x)>radius || Math.abs(q.y-from.y)>radius || Math.abs(q.z-from.z)>radius) continue;
495 if (q.y<world.getMinHeight()+1 || q.y>=world.getMaxHeight()-1) continue;
496 if (!world.isChunkLoaded(q.x>>4,q.z>>4)) continue;
497 if (!passable(world,q) || !transitionClear(world, p, q)) continue;
498 double ng=n.g()+movementCost(world,q,destination);
499 if(ng<cost.getOrDefault(q,Double.MAX_VALUE)) {
500 cost.put(q,ng); prev.put(q,p);
501 double heuristic = new Location(world,q.x+.5,q.y+.5,q.z+.5).distanceSquared(virtualPosition)*0.01;
502 open.add(new Node(q,ng,ng+heuristic*heuristicWeight));
503 }
504 }
505 }
506 if (best == null) return null;
507 List<Vec3> outward = reverse(prev,best,world); // destination -> reachable boundary
508 Collections.reverse(outward); // boundary -> destination
509 return outward;
510 }
511
512 private boolean isLoadedRegionBoundary(World world, GridPos p) {
513 int cx=p.x>>4, cz=p.z>>4;
514 return !world.isChunkLoaded(cx+1,cz) || !world.isChunkLoaded(cx-1,cz)
515 || !world.isChunkLoaded(cx,cz+1) || !world.isChunkLoaded(cx,cz-1);
516 }
517
518 private double movementCost(World world, GridPos p, Location goal) {
519 Material m=world.getBlockAt(p.x,p.y,p.z).getType();
520 double cost=1.0;
521 if(m==Material.WATER) cost+=Math.max(0,getConfig().getDouble("flight.water-cost",6));
522 if(m==Material.LAVA) cost+=Math.max(0,getConfig().getDouble("flight.lava-cost",20));
523 double approach=getConfig().getDouble("flight.direct-approach-distance",10.0);
524 if(new Location(world,p.x+.5,p.y+.5,p.z+.5).distanceSquared(goal)>approach*approach){
525 int preferred=Math.max(0,getConfig().getInt("flight.preferred-height-above-ground",5));
526 int floor=findFloor(world,p.x,p.y,p.z,preferred+8);
527 if(floor>=0) cost+=Math.abs((p.y-floor)-preferred)*0.15;
528 }
529 return cost;
530 }
531
532 private int findFloor(World world,int x,int y,int z,int range){for(int yy=y-1;yy>=Math.max(world.getMinHeight(),y-range);yy--)if(world.getBlockAt(x,yy,z).getType().isSolid())return yy;return -1;}
533
534 /** Prevents diagonal corner cutting by requiring every axis-partial cell to be clear. */
535 private boolean transitionClear(World world, GridPos from, GridPos to) {
536 int dx = Integer.signum(to.x - from.x);
537 int dy = Integer.signum(to.y - from.y);
538 int dz = Integer.signum(to.z - from.z);
539 int changed = (dx != 0 ? 1 : 0) + (dy != 0 ? 1 : 0) + (dz != 0 ? 1 : 0);
540 if (changed <= 1) return true;
541
542 // Check every non-empty proper subset of the moved axes. For a 2-axis
543 // diagonal this checks both adjacent orthogonal cells; for a 3-axis
544 // diagonal it checks the three face-adjacent and three edge-adjacent cells.
545 for (int mask = 1; mask < 8; mask++) {
546 int sx = (mask & 1) != 0 ? dx : 0;
547 int sy = (mask & 2) != 0 ? dy : 0;
548 int sz = (mask & 4) != 0 ? dz : 0;
549 if ((sx == 0 && sy == 0 && sz == 0) || (sx == dx && sy == dy && sz == dz)) continue;
550 if ((sx != 0 && dx == 0) || (sy != 0 && dy == 0) || (sz != 0 && dz == 0)) continue;
551 if (!passable(world, new GridPos(from.x + sx, from.y + sy, from.z + sz))) return false;
552 }
553 return true;
554 }
555
556 private boolean passable(World w,GridPos p){Block a=w.getBlockAt(p.x,p.y,p.z), b=w.getBlockAt(p.x,p.y+1,p.z);return !a.getType().isSolid()&&!b.getType().isSolid();}
557 private boolean isFree(World w,Location l){return passable(w,GridPos.of(l));}
558
559 private void followRoute(Shipment s,World world,double speed){
560 if(s.routeIndex>=s.route.size())return;
561 Location current=s.location(world);
562 Location next=s.route.get(s.routeIndex).location(world);
563 if(current.distanceSquared(next)<0.35*0.35){s.routeIndex++;return;}
564
565 Vector direction=next.toVector().subtract(current.toVector());
566 if(direction.lengthSquared()<=1.0e-9)return;
567 direction.normalize().multiply(Math.min(speed,Math.sqrt(current.distanceSquared(next))));
568 Location candidate=current.clone().add(direction);
569
570 if(!movementSegmentClear(world,current,candidate)){
571 // Route nodes are cell centres, but the courier may currently be off-centre.
572 // Before discarding a valid diagonal route, move back toward the centre of
573 // the current free cell so the next transition starts from a safe position.
574 GridPos cell=GridPos.of(current);
575 Location centre=new Location(world,cell.x+.5,cell.y+.5,cell.z+.5);
576 if(current.distanceSquared(centre)>0.08*0.08){
577 Vector centreStep=centre.toVector().subtract(current.toVector());
578 if(centreStep.lengthSquared()>1.0e-9){
579 centreStep.normalize().multiply(Math.min(speed, Math.sqrt(current.distanceSquared(centre))));
580 Location centredCandidate=current.clone().add(centreStep);
581 if(movementSegmentClear(world,current,centredCandidate)){
582 moveVisualAndState(s,world,centredCandidate);
583 return;
584 }
585 }
586 }
587
588 // The route became invalid (for example because a block changed). Do not
589 // keep pushing into the same corner; release this route and request a new
590 // path on a later fair-scheduling turn.
591 s.route.clear();
592 s.routeIndex=0;
593 s.pathAge=0;
594 s.pathRetryCooldown=Math.max(1,getConfig().getInt("flight.blocked-retry-delay-ticks",4));
595 return;
596 }
597 moveVisualAndState(s,world,candidate);
598 }
599
600 /**
601 * Checks the actual interpolated movement, not only the centre-to-centre A* edge.
602 * This prevents an off-centre courier from cutting through a solid corner while
603 * moving toward a valid diagonal waypoint.
604 */
605 private boolean movementSegmentClear(World world,Location from,Location to){
606 double distance=Math.sqrt(from.distanceSquared(to));
607 int samples=Math.max(1,(int)Math.ceil(distance/0.10));
608 GridPos previous=GridPos.of(from);
609 for(int i=1;i<=samples;i++){
610 double t=(double)i/samples;
611 Location sample=new Location(world,
612 from.getX()+(to.getX()-from.getX())*t,
613 from.getY()+(to.getY()-from.getY())*t,
614 from.getZ()+(to.getZ()-from.getZ())*t);
615 GridPos cell=GridPos.of(sample);
616 if(!world.isChunkLoaded(cell.x>>4,cell.z>>4))return false;
617 if(!passable(world,cell))return false;
618 if(!cell.equals(previous)&&!transitionClear(world,previous,cell))return false;
619 previous=cell;
620 }
621 return true;
622 }
623 private void moveStraight(Shipment s,Location current,Location goal,double speed){
624 Vector d=goal.toVector().subtract(current.toVector());
625 double remaining=d.length();
626 if(remaining<=1.0e-9)return;
627 if(remaining>speed)d.multiply(speed/remaining);
628 s.x+=d.getX();s.y+=d.getY();s.z+=d.getZ();
629 }
630 private Location nearestFreeLocation(World world, Location around, int radius) {
631 if (isFree(world, around)) return around.clone();
632 for (int r = 1; r <= radius; r++) {
633 for (int dx = -r; dx <= r; dx++) for (int dy = -r; dy <= r; dy++) for (int dz = -r; dz <= r; dz++) {
634 if (Math.max(Math.max(Math.abs(dx), Math.abs(dy)), Math.abs(dz)) != r) continue;
635 Location candidate = around.clone().add(dx, dy, dz);
636 if (!world.isChunkLoaded(candidate.getBlockX() >> 4, candidate.getBlockZ() >> 4)) continue;
637 if (isFree(world, candidate)) return candidate;
638 }
639 }
640 return null;
641 }
642
643 private void randomReachableMovement(Shipment s, World world, Location current, Location goal, double speed) {
644 GridPos from = GridPos.of(current);
645 List<GridPos> options = new ArrayList<>();
646 for (GridPos q : from.neighbors()) {
647 if (!world.isChunkLoaded(q.x >> 4, q.z >> 4)) continue;
648 if (q.y < world.getMinHeight() + 1 || q.y >= world.getMaxHeight() - 1) continue;
649 if (passable(world, q) && transitionClear(world, from, q)) options.add(q);
650 }
651 if (options.isEmpty()) return;
652 options.sort(Comparator.comparingDouble(q -> q.distance(GridPos.of(goal)) + ThreadLocalRandom.current().nextDouble(0.0, 2.0)));
653 GridPos chosen = options.get(0);
654 Location target = new Location(world, chosen.x + .5, chosen.y + .5, chosen.z + .5);
655 Vector d = target.toVector().subtract(current.toVector());
656 if (d.lengthSquared() > 0) d.normalize().multiply(speed * 0.65);
657 moveVisualAndState(s, world, current.clone().add(d));
658 }
659
660 private void orbit(Shipment s,Location current,double speed){double r=getConfig().getDouble("unreachable.orbit-radius",2.5);double a=(System.nanoTime()/1.0e9)% (Math.PI*2);Location n=current.clone().add(Math.cos(a)*Math.min(speed,r),0,Math.sin(a)*Math.min(speed,r));moveVisualAndState(s,current.getWorld(),n);}
661 private void moveVisualAndState(Shipment s,World world,Location next){
662 Vector actualStep=new Vector(next.getX()-s.x,next.getY()-s.y,next.getZ()-s.z);
663 Vector facing=smoothedFacing(s,world,next,actualStep);
664 if(facing.lengthSquared()>1.0e-9){
665 double horizontal=Math.sqrt(facing.getX()*facing.getX()+facing.getZ()*facing.getZ());
666 next.setYaw((float)Math.toDegrees(Math.atan2(-facing.getX(),facing.getZ())));
667 next.setPitch((float)Math.toDegrees(-Math.atan2(facing.getY(),Math.max(1.0e-6,horizontal))));
668 }
669 rememberStep(s,actualStep);
670 s.x=next.getX();s.y=next.getY();s.z=next.getZ();
671 Entity e=entity(s);if(e!=null)e.teleport(next);
672 }
673
674 private Vector smoothedFacing(Shipment s,World world,Location next,Vector actualStep){
675 double sumX=0,sumY=0,sumZ=0;
676 int count=0;
677 for(Vec3 previous:s.recentSteps){
678 Vector v=new Vector(previous.x,previous.y,previous.z);
679 if(v.lengthSquared()>1.0e-9){v.normalize();sumX+=v.getX();sumY+=v.getY();sumZ+=v.getZ();count++;}
680 }
681
682 if(actualStep.lengthSquared()>1.0e-9){
683 Vector v=actualStep.clone().normalize();
684 sumX+=v.getX();sumY+=v.getY();sumZ+=v.getZ();count++;
685 }
686
687 Location cursor=next;
688 for(int i=0;i<2;i++){
689 int index=s.routeIndex+i;
690 if(index>=s.route.size())break;
691 Location future=s.route.get(index).location(world);
692 Vector v=future.toVector().subtract(cursor.toVector());
693 if(v.lengthSquared()>1.0e-9){v.normalize();sumX+=v.getX();sumY+=v.getY();sumZ+=v.getZ();count++;}
694 cursor=future;
695 }
696
697 return count==0?actualStep:new Vector(sumX/count,sumY/count,sumZ/count);
698 }
699
700 private void rememberStep(Shipment s,Vector step){
701 if(step.lengthSquared()<=1.0e-9)return;
702 Vector normalized=step.clone().normalize();
703 s.recentSteps.addLast(new Vec3(normalized.getX(),normalized.getY(),normalized.getZ()));
704 while(s.recentSteps.size()>2)s.recentSteps.removeFirst();
705 }
706
707 private void ensureVisual(Shipment s,World world,Location at){
708 CourierChoicePatch.ensureVisual(this, s, world, at);
709 }
710 private double virtualSpeedMultiplier(){
711 return Math.max(0.1, getConfig().getDouble("flight.unloaded-speed-multiplier", 3.0));
712 }
713
714 private String chooseVisualVariant(String visualType){
715 if ("PARROT".equalsIgnoreCase(visualType)) {
716 String[] variants = {"RED", "BLUE", "GREEN", "CYAN", "GRAY"};
717 return variants[ThreadLocalRandom.current().nextInt(variants.length)];
718 }
719 return "";
720 }
721
722 @SuppressWarnings({"unchecked", "rawtypes"})
723 private void applyVisualVariant(Entity entity, String variantName){
724 if (variantName == null || variantName.isBlank()) return;
725 try {
726 Method getter = entity.getClass().getMethod("getVariant");
727 Class<?> variantClass = getter.getReturnType();
728 if (!variantClass.isEnum()) return;
729 Object variant = Enum.valueOf((Class<? extends Enum>) variantClass.asSubclass(Enum.class), variantName);
730 Method setter = entity.getClass().getMethod("setVariant", variantClass);
731 setter.invoke(entity, variant);
732 } catch (ReflectiveOperationException ignored) {
733 // The configured visual entity has no supported variant API.
734 }
735 }
736
737 private EntityType parseFlyingType(String raw){
738 EntityType t;try{t=EntityType.valueOf(raw.toUpperCase(Locale.ROOT));}catch(Exception e){return EntityType.PARROT;}
739 return Set.of(EntityType.PARROT,EntityType.BAT,EntityType.ALLAY,EntityType.BEE,EntityType.BLAZE,EntityType.GHAST,EntityType.PHANTOM,EntityType.VEX).contains(t)?t:EntityType.PARROT;
740 }
741 private Entity entity(Shipment s){return s.visualId==null?null:Bukkit.getEntity(s.visualId);}
742 private String shipmentTag(long id){return "birdcourier-shipment:"+id;}
743 private void removeVisual(Shipment s){
744 Entity e=entity(s);if(e!=null)e.remove();
745 String tag=shipmentTag(s.id);
746 for(World world:Bukkit.getWorlds())for(Entity candidate:world.getEntities())
747 if(candidate.getScoreboardTags().contains(tag))candidate.remove();
748 s.visualId=null;s.recentSteps.clear();
749 }
750 private void cleanupAllTaggedVisuals(){ CleanupPatch.cleanupAll(this); }
751
752
753 private boolean canDeliverAtSameLevel(Location bird, Player target) {
754 Location player = target.getLocation();
755 if (bird.getWorld() == null || player.getWorld() == null || !bird.getWorld().getUID().equals(player.getWorld().getUID())) return false;
756
757 double dx = bird.getX() - player.getX();
758 double dz = bird.getZ() - player.getZ();
759 double maximum = Math.max(0.1, getConfig().getDouble("flight.delivery-distance", 2.0));
760 if (dx * dx + dz * dz > maximum * maximum) return false;
761
762 // Use a continuous body-height band instead of rounded block layers. A courier
763 // flying at the recipient's head is valid, while a courier on the floor above
764 // remains outside the default range.
765 double relativeY = bird.getY() - player.getY();
766 double minimum = getConfig().getDouble("flight.delivery-min-relative-y", -0.5);
767 double maximumY = getConfig().getDouble("flight.delivery-max-relative-y", 2.25);
768 return relativeY >= minimum && relativeY <= maximumY;
769 }
770
771 private void deliver(Shipment s,Player target,Location at){
772 removeVisual(s); at.getWorld().spawnParticle(Particle.SMOKE,at,16,.35,.35,.35,.02);
773 Item dropped=at.getWorld().dropItem(at,s.payload.clone()); dropped.setVelocity(target.getEyeLocation().toVector().subtract(at.toVector()).normalize().multiply(.3));
774 target.sendMessage(msg("delivered")
775 .replace("{player}", Optional.ofNullable(Bukkit.getOfflinePlayer(s.sender).getName()).orElse("someone"))
776 .replace("{amount}", Integer.toString(s.payload.getAmount()))
777 .replace("{item}", readableItemName(s.payload)));
778 shipments.remove(s.id); saveShipments();
779 }
780 private void lose(Shipment s){removeVisual(s);shipments.remove(s.id);Player p=Bukkit.getPlayer(s.sender);if(p!=null)p.sendMessage(msg("lost"));saveShipments();}
781
782 private Location findNearbyPortal(World w, Location origin, int radius) {
783 int ox = origin.getBlockX(), oy = origin.getBlockY(), oz = origin.getBlockZ();
784 int minY = Math.max(w.getMinHeight(), oy - radius);
785 int maxY = Math.min(w.getMaxHeight() - 1, oy + radius);
786 for (int r = 0; r <= radius; r++) {
787 for (int x = ox - r; x <= ox + r; x++) {
788 Location found = portalInColumn(w, x, minY, maxY, oz - r);
789 if (found != null) return found;
790 if (r > 0) {
791 found = portalInColumn(w, x, minY, maxY, oz + r);
792 if (found != null) return found;
793 }
794 }
795 for (int z = oz - r + 1; z <= oz + r - 1; z++) {
796 Location found = portalInColumn(w, ox - r, minY, maxY, z);
797 if (found != null) return found;
798 if (r > 0) {
799 found = portalInColumn(w, ox + r, minY, maxY, z);
800 if (found != null) return found;
801 }
802 }
803 }
804 return null;
805 }
806
807 private Location portalInColumn(World w, int x, int minY, int maxY, int z) {
808 if (!w.isChunkLoaded(x >> 4, z >> 4)) return null;
809 for (int y = minY; y <= maxY; y++) {
810 if (w.getBlockAt(x, y, z).getType() == Material.NETHER_PORTAL)
811 return new Location(w, x + .5, y + .5, z + .5);
812 }
813 return null;
814 }
815
816 private String readableItemName(ItemStack item) {
817 String raw = item.getType().name().toLowerCase(Locale.ROOT).replace('_', ' ');
818 StringBuilder result = new StringBuilder(raw.length());
819 boolean upper = true;
820 for (char c : raw.toCharArray()) {
821 if (upper && Character.isLetter(c)) { result.append(Character.toUpperCase(c)); upper = false; }
822 else { result.append(c); if (c == ' ') upper = true; }
823 }
824 return result.toString();
825 }
826
827 private String msg(String key){return getConfig().getString("messages."+key,key);}
828 private static double square(double d){return d*d;}
829 private static List<Vec3> reverse(Map<GridPos,GridPos> prev,GridPos end,World w){ArrayList<Vec3> out=new ArrayList<>();for(GridPos p=end;p!=null;p=prev.get(p))out.add(new Vec3(p.x+.5,p.y+.5,p.z+.5));Collections.reverse(out);return out;}
830
831 private void saveShipments(){
832 try{getDataFolder().mkdirs();Path tmp=Path.of(saveFile+".tmp");StringBuilder b=new StringBuilder("# BirdCourier 1.1.3\n");for(Shipment s:shipments.values())b.append(s.serialize()).append('\n');Files.writeString(tmp,b.toString(),StandardCharsets.UTF_8);Files.move(tmp,saveFile.toPath(),StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);}catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Could not save shipments",e);}
833 }
834 private void loadShipments(){
835 shipments.clear();if(!saveFile.exists())return;try{for(String line:Files.readAllLines(saveFile.toPath(),StandardCharsets.UTF_8)){line=line.trim();if(line.isEmpty()||line.startsWith("#"))continue;try{Shipment s=Shipment.parse(line);shipments.put(s.id,s);nextId.set(Math.max(nextId.get(),s.id+1));}catch(Exception e){getLogger().warning("Skipped invalid shipment: "+e.getMessage());}}}catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Could not load shipments",e);}
836 }
837
838 enum State{TO_TARGET,RETURNING}
839 static final class Shipment{
840 final long id;final UUID sender,recipient;final ItemStack payload;UUID worldId;double x,y,z;State state;UUID visualId;List<Vec3> route=new ArrayList<>();final Deque<Vec3> recentSteps=new ArrayDeque<>(2);int routeIndex,pathAge,waitTicks,pathRetryCooldown;boolean wasVirtual;
841 final String visualType; final String visualVariant;
842 UUID portalDestinationWorld; int portalX=Integer.MIN_VALUE,portalY=Integer.MIN_VALUE,portalZ=Integer.MIN_VALUE; boolean portalSearchDone;
843 Shipment(long id,UUID sender,UUID recipient,ItemStack payload,UUID worldId,double x,double y,double z,State state,String visualType,String visualVariant){this.id=id;this.sender=sender;this.recipient=recipient;this.payload=payload;this.worldId=worldId;this.x=x;this.y=y;this.z=z;this.state=state;this.visualType=visualType;this.visualVariant=visualVariant;}
844 Location location(World w){return new Location(w,x,y,z);}
845 Location portalLocation(World w){return portalX==Integer.MIN_VALUE?null:new Location(w,portalX+.5,portalY+.5,portalZ+.5);}
846 String serialize(){return id+"\t"+sender+"\t"+recipient+"\t"+worldId+"\t"+x+"\t"+y+"\t"+z+"\t"+state+"\t"+Base64.getUrlEncoder().withoutPadding().encodeToString(payload.serializeAsBytes())+"\t"+visualType+"\t"+visualVariant;}
847 static Shipment parse(String l){String[]p=l.split("\\t",-1);String type=p.length>9&&!p[9].isBlank()?p[9]:"PARROT";String variant=p.length>10?p[10]:"";if("PARROT".equals(type)&&variant.isBlank())variant="RED";return new Shipment(Long.parseLong(p[0]),UUID.fromString(p[1]),UUID.fromString(p[2]),ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(p[8])),UUID.fromString(p[3]),Double.parseDouble(p[4]),Double.parseDouble(p[5]),Double.parseDouble(p[6]),State.valueOf(p[7]),type,variant);}
848 }
849 record Vec3(double x,double y,double z){Location location(World w){return new Location(w,x,y,z);}}
850 record GridPos(int x,int y,int z){static GridPos of(Location l){return new GridPos(l.getBlockX(),l.getBlockY(),l.getBlockZ());}double distance(GridPos o){double dx=x-o.x,dy=y-o.y,dz=z-o.z;return Math.sqrt(dx*dx+dy*dy+dz*dz);}List<GridPos> neighbors(){ArrayList<GridPos>n=new ArrayList<>();for(int dx=-1;dx<=1;dx++)for(int dy=-1;dy<=1;dy++)for(int dz=-1;dz<=1;dz++)if(dx!=0||dy!=0||dz!=0)n.add(new GridPos(x+dx,y+dy,z+dz));return n;}}
851 }
@@ -0,0 +1,851 @@
1package nl.timfalken.birdcourier;
2
3import org.bukkit.*;
4import org.bukkit.block.Block;
5import org.bukkit.command.*;
6import org.bukkit.entity.*;
7import org.bukkit.event.*;
8import org.bukkit.event.player.PlayerQuitEvent;
9import org.bukkit.event.world.ChunkLoadEvent;
10import org.bukkit.inventory.*;
11import org.bukkit.plugin.java.JavaPlugin;
12import org.bukkit.scheduler.BukkitTask;
13import org.bukkit.util.Vector;
14
15import java.io.*;
16import java.nio.charset.StandardCharsets;
17import java.nio.file.*;
18import java.util.*;
19import java.util.concurrent.atomic.AtomicLong;
20import java.util.concurrent.ThreadLocalRandom;
21import java.lang.reflect.Method;
22
23public final class BirdCourierPlugin extends JavaPlugin implements Listener, CommandExecutor {
24 private final Map<Long, Shipment> shipments = new LinkedHashMap<>();
25 private final AtomicLong nextId = new AtomicLong(1);
26 private BukkitTask tickTask, saveTask;
27 private File saveFile;
28 private int pathfindsThisTick;
29 private int shipmentTickCursor;
30
31 @Override public void onEnable() {
32 saveDefaultConfig();
33 saveFile = new File(getDataFolder(), "shipments.tsv");
34 Objects.requireNonNull(getCommand("send")).setExecutor(this);
35 Objects.requireNonNull(getCommand("birdcourier")).setExecutor(this);
36 CourierChoicePatch.install(this);
37 getServer().getPluginManager().registerEvents(this, this);
38 cleanupAllTaggedVisuals();
39 loadShipments();
40 startTasks();
41 getLogger().info("BirdCourier 1.1.3 enabled with " + shipments.size() + " active shipment(s).");
42 }
43
44 @Override public void onDisable() {
45 if (tickTask != null) tickTask.cancel();
46 if (saveTask != null) saveTask.cancel();
47 for (Shipment s : shipments.values()) removeVisual(s);
48 saveShipments();
49 }
50
51 private void startTasks() {
52 if (tickTask != null) tickTask.cancel();
53 if (saveTask != null) saveTask.cancel();
54 tickTask = Bukkit.getScheduler().runTaskTimer(this, this::tickAll, 1L, 1L);
55 long saveEvery = Math.max(20L, getConfig().getLong("persistence.autosave-interval-ticks", 100L));
56 saveTask = Bukkit.getScheduler().runTaskTimer(this, this::saveShipments, saveEvery, saveEvery);
57 }
58
59 @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
60 return CourierChoicePatch.onCommand(this, sender, command, label, args);
61 }
62
63 @EventHandler public void onChunkLoad(ChunkLoadEvent event) {
64 CleanupPatch.onChunkLoad(this, event);
65 }
66
67 private Long taggedShipmentId(Entity entity) {
68 for (String tag : entity.getScoreboardTags()) {
69 if (!tag.startsWith("birdcourier-shipment:")) continue;
70 try { return Long.parseLong(tag.substring("birdcourier-shipment:".length())); }
71 catch (NumberFormatException ignored) { return null; }
72 }
73 return null;
74 }
75
76 @EventHandler public void onQuit(PlayerQuitEvent event) {
77 UUID id = event.getPlayer().getUniqueId();
78 for (Shipment s : List.copyOf(shipments.values())) {
79 if (s.state == State.TO_TARGET && s.recipient.equals(id)) {
80 s.state = State.RETURNING;
81 s.waitTicks = 0;
82 removeVisual(s);
83 Player sender = Bukkit.getPlayer(s.sender);
84 if (sender != null) sender.sendMessage(msg("returned"));
85 } else if (s.state == State.RETURNING && s.sender.equals(id)) {
86 lose(s);
87 }
88 }
89 }
90
91 private void tickAll() {
92 pathfindsThisTick = 0;
93 List<Shipment> active = new ArrayList<>(shipments.values());
94 if (active.isEmpty()) return;
95 if (shipmentTickCursor >= active.size()) shipmentTickCursor = 0;
96 for (int i = 0; i < active.size(); i++) {
97 tickShipment(active.get((shipmentTickCursor + i) % active.size()));
98 }
99 shipmentTickCursor = (shipmentTickCursor + 1) % Math.max(1, active.size());
100 }
101
102 private boolean acquirePathfindingBudget() {
103 int maximum = Math.max(1, getConfig().getInt("flight.maximum-pathfinds-per-tick", 1));
104 if (pathfindsThisTick >= maximum) return false;
105 pathfindsThisTick++;
106 return true;
107 }
108
109 private void tickShipment(Shipment s) {
110 Player destination = Bukkit.getPlayer(s.state == State.RETURNING ? s.sender : s.recipient);
111 if (destination == null || !destination.isOnline()) {
112 if (s.state == State.TO_TARGET) {
113 s.state = State.RETURNING;
114 s.waitTicks = 0;
115 removeVisual(s);
116 destination = Bukkit.getPlayer(s.sender);
117 if (destination == null || !destination.isOnline()) { lose(s); return; }
118 } else { lose(s); return; }
119 }
120
121 Location goal = destination.getLocation().add(0, 1.0, 0);
122 if (!goal.getWorld().getUID().equals(s.worldId)) {
123 handleDimensionChange(s, destination, goal);
124 return;
125 }
126
127 World world = Bukkit.getWorld(s.worldId);
128 if (world == null) { lose(s); return; }
129 Location current = s.location(world);
130 double speed = Math.max(0.05, getConfig().getDouble("flight.speed-blocks-per-second", 8.0) / 20.0);
131
132 boolean chunkLoaded = world.isChunkLoaded(current.getBlockX() >> 4, current.getBlockZ() >> 4);
133 if (!chunkLoaded) {
134 removeVisual(s);
135 s.wasVirtual = true;
136 Location beforeMove = current.clone();
137 moveStraight(s, current, goal, speed * virtualSpeedMultiplier());
138 Location afterMove = s.location(world);
139
140 // The target player keeps their own chunk loaded. If a moving target meets or
141 // crosses the virtual courier, immediately transfer the shipment into that
142 // loaded arrival region instead of letting the virtual point pass by.
143 if (shouldEnterDestinationRegion(beforeMove, afterMove, goal, world)) {
144 Location arrival = chooseArrivalBoundary(goal);
145 s.x = arrival.getX(); s.y = arrival.getY(); s.z = arrival.getZ();
146 s.route.clear(); s.routeIndex = 0; s.pathAge = 0;
147 s.pathRetryCooldown = 0;
148 return;
149 }
150
151 if (world.isChunkLoaded(((int)Math.floor(s.x)) >> 4, ((int)Math.floor(s.z)) >> 4)) {
152 s.route.clear(); s.routeIndex = 0;
153 }
154 return;
155 }
156
157 if (canDeliverAtSameLevel(current, destination)) {
158 deliver(s, destination, current);
159 return;
160 }
161
162 if (s.wasVirtual) {
163 int routeRadius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
164 double arrivalTrigger = Math.max(routeRadius,
165 getConfig().getDouble("flight.virtual-arrival-trigger-distance", routeRadius * 1.5));
166 if (current.distanceSquared(goal) <= arrivalTrigger * arrivalTrigger) {
167 if (!acquirePathfindingBudget()) return;
168 List<Vec3> arrivalRoute = findArrivalRoute(world, goal, current);
169 if (arrivalRoute != null && !arrivalRoute.isEmpty()) {
170 Vec3 entry = arrivalRoute.get(0);
171 s.x = entry.x(); s.y = entry.y(); s.z = entry.z();
172 s.route = arrivalRoute;
173 s.routeIndex = 0;
174 s.pathAge = 0;
175 s.waitTicks = 0;
176 s.wasVirtual = false;
177 Location entryLocation = s.location(world);
178 ensureVisual(s, world, entryLocation);
179 followRoute(s, world, speed);
180 return;
181 }
182
183 // We are already inside a loaded chunk. Stay visible here instead of
184 // falling back to invisible travel beside the destination. A local partial
185 // route will move the courier to the closest reachable point.
186 Location visible = nearestFreeLocation(world, current, 6);
187 if (visible != null) {
188 s.x = visible.getX(); s.y = visible.getY(); s.z = visible.getZ();
189 s.wasVirtual = false;
190 s.route.clear(); s.routeIndex = 0; s.pathAge = 0;
191 s.pathRetryCooldown = 0;
192 ensureVisual(s, world, visible);
193 randomReachableMovement(s, world, visible, goal, speed);
194 return;
195 }
196 // Only remain virtual if there is genuinely no free visible position.
197 removeVisual(s);
198 moveStraight(s, current, goal, speed * virtualSpeedMultiplier());
199 return;
200 }
201 }
202
203 ensureVisual(s, world, current);
204 s.pathAge++;
205 if (s.pathRetryCooldown > 0) s.pathRetryCooldown--;
206 boolean needRoute = s.route.isEmpty() || s.routeIndex >= s.route.size()
207 || s.pathAge >= Math.max(1, getConfig().getInt("flight.path-recalculate-ticks", 10));
208 if (needRoute) {
209 int routeRadius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
210 double localApproach = Math.max(8.0, getConfig().getDouble("flight.local-approach-distance", routeRadius * 0.75));
211 boolean closeEnoughForFinalRoute = current.distanceSquared(goal) <= localApproach * localApproach;
212 Location routeGoal;
213 List<Vec3> route;
214
215 routeGoal = closeEnoughForFinalRoute ? goal : chooseLocalStage(world, current, goal, routeRadius);
216 if (routeGoal == null) {
217 // We reached the edge of the currently loaded region. Continue virtually
218 // instead of treating a long-distance journey as an unreachable target.
219 removeVisual(s);
220 s.wasVirtual = true;
221 moveStraight(s, current, goal, speed * virtualSpeedMultiplier());
222 s.route.clear();
223 s.routeIndex = 0;
224 s.pathAge = 0;
225 return;
226 }
227 if (s.pathRetryCooldown > 0) {
228 if (!s.route.isEmpty() && s.routeIndex < s.route.size()) followRoute(s, world, speed);
229 else randomReachableMovement(s, world, current, goal, speed);
230 return;
231 }
232 if (!acquirePathfindingBudget()) {
233 // Keep following an existing route, or move harmlessly while another courier
234 // uses this tick's pathfinding budget.
235 if (!s.route.isEmpty() && s.routeIndex < s.route.size()) followRoute(s, world, speed);
236 else randomReachableMovement(s, world, current, goal, speed);
237 return;
238 }
239 route = findLocalRoute(world, current, routeGoal);
240 s.wasVirtual = false;
241 s.pathAge = 0;
242
243 if (route == null || route.isEmpty()) {
244 // A failed route inside a loaded chunk must never make the courier invisible.
245 // Stay visible, move among reachable nearby cells, and retry later. The
246 // cooldown prevents this courier from monopolising the global path budget.
247 s.waitTicks++;
248 s.pathRetryCooldown = Math.max(1, getConfig().getInt("unreachable.retry-interval-ticks", 20));
249 randomReachableMovement(s, world, current, goal, speed);
250 int maxWait = Math.max(1, getConfig().getInt("unreachable.wait-seconds", 20)) * 20;
251 if (s.waitTicks >= maxWait) {
252 if (s.state == State.TO_TARGET) {
253 s.state = State.RETURNING; s.waitTicks = 0; s.pathRetryCooldown = 0;
254 s.route.clear(); s.routeIndex = 0;
255 } else lose(s);
256 }
257 return;
258 }
259 s.route = route; s.routeIndex = 0; s.waitTicks = 0;
260 }
261
262 followRoute(s, world, speed);
263 }
264
265 private boolean shouldEnterDestinationRegion(Location before, Location after, Location goal, World world) {
266 if (!world.isChunkLoaded(goal.getBlockX() >> 4, goal.getBlockZ() >> 4)) return false;
267 int routeRadius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
268 double trigger = Math.max(routeRadius,
269 getConfig().getDouble("flight.virtual-arrival-trigger-distance", routeRadius * 1.5));
270 if (after.distanceSquared(goal) <= trigger * trigger) return true;
271
272 // Detect crossing a moving goal between ticks. This avoids overshooting when the
273 // recipient flies toward the courier faster than the courier itself moves.
274 Vector segment = after.toVector().subtract(before.toVector());
275 double lengthSquared = segment.lengthSquared();
276 if (lengthSquared < 1.0e-9) return false;
277 Vector towardGoal = goal.toVector().subtract(before.toVector());
278 double t = Math.max(0.0, Math.min(1.0, towardGoal.dot(segment) / lengthSquared));
279 Vector closest = before.toVector().add(segment.multiply(t));
280 double crossingDistance = Math.max(2.0, getConfig().getDouble("flight.delivery-distance", 2.0));
281 return closest.distanceSquared(goal.toVector()) <= crossingDistance * crossingDistance;
282 }
283
284 private void handleDimensionChange(Shipment s, Player destination, Location goal) {
285 World currentWorld = Bukkit.getWorld(s.worldId);
286 if (currentWorld == null) { transitionToDimension(s, goal); return; }
287
288 UUID destinationWorld = goal.getWorld().getUID();
289 if (!destinationWorld.equals(s.portalDestinationWorld)) {
290 s.portalDestinationWorld = destinationWorld;
291 s.portalX = s.portalY = s.portalZ = Integer.MIN_VALUE;
292 s.portalSearchDone = false;
293 s.route.clear(); s.routeIndex = 0; s.pathAge = 0;
294 }
295
296 if (getConfig().getBoolean("portals.enabled", true)) {
297 if (!s.portalSearchDone) {
298 Location found = findNearbyPortal(currentWorld, s.location(currentWorld),
299 Math.max(1, getConfig().getInt("portals.search-radius", 100)));
300 s.portalSearchDone = true;
301 if (found != null) {
302 s.portalX = found.getBlockX(); s.portalY = found.getBlockY(); s.portalZ = found.getBlockZ();
303 }
304 }
305
306 Location portal = s.portalLocation(currentWorld);
307 if (portal != null && currentWorld.isChunkLoaded(portal.getBlockX() >> 4, portal.getBlockZ() >> 4)) {
308 Location current = s.location(currentWorld);
309 double enterDistance = Math.max(0.5, getConfig().getDouble("portals.enter-distance", 3.0));
310 if (current.distanceSquared(portal) <= enterDistance * enterDistance) {
311 currentWorld.spawnParticle(Particle.SMOKE, portal, 12, .25, .35, .25, .01);
312 transitionToDimension(s, goal);
313 return;
314 }
315
316 if (!currentWorld.isChunkLoaded(current.getBlockX() >> 4, current.getBlockZ() >> 4)) {
317 removeVisual(s);
318 moveStraight(s, current, portal, Math.max(0.05, getConfig().getDouble("flight.speed-blocks-per-second", 8.0) / 20.0) * virtualSpeedMultiplier());
319 return;
320 }
321
322 ensureVisual(s, currentWorld, current);
323 s.pathAge++;
324 if (s.route.isEmpty() || s.routeIndex >= s.route.size()
325 || s.pathAge >= Math.max(1, getConfig().getInt("flight.path-recalculate-ticks", 10))) {
326 int radius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
327 double approach = Math.max(8.0, getConfig().getDouble("flight.local-approach-distance", radius * 0.75));
328 boolean finalLeg = current.distanceSquared(portal) <= approach * approach;
329 Location stage = finalLeg ? portal : chooseLocalStage(currentWorld, current, portal, radius);
330 if (stage == null) {
331 // No visible continuation is possible: continue the transition virtually.
332 transitionToDimension(s, goal);
333 return;
334 }
335 if (!acquirePathfindingBudget()) return;
336 List<Vec3> route = findLocalRoute(currentWorld, current, stage);
337 if (route == null || route.isEmpty()) {
338 transitionToDimension(s, goal);
339 return;
340 }
341 s.route = route; s.routeIndex = 0; s.pathAge = 0;
342 }
343 followRoute(s, currentWorld, Math.max(0.05,
344 getConfig().getDouble("flight.speed-blocks-per-second", 8.0) / 20.0));
345 return;
346 }
347 }
348
349 // No usable portal exists. The rest of the dimension crossing is virtual.
350 transitionToDimension(s, goal);
351 }
352
353 private void transitionToDimension(Shipment s, Location goal) {
354 removeVisual(s);
355 s.worldId = goal.getWorld().getUID();
356 Location arrival = chooseArrivalBoundary(goal);
357 s.x = arrival.getX(); s.y = arrival.getY(); s.z = arrival.getZ();
358 s.route.clear(); s.routeIndex = 0; s.pathAge = 0; s.wasVirtual = true;
359 s.portalDestinationWorld = null;
360 s.portalX = s.portalY = s.portalZ = Integer.MIN_VALUE;
361 s.portalSearchDone = false;
362 }
363
364 private Location chooseArrivalBoundary(Location goal) {
365 World w = goal.getWorld();
366 int cx = goal.getBlockX() >> 4, cz = goal.getBlockZ() >> 4;
367 List<Location> candidates = new ArrayList<>();
368 for (int i=0;i<16;i++) {
369 candidates.add(new Location(w, cx*16+0.5, goal.getY(), cz*16+i+0.5));
370 candidates.add(new Location(w, cx*16+15.5, goal.getY(), cz*16+i+0.5));
371 candidates.add(new Location(w, cx*16+i+0.5, goal.getY(), cz*16+0.5));
372 candidates.add(new Location(w, cx*16+i+0.5, goal.getY(), cz*16+15.5));
373 }
374 for (Location c : candidates) if (isFree(w,c)) return c;
375 return goal.clone().add(0, Math.min(5, Math.max(0, w.getMaxHeight()-goal.getBlockY()-2)), 0);
376 }
377
378
379 private Location chooseLocalStage(World world, Location current, Location goal, int routeRadius) {
380 Vector direction = goal.toVector().subtract(current.toVector());
381 double distance = direction.length();
382 if (distance < 1.0e-6) return goal.clone();
383 direction.normalize();
384
385 double configured = Math.max(8.0, getConfig().getDouble("flight.local-stage-distance", 28.0));
386 double maximum = Math.min(configured, Math.max(6.0, routeRadius - 4.0));
387 maximum = Math.min(maximum, distance);
388
389 Location best = null;
390 for (double step = 2.0; step <= maximum + 0.001; step += 2.0) {
391 Location candidate = current.clone().add(direction.clone().multiply(step));
392 int chunkX = candidate.getBlockX() >> 4;
393 int chunkZ = candidate.getBlockZ() >> 4;
394 if (!world.isChunkLoaded(chunkX, chunkZ)) break;
395
396 Location adjusted = choosePreferredAirPosition(world, candidate);
397 if (adjusted != null) best = adjusted;
398 }
399 return best;
400 }
401
402 private Location choosePreferredAirPosition(World world, Location candidate) {
403 int preferred = Math.max(0, getConfig().getInt("flight.preferred-height-above-ground", 5));
404 int x = candidate.getBlockX();
405 int z = candidate.getBlockZ();
406 int baseY = Math.max(world.getMinHeight() + 1, Math.min(world.getMaxHeight() - 2, candidate.getBlockY()));
407
408 int floor = findFloor(world, x, baseY, z, Math.max(12, preferred + 8));
409 if (floor >= 0) {
410 int wantedY = Math.min(world.getMaxHeight() - 2, floor + preferred);
411 for (int delta = 0; delta <= 8; delta++) {
412 int[] ys = delta == 0 ? new int[]{wantedY} : new int[]{wantedY - delta, wantedY + delta};
413 for (int y : ys) {
414 if (y <= world.getMinHeight() || y >= world.getMaxHeight() - 1) continue;
415 Location location = new Location(world, x + 0.5, y + 0.5, z + 0.5);
416 if (isFree(world, location)) return location;
417 }
418 }
419 }
420
421 for (int delta = 0; delta <= 12; delta++) {
422 int[] ys = delta == 0 ? new int[]{baseY} : new int[]{baseY + delta, baseY - delta};
423 for (int y : ys) {
424 if (y <= world.getMinHeight() || y >= world.getMaxHeight() - 1) continue;
425 Location location = new Location(world, x + 0.5, y + 0.5, z + 0.5);
426 if (isFree(world, location)) return location;
427 }
428 }
429 return null;
430 }
431
432 private List<Vec3> findLocalRoute(World world, Location start, Location goal) {
433 int radius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
434 int maxNodes = Math.max(1000, getConfig().getInt("flight.maximum-path-nodes", 35000));
435 GridPos from = GridPos.of(start), to = GridPos.of(goal);
436 record Node(GridPos p, double g, double f) {}
437 PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingDouble(Node::f));
438 Map<GridPos,Double> cost = new HashMap<>();
439 Map<GridPos,GridPos> prev = new HashMap<>();
440 double heuristicWeight = Math.max(1.0, getConfig().getDouble("flight.weighted-a-star", 1.35));
441 open.add(new Node(from,0,from.distance(to) * heuristicWeight)); cost.put(from,0.0);
442 GridPos best = from;
443 double bestDistance = from.distance(to);
444 int visited=0;
445 while(!open.isEmpty() && visited++ < maxNodes) {
446 Node n=open.poll();
447 if (n.g()!=cost.getOrDefault(n.p(),Double.MAX_VALUE)) continue;
448 double distanceToGoal = n.p().distance(to);
449 if (distanceToGoal < bestDistance) { bestDistance = distanceToGoal; best = n.p(); }
450 if (distanceToGoal <= 1.5) return reverse(prev,n.p(),world);
451 for (GridPos q : n.p().neighbors()) {
452 if (Math.abs(q.x-from.x)>radius || Math.abs(q.y-from.y)>radius || Math.abs(q.z-from.z)>radius) continue;
453 if (q.y<world.getMinHeight()+1 || q.y>=world.getMaxHeight()-1) continue;
454 if (!world.isChunkLoaded(q.x>>4,q.z>>4)) continue;
455 if (!passable(world,q) || !transitionClear(world, n.p(), q)) continue;
456 double step = movementCost(world,q,goal);
457 double ng=n.g()+step;
458 if(ng<cost.getOrDefault(q,Double.MAX_VALUE)){cost.put(q,ng);prev.put(q,n.p());open.add(new Node(q,ng,ng+q.distance(to)*heuristicWeight));}
459 }
460 }
461 // Return the best partial route if it made meaningful progress. This keeps
462 // an unreachable courier visible at the closest reachable location.
463 if (!best.equals(from) && bestDistance + 0.5 < from.distance(to)) return reverse(prev,best,world);
464 return null;
465 }
466
467 private List<Vec3> findArrivalRoute(World world, Location destination, Location virtualPosition) {
468 int radius = Math.max(8, getConfig().getInt("flight.route-search-radius", 48));
469 int maxNodes = Math.max(1000, getConfig().getInt("flight.maximum-path-nodes", 35000));
470 GridPos from = GridPos.of(destination);
471 record Node(GridPos p, double g, double f) {}
472 PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingDouble(Node::f));
473 Map<GridPos,Double> cost = new HashMap<>();
474 Map<GridPos,GridPos> prev = new HashMap<>();
475 double heuristicWeight = Math.max(1.0, getConfig().getDouble("flight.weighted-a-star", 1.35));
476 open.add(new Node(from,0,0)); cost.put(from,0.0);
477 GridPos best = null;
478 double bestScore = Double.MAX_VALUE;
479 int visited = 0;
480
481 while(!open.isEmpty() && visited++ < maxNodes) {
482 Node n = open.poll();
483 if (n.g()!=cost.getOrDefault(n.p(),Double.MAX_VALUE)) continue;
484 GridPos p = n.p();
485
486 if (isLoadedRegionBoundary(world,p)) {
487 Location candidate = new Location(world,p.x+.5,p.y+.5,p.z+.5);
488 double score = candidate.distanceSquared(virtualPosition) + n.g()*0.20;
489 if (score < bestScore) { bestScore = score; best = p; }
490 if (score <= 9.0) break;
491 }
492
493 for (GridPos q : p.neighbors()) {
494 if (Math.abs(q.x-from.x)>radius || Math.abs(q.y-from.y)>radius || Math.abs(q.z-from.z)>radius) continue;
495 if (q.y<world.getMinHeight()+1 || q.y>=world.getMaxHeight()-1) continue;
496 if (!world.isChunkLoaded(q.x>>4,q.z>>4)) continue;
497 if (!passable(world,q) || !transitionClear(world, p, q)) continue;
498 double ng=n.g()+movementCost(world,q,destination);
499 if(ng<cost.getOrDefault(q,Double.MAX_VALUE)) {
500 cost.put(q,ng); prev.put(q,p);
501 double heuristic = new Location(world,q.x+.5,q.y+.5,q.z+.5).distanceSquared(virtualPosition)*0.01;
502 open.add(new Node(q,ng,ng+heuristic*heuristicWeight));
503 }
504 }
505 }
506 if (best == null) return null;
507 List<Vec3> outward = reverse(prev,best,world); // destination -> reachable boundary
508 Collections.reverse(outward); // boundary -> destination
509 return outward;
510 }
511
512 private boolean isLoadedRegionBoundary(World world, GridPos p) {
513 int cx=p.x>>4, cz=p.z>>4;
514 return !world.isChunkLoaded(cx+1,cz) || !world.isChunkLoaded(cx-1,cz)
515 || !world.isChunkLoaded(cx,cz+1) || !world.isChunkLoaded(cx,cz-1);
516 }
517
518 private double movementCost(World world, GridPos p, Location goal) {
519 Material m=world.getBlockAt(p.x,p.y,p.z).getType();
520 double cost=1.0;
521 if(m==Material.WATER) cost+=Math.max(0,getConfig().getDouble("flight.water-cost",6));
522 if(m==Material.LAVA) cost+=Math.max(0,getConfig().getDouble("flight.lava-cost",20));
523 double approach=getConfig().getDouble("flight.direct-approach-distance",10.0);
524 if(new Location(world,p.x+.5,p.y+.5,p.z+.5).distanceSquared(goal)>approach*approach){
525 int preferred=Math.max(0,getConfig().getInt("flight.preferred-height-above-ground",5));
526 int floor=findFloor(world,p.x,p.y,p.z,preferred+8);
527 if(floor>=0) cost+=Math.abs((p.y-floor)-preferred)*0.15;
528 }
529 return cost;
530 }
531
532 private int findFloor(World world,int x,int y,int z,int range){for(int yy=y-1;yy>=Math.max(world.getMinHeight(),y-range);yy--)if(world.getBlockAt(x,yy,z).getType().isSolid())return yy;return -1;}
533
534 /** Prevents diagonal corner cutting by requiring every axis-partial cell to be clear. */
535 private boolean transitionClear(World world, GridPos from, GridPos to) {
536 int dx = Integer.signum(to.x - from.x);
537 int dy = Integer.signum(to.y - from.y);
538 int dz = Integer.signum(to.z - from.z);
539 int changed = (dx != 0 ? 1 : 0) + (dy != 0 ? 1 : 0) + (dz != 0 ? 1 : 0);
540 if (changed <= 1) return true;
541
542 // Check every non-empty proper subset of the moved axes. For a 2-axis
543 // diagonal this checks both adjacent orthogonal cells; for a 3-axis
544 // diagonal it checks the three face-adjacent and three edge-adjacent cells.
545 for (int mask = 1; mask < 8; mask++) {
546 int sx = (mask & 1) != 0 ? dx : 0;
547 int sy = (mask & 2) != 0 ? dy : 0;
548 int sz = (mask & 4) != 0 ? dz : 0;
549 if ((sx == 0 && sy == 0 && sz == 0) || (sx == dx && sy == dy && sz == dz)) continue;
550 if ((sx != 0 && dx == 0) || (sy != 0 && dy == 0) || (sz != 0 && dz == 0)) continue;
551 if (!passable(world, new GridPos(from.x + sx, from.y + sy, from.z + sz))) return false;
552 }
553 return true;
554 }
555
556 private boolean passable(World w,GridPos p){Block a=w.getBlockAt(p.x,p.y,p.z), b=w.getBlockAt(p.x,p.y+1,p.z);return !a.getType().isSolid()&&!b.getType().isSolid();}
557 private boolean isFree(World w,Location l){return passable(w,GridPos.of(l));}
558
559 private void followRoute(Shipment s,World world,double speed){
560 if(s.routeIndex>=s.route.size())return;
561 Location current=s.location(world);
562 Location next=s.route.get(s.routeIndex).location(world);
563 if(current.distanceSquared(next)<0.35*0.35){s.routeIndex++;return;}
564
565 Vector direction=next.toVector().subtract(current.toVector());
566 if(direction.lengthSquared()<=1.0e-9)return;
567 direction.normalize().multiply(Math.min(speed,Math.sqrt(current.distanceSquared(next))));
568 Location candidate=current.clone().add(direction);
569
570 if(!movementSegmentClear(world,current,candidate)){
571 // Route nodes are cell centres, but the courier may currently be off-centre.
572 // Before discarding a valid diagonal route, move back toward the centre of
573 // the current free cell so the next transition starts from a safe position.
574 GridPos cell=GridPos.of(current);
575 Location centre=new Location(world,cell.x+.5,cell.y+.5,cell.z+.5);
576 if(current.distanceSquared(centre)>0.08*0.08){
577 Vector centreStep=centre.toVector().subtract(current.toVector());
578 if(centreStep.lengthSquared()>1.0e-9){
579 centreStep.normalize().multiply(Math.min(speed, Math.sqrt(current.distanceSquared(centre))));
580 Location centredCandidate=current.clone().add(centreStep);
581 if(movementSegmentClear(world,current,centredCandidate)){
582 moveVisualAndState(s,world,centredCandidate);
583 return;
584 }
585 }
586 }
587
588 // The route became invalid (for example because a block changed). Do not
589 // keep pushing into the same corner; release this route and request a new
590 // path on a later fair-scheduling turn.
591 s.route.clear();
592 s.routeIndex=0;
593 s.pathAge=0;
594 s.pathRetryCooldown=Math.max(1,getConfig().getInt("flight.blocked-retry-delay-ticks",4));
595 return;
596 }
597 moveVisualAndState(s,world,candidate);
598 }
599
600 /**
601 * Checks the actual interpolated movement, not only the centre-to-centre A* edge.
602 * This prevents an off-centre courier from cutting through a solid corner while
603 * moving toward a valid diagonal waypoint.
604 */
605 private boolean movementSegmentClear(World world,Location from,Location to){
606 double distance=Math.sqrt(from.distanceSquared(to));
607 int samples=Math.max(1,(int)Math.ceil(distance/0.10));
608 GridPos previous=GridPos.of(from);
609 for(int i=1;i<=samples;i++){
610 double t=(double)i/samples;
611 Location sample=new Location(world,
612 from.getX()+(to.getX()-from.getX())*t,
613 from.getY()+(to.getY()-from.getY())*t,
614 from.getZ()+(to.getZ()-from.getZ())*t);
615 GridPos cell=GridPos.of(sample);
616 if(!world.isChunkLoaded(cell.x>>4,cell.z>>4))return false;
617 if(!passable(world,cell))return false;
618 if(!cell.equals(previous)&&!transitionClear(world,previous,cell))return false;
619 previous=cell;
620 }
621 return true;
622 }
623 private void moveStraight(Shipment s,Location current,Location goal,double speed){
624 Vector d=goal.toVector().subtract(current.toVector());
625 double remaining=d.length();
626 if(remaining<=1.0e-9)return;
627 if(remaining>speed)d.multiply(speed/remaining);
628 s.x+=d.getX();s.y+=d.getY();s.z+=d.getZ();
629 }
630 private Location nearestFreeLocation(World world, Location around, int radius) {
631 if (isFree(world, around)) return around.clone();
632 for (int r = 1; r <= radius; r++) {
633 for (int dx = -r; dx <= r; dx++) for (int dy = -r; dy <= r; dy++) for (int dz = -r; dz <= r; dz++) {
634 if (Math.max(Math.max(Math.abs(dx), Math.abs(dy)), Math.abs(dz)) != r) continue;
635 Location candidate = around.clone().add(dx, dy, dz);
636 if (!world.isChunkLoaded(candidate.getBlockX() >> 4, candidate.getBlockZ() >> 4)) continue;
637 if (isFree(world, candidate)) return candidate;
638 }
639 }
640 return null;
641 }
642
643 private void randomReachableMovement(Shipment s, World world, Location current, Location goal, double speed) {
644 GridPos from = GridPos.of(current);
645 List<GridPos> options = new ArrayList<>();
646 for (GridPos q : from.neighbors()) {
647 if (!world.isChunkLoaded(q.x >> 4, q.z >> 4)) continue;
648 if (q.y < world.getMinHeight() + 1 || q.y >= world.getMaxHeight() - 1) continue;
649 if (passable(world, q) && transitionClear(world, from, q)) options.add(q);
650 }
651 if (options.isEmpty()) return;
652 options.sort(Comparator.comparingDouble(q -> q.distance(GridPos.of(goal)) + ThreadLocalRandom.current().nextDouble(0.0, 2.0)));
653 GridPos chosen = options.get(0);
654 Location target = new Location(world, chosen.x + .5, chosen.y + .5, chosen.z + .5);
655 Vector d = target.toVector().subtract(current.toVector());
656 if (d.lengthSquared() > 0) d.normalize().multiply(speed * 0.65);
657 moveVisualAndState(s, world, current.clone().add(d));
658 }
659
660 private void orbit(Shipment s,Location current,double speed){double r=getConfig().getDouble("unreachable.orbit-radius",2.5);double a=(System.nanoTime()/1.0e9)% (Math.PI*2);Location n=current.clone().add(Math.cos(a)*Math.min(speed,r),0,Math.sin(a)*Math.min(speed,r));moveVisualAndState(s,current.getWorld(),n);}
661 private void moveVisualAndState(Shipment s,World world,Location next){
662 Vector actualStep=new Vector(next.getX()-s.x,next.getY()-s.y,next.getZ()-s.z);
663 Vector facing=smoothedFacing(s,world,next,actualStep);
664 if(facing.lengthSquared()>1.0e-9){
665 double horizontal=Math.sqrt(facing.getX()*facing.getX()+facing.getZ()*facing.getZ());
666 next.setYaw((float)Math.toDegrees(Math.atan2(-facing.getX(),facing.getZ())));
667 next.setPitch((float)Math.toDegrees(-Math.atan2(facing.getY(),Math.max(1.0e-6,horizontal))));
668 }
669 rememberStep(s,actualStep);
670 s.x=next.getX();s.y=next.getY();s.z=next.getZ();
671 Entity e=entity(s);if(e!=null)e.teleport(next);
672 }
673
674 private Vector smoothedFacing(Shipment s,World world,Location next,Vector actualStep){
675 double sumX=0,sumY=0,sumZ=0;
676 int count=0;
677 for(Vec3 previous:s.recentSteps){
678 Vector v=new Vector(previous.x,previous.y,previous.z);
679 if(v.lengthSquared()>1.0e-9){v.normalize();sumX+=v.getX();sumY+=v.getY();sumZ+=v.getZ();count++;}
680 }
681
682 if(actualStep.lengthSquared()>1.0e-9){
683 Vector v=actualStep.clone().normalize();
684 sumX+=v.getX();sumY+=v.getY();sumZ+=v.getZ();count++;
685 }
686
687 Location cursor=next;
688 for(int i=0;i<2;i++){
689 int index=s.routeIndex+i;
690 if(index>=s.route.size())break;
691 Location future=s.route.get(index).location(world);
692 Vector v=future.toVector().subtract(cursor.toVector());
693 if(v.lengthSquared()>1.0e-9){v.normalize();sumX+=v.getX();sumY+=v.getY();sumZ+=v.getZ();count++;}
694 cursor=future;
695 }
696
697 return count==0?actualStep:new Vector(sumX/count,sumY/count,sumZ/count);
698 }
699
700 private void rememberStep(Shipment s,Vector step){
701 if(step.lengthSquared()<=1.0e-9)return;
702 Vector normalized=step.clone().normalize();
703 s.recentSteps.addLast(new Vec3(normalized.getX(),normalized.getY(),normalized.getZ()));
704 while(s.recentSteps.size()>2)s.recentSteps.removeFirst();
705 }
706
707 private void ensureVisual(Shipment s,World world,Location at){
708 CourierChoicePatch.ensureVisual(this, s, world, at);
709 }
710 private double virtualSpeedMultiplier(){
711 return Math.max(0.1, getConfig().getDouble("flight.unloaded-speed-multiplier", 3.0));
712 }
713
714 private String chooseVisualVariant(String visualType){
715 if ("PARROT".equalsIgnoreCase(visualType)) {
716 String[] variants = {"RED", "BLUE", "GREEN", "CYAN", "GRAY"};
717 return variants[ThreadLocalRandom.current().nextInt(variants.length)];
718 }
719 return "";
720 }
721
722 @SuppressWarnings({"unchecked", "rawtypes"})
723 private void applyVisualVariant(Entity entity, String variantName){
724 if (variantName == null || variantName.isBlank()) return;
725 try {
726 Method getter = entity.getClass().getMethod("getVariant");
727 Class<?> variantClass = getter.getReturnType();
728 if (!variantClass.isEnum()) return;
729 Object variant = Enum.valueOf((Class<? extends Enum>) variantClass.asSubclass(Enum.class), variantName);
730 Method setter = entity.getClass().getMethod("setVariant", variantClass);
731 setter.invoke(entity, variant);
732 } catch (ReflectiveOperationException ignored) {
733 // The configured visual entity has no supported variant API.
734 }
735 }
736
737 private EntityType parseFlyingType(String raw){
738 EntityType t;try{t=EntityType.valueOf(raw.toUpperCase(Locale.ROOT));}catch(Exception e){return EntityType.PARROT;}
739 return Set.of(EntityType.PARROT,EntityType.BAT,EntityType.ALLAY,EntityType.BEE,EntityType.BLAZE,EntityType.GHAST,EntityType.PHANTOM,EntityType.VEX).contains(t)?t:EntityType.PARROT;
740 }
741 private Entity entity(Shipment s){return s.visualId==null?null:Bukkit.getEntity(s.visualId);}
742 private String shipmentTag(long id){return "birdcourier-shipment:"+id;}
743 private void removeVisual(Shipment s){
744 Entity e=entity(s);if(e!=null)e.remove();
745 String tag=shipmentTag(s.id);
746 for(World world:Bukkit.getWorlds())for(Entity candidate:world.getEntities())
747 if(candidate.getScoreboardTags().contains(tag))candidate.remove();
748 s.visualId=null;s.recentSteps.clear();
749 }
750 private void cleanupAllTaggedVisuals(){ CleanupPatch.cleanupAll(this); }
751
752
753 private boolean canDeliverAtSameLevel(Location bird, Player target) {
754 Location player = target.getLocation();
755 if (bird.getWorld() == null || player.getWorld() == null || !bird.getWorld().getUID().equals(player.getWorld().getUID())) return false;
756
757 double dx = bird.getX() - player.getX();
758 double dz = bird.getZ() - player.getZ();
759 double maximum = Math.max(0.1, getConfig().getDouble("flight.delivery-distance", 2.0));
760 if (dx * dx + dz * dz > maximum * maximum) return false;
761
762 // Use a continuous body-height band instead of rounded block layers. A courier
763 // flying at the recipient's head is valid, while a courier on the floor above
764 // remains outside the default range.
765 double relativeY = bird.getY() - player.getY();
766 double minimum = getConfig().getDouble("flight.delivery-min-relative-y", -0.5);
767 double maximumY = getConfig().getDouble("flight.delivery-max-relative-y", 2.25);
768 return relativeY >= minimum && relativeY <= maximumY;
769 }
770
771 private void deliver(Shipment s,Player target,Location at){
772 removeVisual(s); at.getWorld().spawnParticle(Particle.SMOKE,at,16,.35,.35,.35,.02);
773 Item dropped=at.getWorld().dropItem(at,s.payload.clone()); dropped.setVelocity(target.getEyeLocation().toVector().subtract(at.toVector()).normalize().multiply(.3));
774 target.sendMessage(msg("delivered")
775 .replace("{player}", Optional.ofNullable(Bukkit.getOfflinePlayer(s.sender).getName()).orElse("someone"))
776 .replace("{amount}", Integer.toString(s.payload.getAmount()))
777 .replace("{item}", readableItemName(s.payload)));
778 shipments.remove(s.id); saveShipments();
779 }
780 private void lose(Shipment s){removeVisual(s);shipments.remove(s.id);Player p=Bukkit.getPlayer(s.sender);if(p!=null)p.sendMessage(msg("lost"));saveShipments();}
781
782 private Location findNearbyPortal(World w, Location origin, int radius) {
783 int ox = origin.getBlockX(), oy = origin.getBlockY(), oz = origin.getBlockZ();
784 int minY = Math.max(w.getMinHeight(), oy - radius);
785 int maxY = Math.min(w.getMaxHeight() - 1, oy + radius);
786 for (int r = 0; r <= radius; r++) {
787 for (int x = ox - r; x <= ox + r; x++) {
788 Location found = portalInColumn(w, x, minY, maxY, oz - r);
789 if (found != null) return found;
790 if (r > 0) {
791 found = portalInColumn(w, x, minY, maxY, oz + r);
792 if (found != null) return found;
793 }
794 }
795 for (int z = oz - r + 1; z <= oz + r - 1; z++) {
796 Location found = portalInColumn(w, ox - r, minY, maxY, z);
797 if (found != null) return found;
798 if (r > 0) {
799 found = portalInColumn(w, ox + r, minY, maxY, z);
800 if (found != null) return found;
801 }
802 }
803 }
804 return null;
805 }
806
807 private Location portalInColumn(World w, int x, int minY, int maxY, int z) {
808 if (!w.isChunkLoaded(x >> 4, z >> 4)) return null;
809 for (int y = minY; y <= maxY; y++) {
810 if (w.getBlockAt(x, y, z).getType() == Material.NETHER_PORTAL)
811 return new Location(w, x + .5, y + .5, z + .5);
812 }
813 return null;
814 }
815
816 private String readableItemName(ItemStack item) {
817 String raw = item.getType().name().toLowerCase(Locale.ROOT).replace('_', ' ');
818 StringBuilder result = new StringBuilder(raw.length());
819 boolean upper = true;
820 for (char c : raw.toCharArray()) {
821 if (upper && Character.isLetter(c)) { result.append(Character.toUpperCase(c)); upper = false; }
822 else { result.append(c); if (c == ' ') upper = true; }
823 }
824 return result.toString();
825 }
826
827 private String msg(String key){return getConfig().getString("messages."+key,key);}
828 private static double square(double d){return d*d;}
829 private static List<Vec3> reverse(Map<GridPos,GridPos> prev,GridPos end,World w){ArrayList<Vec3> out=new ArrayList<>();for(GridPos p=end;p!=null;p=prev.get(p))out.add(new Vec3(p.x+.5,p.y+.5,p.z+.5));Collections.reverse(out);return out;}
830
831 private void saveShipments(){
832 try{getDataFolder().mkdirs();Path tmp=Path.of(saveFile+".tmp");StringBuilder b=new StringBuilder("# BirdCourier 1.1.3\n");for(Shipment s:shipments.values())b.append(s.serialize()).append('\n');Files.writeString(tmp,b.toString(),StandardCharsets.UTF_8);Files.move(tmp,saveFile.toPath(),StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);}catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Could not save shipments",e);}
833 }
834 private void loadShipments(){
835 shipments.clear();if(!saveFile.exists())return;try{for(String line:Files.readAllLines(saveFile.toPath(),StandardCharsets.UTF_8)){line=line.trim();if(line.isEmpty()||line.startsWith("#"))continue;try{Shipment s=Shipment.parse(line);shipments.put(s.id,s);nextId.set(Math.max(nextId.get(),s.id+1));}catch(Exception e){getLogger().warning("Skipped invalid shipment: "+e.getMessage());}}}catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Could not load shipments",e);}
836 }
837
838 enum State{TO_TARGET,RETURNING}
839 static final class Shipment{
840 final long id;final UUID sender,recipient;final ItemStack payload;UUID worldId;double x,y,z;State state;UUID visualId;List<Vec3> route=new ArrayList<>();final Deque<Vec3> recentSteps=new ArrayDeque<>(2);int routeIndex,pathAge,waitTicks,pathRetryCooldown;boolean wasVirtual;
841 final String visualType; final String visualVariant;
842 UUID portalDestinationWorld; int portalX=Integer.MIN_VALUE,portalY=Integer.MIN_VALUE,portalZ=Integer.MIN_VALUE; boolean portalSearchDone;
843 Shipment(long id,UUID sender,UUID recipient,ItemStack payload,UUID worldId,double x,double y,double z,State state,String visualType,String visualVariant){this.id=id;this.sender=sender;this.recipient=recipient;this.payload=payload;this.worldId=worldId;this.x=x;this.y=y;this.z=z;this.state=state;this.visualType=visualType;this.visualVariant=visualVariant;}
844 Location location(World w){return new Location(w,x,y,z);}
845 Location portalLocation(World w){return portalX==Integer.MIN_VALUE?null:new Location(w,portalX+.5,portalY+.5,portalZ+.5);}
846 String serialize(){return id+"\t"+sender+"\t"+recipient+"\t"+worldId+"\t"+x+"\t"+y+"\t"+z+"\t"+state+"\t"+Base64.getUrlEncoder().withoutPadding().encodeToString(payload.serializeAsBytes())+"\t"+visualType+"\t"+visualVariant;}
847 static Shipment parse(String l){String[]p=l.split("\\t",-1);String type=p.length>9&&!p[9].isBlank()?p[9]:"PARROT";String variant=p.length>10?p[10]:"";if("PARROT".equals(type)&&variant.isBlank())variant="RED";return new Shipment(Long.parseLong(p[0]),UUID.fromString(p[1]),UUID.fromString(p[2]),ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(p[8])),UUID.fromString(p[3]),Double.parseDouble(p[4]),Double.parseDouble(p[5]),Double.parseDouble(p[6]),State.valueOf(p[7]),type,variant);}
848 }
849 record Vec3(double x,double y,double z){Location location(World w){return new Location(w,x,y,z);}}
850 record GridPos(int x,int y,int z){static GridPos of(Location l){return new GridPos(l.getBlockX(),l.getBlockY(),l.getBlockZ());}double distance(GridPos o){double dx=x-o.x,dy=y-o.y,dz=z-o.z;return Math.sqrt(dx*dx+dy*dy+dz*dz);}List<GridPos> neighbors(){ArrayList<GridPos>n=new ArrayList<>();for(int dx=-1;dx<=1;dx++)for(int dy=-1;dy<=1;dy++)for(int dz=-1;dz<=1;dz++)if(dx!=0||dy!=0||dz!=0)n.add(new GridPos(x+dx,y+dy,z+dz));return n;}}
851}
src/main/java/nl/timfalken/birdcourier/CleanupPatch.java added +262 −0
@@ -0,0 +1,262 @@
1 package nl.timfalken.birdcourier;
2
3 import java.lang.reflect.*;
4 import java.util.*;
5 import java.util.concurrent.atomic.AtomicBoolean;
6
7 /** Cleanup compatibility layer using reflection to avoid unstable Paper descriptors. */
8 public final class CleanupPatch {
9 private static final AtomicBoolean PERIODIC_STARTED = new AtomicBoolean(false);
10 private CleanupPatch() {}
11
12 /** Schedule two scans because entities may appear a few ticks after ChunkLoadEvent. */
13 public static void onChunkLoad(Object plugin, Object event) {
14 try {
15 Object chunk = call(event, "getChunk");
16 long delay = cleanupDelayTicks(plugin);
17 schedule(plugin, () -> cleanupChunk(plugin, chunk), delay);
18 schedule(plugin, () -> cleanupChunk(plugin, chunk), delay + Math.max(20L, delay));
19 } catch (Throwable t) {
20 log(plugin, "Could not schedule BirdCourier cleanup for loaded chunk", t);
21 }
22 }
23
24 private static void schedule(Object plugin, Runnable task, long delay) throws Exception {
25 Object scheduler = callStatic("org.bukkit.Bukkit", "getScheduler");
26 Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, CleanupPatch.class.getClassLoader());
27 call(scheduler, "runTaskLater", new Class<?>[]{pluginClass, Runnable.class, long.class}, plugin, task, delay);
28 }
29
30 private static void cleanupChunk(Object plugin, Object chunk) {
31 try {
32 try {
33 Object loaded = call(chunk, "isLoaded");
34 if (loaded instanceof Boolean value && !value) return;
35 } catch (Throwable ignored) {}
36 Object entitiesRaw = call(chunk, "getEntities");
37 for (Object entity : iterableEntities(entitiesRaw)) inspectLoadedEntity(plugin, entity, false);
38 } catch (Throwable t) {
39 log(plugin, "Could not clean BirdCourier visuals in loaded chunk", t);
40 }
41 }
42
43 /** Startup cleanup plus recurring sweep of all currently loaded entities. */
44 public static void cleanupAll(Object plugin) {
45 sweepAll(plugin, true);
46 if (PERIODIC_STARTED.compareAndSet(false, true)) {
47 try {
48 long interval = periodicIntervalTicks(plugin);
49 Object scheduler = callStatic("org.bukkit.Bukkit", "getScheduler");
50 Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, CleanupPatch.class.getClassLoader());
51 Runnable task = () -> sweepAll(plugin, false);
52 call(scheduler, "runTaskTimer", new Class<?>[]{pluginClass, Runnable.class, long.class, long.class},
53 plugin, task, interval, interval);
54 } catch (Throwable t) {
55 log(plugin, "Could not start periodic BirdCourier cleanup", t);
56 }
57 }
58 }
59
60 private static void sweepAll(Object plugin, boolean startup) {
61 try {
62 Object worldsRaw = callStatic("org.bukkit.Bukkit", "getWorlds");
63 for (Object world : iterableEntities(worldsRaw)) {
64 Object entitiesRaw = call(world, "getEntities");
65 for (Object entity : iterableEntities(entitiesRaw)) inspectLoadedEntity(plugin, entity, startup);
66 }
67 } catch (Throwable t) {
68 log(plugin, "Could not clean BirdCourier visuals", t);
69 }
70 }
71
72 private static Iterable<?> iterableEntities(Object raw) {
73 if (raw instanceof Iterable<?> iterable) return iterable;
74 if (raw instanceof Object[] array) return Arrays.asList(array);
75 return List.of();
76 }
77
78 private static void inspectLoadedEntity(Object plugin, Object entity, boolean startup) throws Exception {
79 UUID entityId = (UUID) call(entity, "getUniqueId");
80 Set<String> tags = lowerTags(entity);
81 Long taggedShipmentId = shipmentId(tags);
82 boolean tagged = isCourierTagged(tags);
83
84 // Exact currently registered visual is always protected after startup.
85 if (!startup && isAnyCurrentVisual(plugin, entityId)) return;
86
87 if (tagged) {
88 if (!startup && taggedShipmentId != null && isCurrentVisual(plugin, taggedShipmentId, entityId)) return;
89 remove(entity);
90 return;
91 }
92
93 if (!isConfiguredVisualType(plugin, entity)) return;
94
95 // Legacy fallback: only AI-disabled mobs of a courier-capable type are
96 // considered old BirdCourier visuals. Gravity-off or invulnerable alone
97 // are deliberately NOT sufficient: legitimate mobs can have those states.
98 if (removeAllAiDisabledConfiguredType(plugin) && hasAiDisabled(entity)) {
99 remove(entity); return;
100 }
101
102 // Deprecated broad-profile options are intentionally ignored for safety.
103 // Tagged BirdCourier entities are still handled above.
104 }
105
106 private static Set<String> lowerTags(Object entity) {
107 try {
108 Object raw = call(entity, "getScoreboardTags");
109 Set<String> tags = new HashSet<>();
110 if (raw instanceof Iterable<?> iterable)
111 for (Object tag : iterable) tags.add(String.valueOf(tag).toLowerCase(Locale.ROOT));
112 return tags;
113 } catch (Throwable ignored) { return Set.of(); }
114 }
115
116 private static boolean isAnyCurrentVisual(Object plugin, UUID entityId) {
117 try {
118 Object map = getField(plugin, "shipments");
119 Object values = call(map, "values");
120 if (values instanceof Iterable<?> iterable) for (Object shipment : iterable) {
121 UUID visual = (UUID) getField(shipment, "visualId");
122 if (entityId.equals(visual)) return true;
123 }
124 } catch (Throwable ignored) {}
125 return false;
126 }
127
128 private static boolean isCurrentVisual(Object plugin, long shipmentId, UUID entityId) {
129 try {
130 Object shipment = shipment(plugin, shipmentId);
131 if (shipment == null) return false;
132 UUID currentVisual = (UUID) getField(shipment, "visualId");
133 return currentVisual != null && currentVisual.equals(entityId);
134 } catch (Throwable ignored) { return false; }
135 }
136
137 private static boolean isCourierTagged(Set<String> tags) {
138 for (String tag : tags) if (tag.equals("birdcourier") || tag.equals("bird_courier")
139 || tag.equals("birdcourier-visual") || tag.equals("birdcourier_visual")
140 || tag.startsWith("birdcourier-shipment:") || tag.startsWith("birdcourier_shipment:")
141 || tag.startsWith("birdcourier:")) return true;
142 return false;
143 }
144
145 private static Long shipmentId(Set<String> tags) {
146 String[] prefixes = {"birdcourier-shipment:", "birdcourier_shipment:", "birdcourier:"};
147 for (String tag : tags) for (String prefix : prefixes) if (tag.startsWith(prefix)) {
148 try { return Long.parseLong(tag.substring(prefix.length())); }
149 catch (NumberFormatException ignored) {}
150 }
151 return null;
152 }
153
154 private static Object shipment(Object plugin, long id) throws Exception {
155 Object map = getField(plugin, "shipments");
156 return call(map, "get", new Class<?>[]{Object.class}, id);
157 }
158
159 private static long cleanupDelayTicks(Object plugin) { return configLong(plugin, "cleanup.chunk-load-delay-ticks", 60L, 1L); }
160 private static long periodicIntervalTicks(Object plugin) { return configLong(plugin, "cleanup.periodic-interval-ticks", 100L, 20L); }
161 private static long configLong(Object plugin, String key, long def, long min) {
162 try {
163 Object config = call(plugin, "getConfig");
164 Number value = (Number) call(config, "getLong", new Class<?>[]{String.class, long.class}, key, def);
165 return Math.max(min, value.longValue());
166 } catch (Throwable ignored) { return def; }
167 }
168
169 private static boolean removeAllAiDisabledConfiguredType(Object plugin) {
170 return configBoolean(plugin, "cleanup.remove-all-ai-disabled-configured-type", true);
171 }
172 private static boolean removeConfiguredTypeWithAnyCourierFlag(Object plugin) {
173 return configBoolean(plugin, "cleanup.remove-configured-type-with-any-courier-flag", true);
174 }
175 private static boolean cleanupUntaggedProfileEnabled(Object plugin) {
176 return configBoolean(plugin, "cleanup.remove-untagged-courier-like-entities", true);
177 }
178 private static boolean configBoolean(Object plugin, String key, boolean def) {
179 try {
180 Object config = call(plugin, "getConfig");
181 return (boolean) call(config, "getBoolean", new Class<?>[]{String.class, boolean.class}, key, def);
182 } catch (Throwable ignored) { return def; }
183 }
184
185 private static boolean isConfiguredVisualType(Object plugin, Object entity) {
186 try {
187 String type = String.valueOf(call(entity, "getType")).toUpperCase(Locale.ROOT);
188 return Set.of("PARROT", "BAT", "ALLAY", "BEE", "BLAZE", "CHICKEN", "HAPPY_GHAST", "VEX").contains(type);
189 } catch (Throwable ignored) { return false; }
190 }
191
192 private static boolean hasAiDisabled(Object entity) {
193 try { Object hasAi = call(entity, "hasAI"); return hasAi instanceof Boolean ai && !ai; }
194 catch (Throwable ignored) { return false; }
195 }
196 private static boolean hasGravityDisabled(Object entity) {
197 try { Object gravity = call(entity, "hasGravity"); return gravity instanceof Boolean value && !value; }
198 catch (Throwable ignored) { return false; }
199 }
200 private static boolean isInvulnerable(Object entity) {
201 try { Object value = call(entity, "isInvulnerable"); return value instanceof Boolean b && b; }
202 catch (Throwable ignored) { return false; }
203 }
204 private static boolean looksLikeCourierVisual(Object entity) {
205 return isInvulnerable(entity) && hasGravityDisabled(entity) && hasAiDisabled(entity);
206 }
207
208 private static void remove(Object entity) {
209 try { call(entity, "remove"); } catch (Throwable ignored) {}
210 }
211
212 private static Object getField(Object object, String name) throws Exception {
213 for (Class<?> type = object.getClass(); type != null; type = type.getSuperclass()) {
214 try { Field f = type.getDeclaredField(name); f.setAccessible(true); return f.get(object); }
215 catch (NoSuchFieldException ignored) {}
216 }
217 throw new NoSuchFieldException(name);
218 }
219
220 private static Object call(Object object, String name, Object... args) throws Exception {
221 return call(object, name, new Class<?>[0], args);
222 }
223 private static Object call(Object object, String name, Class<?>[] types, Object... args) throws Exception {
224 Method method = findMethod(object.getClass(), name, types); method.setAccessible(true); return method.invoke(object, args);
225 }
226 private static Object callStatic(String className, String name, Object... args) throws Exception {
227 Class<?> type = Class.forName(className, false, CleanupPatch.class.getClassLoader());
228 Method method = findMethod(type, name, new Class<?>[0]); method.setAccessible(true); return method.invoke(null, args);
229 }
230 private static Method findMethod(Class<?> type, String name, Class<?>[] expected) throws NoSuchMethodException {
231 // Public lookup includes inherited interface methods such as Mob#hasAI().
232 try { return type.getMethod(name, expected); }
233 catch (NoSuchMethodException ignored) {}
234 for (Class<?> current = type; current != null; current = current.getSuperclass()) {
235 for (Method method : current.getDeclaredMethods()) {
236 if (!method.getName().equals(name) || method.getParameterCount() != expected.length) continue;
237 Class<?>[] actual = method.getParameterTypes(); boolean ok = true;
238 for (int i=0;i<actual.length;i++) if (!wrap(actual[i]).isAssignableFrom(wrap(expected[i]))) { ok=false; break; }
239 if (ok) return method;
240 }
241 for (Class<?> iface : current.getInterfaces()) {
242 try { return findMethod(iface, name, expected); }
243 catch (NoSuchMethodException ignored) {}
244 }
245 }
246 throw new NoSuchMethodException(type.getName()+"."+name);
247 }
248 private static Class<?> wrap(Class<?> c) {
249 if (!c.isPrimitive()) return c;
250 if (c == boolean.class) return Boolean.class;
251 if (c == int.class) return Integer.class;
252 if (c == long.class) return Long.class;
253 return c;
254 }
255 private static void log(Object plugin, String message, Throwable t) {
256 try {
257 Object logger = call(plugin, "getLogger");
258 call(logger, "log", new Class<?>[]{java.util.logging.Level.class,String.class,Throwable.class},
259 java.util.logging.Level.WARNING, message, t);
260 } catch (Throwable ignored) {}
261 }
262 }
@@ -0,0 +1,262 @@
1package nl.timfalken.birdcourier;
2
3import java.lang.reflect.*;
4import java.util.*;
5import java.util.concurrent.atomic.AtomicBoolean;
6
7/** Cleanup compatibility layer using reflection to avoid unstable Paper descriptors. */
8public final class CleanupPatch {
9 private static final AtomicBoolean PERIODIC_STARTED = new AtomicBoolean(false);
10 private CleanupPatch() {}
11
12 /** Schedule two scans because entities may appear a few ticks after ChunkLoadEvent. */
13 public static void onChunkLoad(Object plugin, Object event) {
14 try {
15 Object chunk = call(event, "getChunk");
16 long delay = cleanupDelayTicks(plugin);
17 schedule(plugin, () -> cleanupChunk(plugin, chunk), delay);
18 schedule(plugin, () -> cleanupChunk(plugin, chunk), delay + Math.max(20L, delay));
19 } catch (Throwable t) {
20 log(plugin, "Could not schedule BirdCourier cleanup for loaded chunk", t);
21 }
22 }
23
24 private static void schedule(Object plugin, Runnable task, long delay) throws Exception {
25 Object scheduler = callStatic("org.bukkit.Bukkit", "getScheduler");
26 Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, CleanupPatch.class.getClassLoader());
27 call(scheduler, "runTaskLater", new Class<?>[]{pluginClass, Runnable.class, long.class}, plugin, task, delay);
28 }
29
30 private static void cleanupChunk(Object plugin, Object chunk) {
31 try {
32 try {
33 Object loaded = call(chunk, "isLoaded");
34 if (loaded instanceof Boolean value && !value) return;
35 } catch (Throwable ignored) {}
36 Object entitiesRaw = call(chunk, "getEntities");
37 for (Object entity : iterableEntities(entitiesRaw)) inspectLoadedEntity(plugin, entity, false);
38 } catch (Throwable t) {
39 log(plugin, "Could not clean BirdCourier visuals in loaded chunk", t);
40 }
41 }
42
43 /** Startup cleanup plus recurring sweep of all currently loaded entities. */
44 public static void cleanupAll(Object plugin) {
45 sweepAll(plugin, true);
46 if (PERIODIC_STARTED.compareAndSet(false, true)) {
47 try {
48 long interval = periodicIntervalTicks(plugin);
49 Object scheduler = callStatic("org.bukkit.Bukkit", "getScheduler");
50 Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, CleanupPatch.class.getClassLoader());
51 Runnable task = () -> sweepAll(plugin, false);
52 call(scheduler, "runTaskTimer", new Class<?>[]{pluginClass, Runnable.class, long.class, long.class},
53 plugin, task, interval, interval);
54 } catch (Throwable t) {
55 log(plugin, "Could not start periodic BirdCourier cleanup", t);
56 }
57 }
58 }
59
60 private static void sweepAll(Object plugin, boolean startup) {
61 try {
62 Object worldsRaw = callStatic("org.bukkit.Bukkit", "getWorlds");
63 for (Object world : iterableEntities(worldsRaw)) {
64 Object entitiesRaw = call(world, "getEntities");
65 for (Object entity : iterableEntities(entitiesRaw)) inspectLoadedEntity(plugin, entity, startup);
66 }
67 } catch (Throwable t) {
68 log(plugin, "Could not clean BirdCourier visuals", t);
69 }
70 }
71
72 private static Iterable<?> iterableEntities(Object raw) {
73 if (raw instanceof Iterable<?> iterable) return iterable;
74 if (raw instanceof Object[] array) return Arrays.asList(array);
75 return List.of();
76 }
77
78 private static void inspectLoadedEntity(Object plugin, Object entity, boolean startup) throws Exception {
79 UUID entityId = (UUID) call(entity, "getUniqueId");
80 Set<String> tags = lowerTags(entity);
81 Long taggedShipmentId = shipmentId(tags);
82 boolean tagged = isCourierTagged(tags);
83
84 // Exact currently registered visual is always protected after startup.
85 if (!startup && isAnyCurrentVisual(plugin, entityId)) return;
86
87 if (tagged) {
88 if (!startup && taggedShipmentId != null && isCurrentVisual(plugin, taggedShipmentId, entityId)) return;
89 remove(entity);
90 return;
91 }
92
93 if (!isConfiguredVisualType(plugin, entity)) return;
94
95 // Legacy fallback: only AI-disabled mobs of a courier-capable type are
96 // considered old BirdCourier visuals. Gravity-off or invulnerable alone
97 // are deliberately NOT sufficient: legitimate mobs can have those states.
98 if (removeAllAiDisabledConfiguredType(plugin) && hasAiDisabled(entity)) {
99 remove(entity); return;
100 }
101
102 // Deprecated broad-profile options are intentionally ignored for safety.
103 // Tagged BirdCourier entities are still handled above.
104 }
105
106 private static Set<String> lowerTags(Object entity) {
107 try {
108 Object raw = call(entity, "getScoreboardTags");
109 Set<String> tags = new HashSet<>();
110 if (raw instanceof Iterable<?> iterable)
111 for (Object tag : iterable) tags.add(String.valueOf(tag).toLowerCase(Locale.ROOT));
112 return tags;
113 } catch (Throwable ignored) { return Set.of(); }
114 }
115
116 private static boolean isAnyCurrentVisual(Object plugin, UUID entityId) {
117 try {
118 Object map = getField(plugin, "shipments");
119 Object values = call(map, "values");
120 if (values instanceof Iterable<?> iterable) for (Object shipment : iterable) {
121 UUID visual = (UUID) getField(shipment, "visualId");
122 if (entityId.equals(visual)) return true;
123 }
124 } catch (Throwable ignored) {}
125 return false;
126 }
127
128 private static boolean isCurrentVisual(Object plugin, long shipmentId, UUID entityId) {
129 try {
130 Object shipment = shipment(plugin, shipmentId);
131 if (shipment == null) return false;
132 UUID currentVisual = (UUID) getField(shipment, "visualId");
133 return currentVisual != null && currentVisual.equals(entityId);
134 } catch (Throwable ignored) { return false; }
135 }
136
137 private static boolean isCourierTagged(Set<String> tags) {
138 for (String tag : tags) if (tag.equals("birdcourier") || tag.equals("bird_courier")
139 || tag.equals("birdcourier-visual") || tag.equals("birdcourier_visual")
140 || tag.startsWith("birdcourier-shipment:") || tag.startsWith("birdcourier_shipment:")
141 || tag.startsWith("birdcourier:")) return true;
142 return false;
143 }
144
145 private static Long shipmentId(Set<String> tags) {
146 String[] prefixes = {"birdcourier-shipment:", "birdcourier_shipment:", "birdcourier:"};
147 for (String tag : tags) for (String prefix : prefixes) if (tag.startsWith(prefix)) {
148 try { return Long.parseLong(tag.substring(prefix.length())); }
149 catch (NumberFormatException ignored) {}
150 }
151 return null;
152 }
153
154 private static Object shipment(Object plugin, long id) throws Exception {
155 Object map = getField(plugin, "shipments");
156 return call(map, "get", new Class<?>[]{Object.class}, id);
157 }
158
159 private static long cleanupDelayTicks(Object plugin) { return configLong(plugin, "cleanup.chunk-load-delay-ticks", 60L, 1L); }
160 private static long periodicIntervalTicks(Object plugin) { return configLong(plugin, "cleanup.periodic-interval-ticks", 100L, 20L); }
161 private static long configLong(Object plugin, String key, long def, long min) {
162 try {
163 Object config = call(plugin, "getConfig");
164 Number value = (Number) call(config, "getLong", new Class<?>[]{String.class, long.class}, key, def);
165 return Math.max(min, value.longValue());
166 } catch (Throwable ignored) { return def; }
167 }
168
169 private static boolean removeAllAiDisabledConfiguredType(Object plugin) {
170 return configBoolean(plugin, "cleanup.remove-all-ai-disabled-configured-type", true);
171 }
172 private static boolean removeConfiguredTypeWithAnyCourierFlag(Object plugin) {
173 return configBoolean(plugin, "cleanup.remove-configured-type-with-any-courier-flag", true);
174 }
175 private static boolean cleanupUntaggedProfileEnabled(Object plugin) {
176 return configBoolean(plugin, "cleanup.remove-untagged-courier-like-entities", true);
177 }
178 private static boolean configBoolean(Object plugin, String key, boolean def) {
179 try {
180 Object config = call(plugin, "getConfig");
181 return (boolean) call(config, "getBoolean", new Class<?>[]{String.class, boolean.class}, key, def);
182 } catch (Throwable ignored) { return def; }
183 }
184
185 private static boolean isConfiguredVisualType(Object plugin, Object entity) {
186 try {
187 String type = String.valueOf(call(entity, "getType")).toUpperCase(Locale.ROOT);
188 return Set.of("PARROT", "BAT", "ALLAY", "BEE", "BLAZE", "CHICKEN", "HAPPY_GHAST", "VEX").contains(type);
189 } catch (Throwable ignored) { return false; }
190 }
191
192 private static boolean hasAiDisabled(Object entity) {
193 try { Object hasAi = call(entity, "hasAI"); return hasAi instanceof Boolean ai && !ai; }
194 catch (Throwable ignored) { return false; }
195 }
196 private static boolean hasGravityDisabled(Object entity) {
197 try { Object gravity = call(entity, "hasGravity"); return gravity instanceof Boolean value && !value; }
198 catch (Throwable ignored) { return false; }
199 }
200 private static boolean isInvulnerable(Object entity) {
201 try { Object value = call(entity, "isInvulnerable"); return value instanceof Boolean b && b; }
202 catch (Throwable ignored) { return false; }
203 }
204 private static boolean looksLikeCourierVisual(Object entity) {
205 return isInvulnerable(entity) && hasGravityDisabled(entity) && hasAiDisabled(entity);
206 }
207
208 private static void remove(Object entity) {
209 try { call(entity, "remove"); } catch (Throwable ignored) {}
210 }
211
212 private static Object getField(Object object, String name) throws Exception {
213 for (Class<?> type = object.getClass(); type != null; type = type.getSuperclass()) {
214 try { Field f = type.getDeclaredField(name); f.setAccessible(true); return f.get(object); }
215 catch (NoSuchFieldException ignored) {}
216 }
217 throw new NoSuchFieldException(name);
218 }
219
220 private static Object call(Object object, String name, Object... args) throws Exception {
221 return call(object, name, new Class<?>[0], args);
222 }
223 private static Object call(Object object, String name, Class<?>[] types, Object... args) throws Exception {
224 Method method = findMethod(object.getClass(), name, types); method.setAccessible(true); return method.invoke(object, args);
225 }
226 private static Object callStatic(String className, String name, Object... args) throws Exception {
227 Class<?> type = Class.forName(className, false, CleanupPatch.class.getClassLoader());
228 Method method = findMethod(type, name, new Class<?>[0]); method.setAccessible(true); return method.invoke(null, args);
229 }
230 private static Method findMethod(Class<?> type, String name, Class<?>[] expected) throws NoSuchMethodException {
231 // Public lookup includes inherited interface methods such as Mob#hasAI().
232 try { return type.getMethod(name, expected); }
233 catch (NoSuchMethodException ignored) {}
234 for (Class<?> current = type; current != null; current = current.getSuperclass()) {
235 for (Method method : current.getDeclaredMethods()) {
236 if (!method.getName().equals(name) || method.getParameterCount() != expected.length) continue;
237 Class<?>[] actual = method.getParameterTypes(); boolean ok = true;
238 for (int i=0;i<actual.length;i++) if (!wrap(actual[i]).isAssignableFrom(wrap(expected[i]))) { ok=false; break; }
239 if (ok) return method;
240 }
241 for (Class<?> iface : current.getInterfaces()) {
242 try { return findMethod(iface, name, expected); }
243 catch (NoSuchMethodException ignored) {}
244 }
245 }
246 throw new NoSuchMethodException(type.getName()+"."+name);
247 }
248 private static Class<?> wrap(Class<?> c) {
249 if (!c.isPrimitive()) return c;
250 if (c == boolean.class) return Boolean.class;
251 if (c == int.class) return Integer.class;
252 if (c == long.class) return Long.class;
253 return c;
254 }
255 private static void log(Object plugin, String message, Throwable t) {
256 try {
257 Object logger = call(plugin, "getLogger");
258 call(logger, "log", new Class<?>[]{java.util.logging.Level.class,String.class,Throwable.class},
259 java.util.logging.Level.WARNING, message, t);
260 } catch (Throwable ignored) {}
261 }
262}
src/main/java/nl/timfalken/birdcourier/CourierChoicePatch.java added +257 −0
@@ -0,0 +1,257 @@
1 package nl.timfalken.birdcourier;
2
3 import java.io.*;
4 import java.lang.reflect.*;
5 import java.nio.charset.StandardCharsets;
6 import java.nio.file.*;
7 import java.util.*;
8 import java.util.concurrent.atomic.AtomicLong;
9
10 /** Runtime compatibility layer for per-player courier selection and visual setup. */
11 public final class CourierChoicePatch {
12 private static final List<String> ALLOWED = List.of("allay", "bat", "bee", "blaze", "chicken", "baby_chicken", "ghast", "parrot", "vex");
13 private static final Map<UUID, String> CHOICES = new HashMap<>();
14 private static Path choicesFile;
15
16 private CourierChoicePatch() {}
17
18 public static void install(Object plugin) {
19 try {
20 Object dataFolder = call(plugin, "getDataFolder");
21 Path dir = ((File) dataFolder).toPath();
22 Files.createDirectories(dir);
23 choicesFile = dir.resolve("couriers.properties");
24 loadChoices();
25
26 Object command = call(plugin, "getCommand", new Class<?>[]{String.class}, "courier");
27 if (command != null) {
28 ClassLoader cl = CourierChoicePatch.class.getClassLoader();
29 Class<?> executorType = Class.forName("org.bukkit.command.CommandExecutor", false, cl);
30 call(command, "setExecutor", new Class<?>[]{executorType}, plugin);
31
32 Class<?> tabType = Class.forName("org.bukkit.command.TabCompleter", false, cl);
33 Object completer = Proxy.newProxyInstance(cl, new Class<?>[]{tabType}, (proxy, method, args) -> {
34 if (!"onTabComplete".equals(method.getName())) return null;
35 String[] words = args != null && args.length >= 4 && args[3] instanceof String[] a ? a : new String[0];
36 if (words.length != 1) return List.of();
37 String prefix = words[0].toLowerCase(Locale.ROOT);
38 return ALLOWED.stream().filter(v -> v.startsWith(prefix)).toList();
39 });
40 call(command, "setTabCompleter", new Class<?>[]{tabType}, completer);
41 }
42 } catch (Throwable t) {
43 log(plugin, "Could not initialise /courier", t);
44 }
45 }
46
47 public static boolean onCommand(Object plugin, Object sender, Object command, String label, String[] args) {
48 try {
49 String name = String.valueOf(call(command, "getName"));
50 if ("courier".equalsIgnoreCase(name)) return handleCourier(plugin, sender, args);
51 if ("send".equalsIgnoreCase(name)) return handleSend(plugin, sender, args);
52
53 if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
54 call(plugin, "reloadConfig");
55 invokePrivate(plugin, "startTasks");
56 send(sender, "BirdCourier reloaded.");
57 return true;
58 }
59 Object shipments = getField(plugin, "shipments");
60 int size = ((Map<?,?>) shipments).size();
61 send(sender, "BirdCourier: " + size + " active shipment(s).");
62 return true;
63 } catch (Throwable t) {
64 log(plugin, "Command failed: " + t.getClass().getSimpleName() + (t.getMessage()==null?"":": "+t.getMessage()), t);
65 return true;
66 }
67 }
68
69 private static boolean handleCourier(Object plugin, Object sender, String[] args) throws Exception {
70 Class<?> playerType = classFor("org.bukkit.entity.Player");
71 if (!playerType.isInstance(sender)) {
72 send(sender, "This command can only be used by a player.");
73 return true;
74 }
75 if (args.length != 1) {
76 send(sender, "Usage: /courier <" + String.join("|", ALLOWED) + ">");
77 return true;
78 }
79 String choice = args[0].toLowerCase(Locale.ROOT);
80 if (!ALLOWED.contains(choice)) {
81 send(sender, "Unknown courier type. Allowed: " + String.join(", ", ALLOWED));
82 return true;
83 }
84 UUID playerId = (UUID) call(sender, "getUniqueId");
85 CHOICES.put(playerId, choice);
86 saveChoices();
87 send(sender, "Courier set to " + displayChoice(choice) + ".");
88 return true;
89 }
90
91 private static boolean handleSend(Object plugin, Object sender, String[] args) throws Exception {
92 Class<?> playerType = classFor("org.bukkit.entity.Player");
93 if (!playerType.isInstance(sender)) return true;
94 Object from = sender;
95 if (args.length != 1) { send(from, msg(plugin, "target-required")); return true; }
96 Object target = callStatic("org.bukkit.Bukkit", "getPlayerExact", new Class<?>[]{String.class}, args[0]);
97 if (target == null || !(boolean) call(target, "isOnline")) { send(from, msg(plugin, "target-offline")); return true; }
98 UUID fromId = (UUID) call(from, "getUniqueId");
99 UUID targetId = (UUID) call(target, "getUniqueId");
100 if (targetId.equals(fromId)) { send(from, msg(plugin, "cannot-send-self")); return true; }
101
102 Object inventory = call(from, "getInventory");
103 Object held = call(inventory, "getItemInMainHand");
104 if (!validItem(held)) { send(from, msg(plugin, "empty-hand")); return true; }
105 Object payload = call(held, "clone");
106
107 AtomicLong nextId = (AtomicLong) getField(plugin, "nextId");
108 long id = nextId.getAndIncrement();
109 Object start = call(from, "getEyeLocation");
110 call(start, "add", new Class<?>[]{double.class,double.class,double.class}, 0.0, 0.4, 0.0);
111 Object world = call(start, "getWorld");
112 UUID worldId = (UUID) call(world, "getUID");
113
114 String choice = CHOICES.get(fromId);
115 if (choice == null) {
116 Object config = call(plugin, "getConfig");
117 choice = String.valueOf(call(config, "getString", new Class<?>[]{String.class,String.class}, "visual.entity-type", "PARROT")).toLowerCase(Locale.ROOT);
118 if (!ALLOWED.contains(choice)) choice = "parrot";
119 }
120 String visualType = storageType(choice);
121 String variant;
122 if ("PARROT".equals(visualType)) {
123 variant = String.valueOf(invokePrivate(plugin, "chooseVisualVariant", new Class<?>[]{String.class}, visualType));
124 } else if ("baby_chicken".equals(choice)) {
125 variant = "BABY";
126 } else {
127 variant = "";
128 }
129
130 Class<?> shipmentClass = nested(plugin.getClass(), "Shipment");
131 Class<?> stateClass = nested(plugin.getClass(), "State");
132 @SuppressWarnings({"unchecked","rawtypes"})
133 Object state = Enum.valueOf((Class<? extends Enum>) stateClass.asSubclass(Enum.class), "TO_TARGET");
134 Constructor<?> ctor = Arrays.stream(shipmentClass.getDeclaredConstructors()).filter(c -> c.getParameterCount() == 11).findFirst().orElseThrow();
135 ctor.setAccessible(true);
136 Object shipment = ctor.newInstance(id, fromId, targetId, payload, worldId,
137 ((Number)call(start,"getX")).doubleValue(), ((Number)call(start,"getY")).doubleValue(), ((Number)call(start,"getZ")).doubleValue(),
138 state, visualType, variant);
139 @SuppressWarnings("unchecked") Map<Long,Object> shipments = (Map<Long,Object>) getField(plugin, "shipments");
140 shipments.put(id, shipment);
141 invokePrivate(plugin, "saveShipments");
142 setMainHand(inventory, null);
143 send(from, msg(plugin, "sent").replace("{player}", String.valueOf(call(target, "getName"))));
144 return true;
145 }
146
147 public static void ensureVisual(Object plugin, Object shipment, Object world, Object at) {
148 try {
149 UUID current = (UUID) getField(shipment, "visualId");
150 if (current != null) {
151 Object existing = callStatic("org.bukkit.Bukkit", "getEntity", new Class<?>[]{UUID.class}, current);
152 if (existing != null && (boolean) call(existing, "isValid")) return;
153 }
154
155 String visualType = String.valueOf(getField(shipment, "visualType"));
156 Object entityType = enumValue("org.bukkit.entity.EntityType", visualType);
157 Object entity = call(world, "spawnEntity", new Class<?>[]{classFor("org.bukkit.Location"), classFor("org.bukkit.entity.EntityType")}, at, entityType);
158
159 call(entity, "setInvulnerable", new Class<?>[]{boolean.class}, true);
160 Object config = call(plugin, "getConfig");
161 boolean silent = (boolean) call(config, "getBoolean", new Class<?>[]{String.class,boolean.class}, "visual.silent", false);
162 call(entity, "setSilent", new Class<?>[]{boolean.class}, silent);
163 call(entity, "setGravity", new Class<?>[]{boolean.class}, false);
164 call(entity, "setPersistent", new Class<?>[]{boolean.class}, false);
165
166 if (isInstance("org.bukkit.entity.Mob", entity)) safeCall(entity, "setAI", new Class<?>[]{boolean.class}, false);
167 if ("BAT".equalsIgnoreCase(visualType)) {
168 safeCall(entity, "setAwake", new Class<?>[]{boolean.class}, true);
169 }
170 if ("CHICKEN".equalsIgnoreCase(visualType)) {
171 if ("BABY".equalsIgnoreCase(String.valueOf(getField(shipment, "visualVariant")))) safeCall(entity, "setBaby");
172 else safeCall(entity, "setAdult");
173 safeCall(entity, "setAgeLock", new Class<?>[]{boolean.class}, true);
174 }
175 if ("HAPPY_GHAST".equalsIgnoreCase(visualType)) {
176 safeCall(entity, "setBaby");
177 safeCall(entity, "setAgeLock", new Class<?>[]{boolean.class}, true);
178 }
179
180 String variant = String.valueOf(getField(shipment, "visualVariant"));
181 if (!variant.isBlank()) invokePrivate(plugin, "applyVisualVariant", new Class<?>[]{classFor("org.bukkit.entity.Entity"), String.class}, entity, variant);
182
183 Object payload = getField(shipment, "payload");
184 equipHeldItem(entity, payload);
185
186 call(entity, "addScoreboardTag", new Class<?>[]{String.class}, "birdcourier");
187 long id = ((Number)getField(shipment, "id")).longValue();
188 call(entity, "addScoreboardTag", new Class<?>[]{String.class}, "birdcourier-shipment:" + id);
189 setField(shipment, "visualId", call(entity, "getUniqueId"));
190 } catch (Throwable t) {
191 log(plugin, "Could not create courier visual", t);
192 }
193 }
194
195 private static void equipHeldItem(Object entity, Object payload) {
196 try {
197 Object equipment = call(entity, "getEquipment");
198 if (equipment == null || payload == null) return;
199 Object copy = call(payload, "clone");
200 Method setter = Arrays.stream(equipment.getClass().getMethods())
201 .filter(m -> m.getName().equals("setItemInMainHand") && m.getParameterCount() == 1)
202 .findFirst().orElse(null);
203 if (setter != null) setter.invoke(equipment, copy);
204 } catch (Throwable ignored) {
205 // Courier type has no usable/rendered hand slot.
206 }
207 }
208
209 private static String storageType(String choice) { if ("ghast".equals(choice)) return "HAPPY_GHAST"; if ("baby_chicken".equals(choice)) return "CHICKEN"; return choice.toUpperCase(Locale.ROOT); }
210 private static String displayChoice(String choice) { if ("ghast".equals(choice)) return "Ghastling"; if ("baby_chicken".equals(choice)) return "Baby Chicken"; return Character.toUpperCase(choice.charAt(0)) + choice.substring(1); }
211
212 private static void loadChoices() {
213 CHOICES.clear();
214 if (choicesFile == null || !Files.exists(choicesFile)) return;
215 Properties p = new Properties();
216 try (Reader r = Files.newBufferedReader(choicesFile, StandardCharsets.UTF_8)) {
217 p.load(r);
218 for (String k : p.stringPropertyNames()) {
219 String v = p.getProperty(k, "").toLowerCase(Locale.ROOT);
220 if (ALLOWED.contains(v)) CHOICES.put(UUID.fromString(k), v);
221 }
222 } catch (Exception ignored) {}
223 }
224
225 private static void saveChoices() {
226 if (choicesFile == null) return;
227 Properties p = new Properties();
228 CHOICES.forEach((k,v) -> p.setProperty(k.toString(), v));
229 try {
230 Path tmp = Path.of(choicesFile + ".tmp");
231 try (Writer w = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8)) { p.store(w, "BirdCourier per-player courier choices"); }
232 Files.move(tmp, choicesFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
233 } catch (Exception ignored) {}
234 }
235
236 private static String msg(Object plugin, String key) throws Exception { return String.valueOf(invokePrivate(plugin, "msg", new Class<?>[]{String.class}, key)); }
237 private static void send(Object sender, String text) { try { call(sender, "sendMessage", new Class<?>[]{String.class}, text); } catch (Throwable ignored) {} }
238 private static boolean validItem(Object item) throws Exception { if (item == null) return false; Object type = call(item,"getType"); return !(boolean)call(type,"isAir") && ((Number)call(item,"getAmount")).intValue() > 0; }
239 private static void setMainHand(Object inv, Object item) throws Exception { Method m = Arrays.stream(inv.getClass().getMethods()).filter(x -> x.getName().equals("setItemInMainHand") && x.getParameterCount()==1).findFirst().orElseThrow(); m.invoke(inv,item); }
240 private static Class<?> nested(Class<?> owner, String simple) { return Arrays.stream(owner.getDeclaredClasses()).filter(c -> c.getSimpleName().equals(simple)).findFirst().orElseThrow(); }
241 @SuppressWarnings({"unchecked","rawtypes"}) private static Object enumValue(String className, String value) throws Exception { Class<?> c=classFor(className); return Enum.valueOf((Class<? extends Enum>)c.asSubclass(Enum.class), value); }
242 private static boolean isInstance(String className,Object o)throws Exception{return classFor(className).isInstance(o);}
243 private static Class<?> classFor(String n)throws ClassNotFoundException{return Class.forName(n,false,CourierChoicePatch.class.getClassLoader());}
244 private static Object getField(Object o,String n)throws Exception{for(Class<?> c=o.getClass();c!=null;c=c.getSuperclass())try{Field f=c.getDeclaredField(n);f.setAccessible(true);return f.get(o);}catch(NoSuchFieldException ignored){}throw new NoSuchFieldException(n);}
245 private static void setField(Object o,String n,Object v)throws Exception{for(Class<?> c=o.getClass();c!=null;c=c.getSuperclass())try{Field f=c.getDeclaredField(n);f.setAccessible(true);f.set(o,v);return;}catch(NoSuchFieldException ignored){}throw new NoSuchFieldException(n);}
246 private static Object invokePrivate(Object o,String n,Object...args)throws Exception{return invokePrivate(o,n,new Class<?>[0],args);}
247 private static Object invokePrivate(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}
248 private static Object call(Object o,String n,Object...args)throws Exception{return call(o,n,new Class<?>[0],args);}
249 private static Object call(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}
250 private static Object safeCall(Object o,String n,Object...args){try{return call(o,n,new Class<?>[0],args);}catch(Throwable ignored){return null;}}
251 private static Object safeCall(Object o,String n,Class<?>[]types,Object...args){try{return call(o,n,types,args);}catch(Throwable ignored){return null;}}
252 private static Object callStatic(String cn,String n,Class<?>[]types,Object...args)throws Exception{Class<?> c=classFor(cn);Method m=findMethod(c,n,types);m.setAccessible(true);return m.invoke(null,args);}
253 private static Method findMethod(Class<?> c,String n,Class<?>[]types)throws NoSuchMethodException{for(Class<?> k=c;k!=null;k=k.getSuperclass()){for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),types))return m;for(Class<?> i:k.getInterfaces())for(Method m:i.getMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),types))return m;}throw new NoSuchMethodException(c.getName()+"."+n);}
254 private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}
255 private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==double.class)return Double.class;if(c==boolean.class)return Boolean.class;if(c==float.class)return Float.class;return c;}
256 private static void log(Object plugin,String msg,Throwable t){try{Object l=call(plugin,"getLogger");call(l,"log",new Class<?>[]{java.util.logging.Level.class,String.class,Throwable.class},java.util.logging.Level.WARNING,msg,t);}catch(Throwable ignored){}}
257 }
@@ -0,0 +1,257 @@
1package nl.timfalken.birdcourier;
2
3import java.io.*;
4import java.lang.reflect.*;
5import java.nio.charset.StandardCharsets;
6import java.nio.file.*;
7import java.util.*;
8import java.util.concurrent.atomic.AtomicLong;
9
10/** Runtime compatibility layer for per-player courier selection and visual setup. */
11public final class CourierChoicePatch {
12 private static final List<String> ALLOWED = List.of("allay", "bat", "bee", "blaze", "chicken", "baby_chicken", "ghast", "parrot", "vex");
13 private static final Map<UUID, String> CHOICES = new HashMap<>();
14 private static Path choicesFile;
15
16 private CourierChoicePatch() {}
17
18 public static void install(Object plugin) {
19 try {
20 Object dataFolder = call(plugin, "getDataFolder");
21 Path dir = ((File) dataFolder).toPath();
22 Files.createDirectories(dir);
23 choicesFile = dir.resolve("couriers.properties");
24 loadChoices();
25
26 Object command = call(plugin, "getCommand", new Class<?>[]{String.class}, "courier");
27 if (command != null) {
28 ClassLoader cl = CourierChoicePatch.class.getClassLoader();
29 Class<?> executorType = Class.forName("org.bukkit.command.CommandExecutor", false, cl);
30 call(command, "setExecutor", new Class<?>[]{executorType}, plugin);
31
32 Class<?> tabType = Class.forName("org.bukkit.command.TabCompleter", false, cl);
33 Object completer = Proxy.newProxyInstance(cl, new Class<?>[]{tabType}, (proxy, method, args) -> {
34 if (!"onTabComplete".equals(method.getName())) return null;
35 String[] words = args != null && args.length >= 4 && args[3] instanceof String[] a ? a : new String[0];
36 if (words.length != 1) return List.of();
37 String prefix = words[0].toLowerCase(Locale.ROOT);
38 return ALLOWED.stream().filter(v -> v.startsWith(prefix)).toList();
39 });
40 call(command, "setTabCompleter", new Class<?>[]{tabType}, completer);
41 }
42 } catch (Throwable t) {
43 log(plugin, "Could not initialise /courier", t);
44 }
45 }
46
47 public static boolean onCommand(Object plugin, Object sender, Object command, String label, String[] args) {
48 try {
49 String name = String.valueOf(call(command, "getName"));
50 if ("courier".equalsIgnoreCase(name)) return handleCourier(plugin, sender, args);
51 if ("send".equalsIgnoreCase(name)) return handleSend(plugin, sender, args);
52
53 if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
54 call(plugin, "reloadConfig");
55 invokePrivate(plugin, "startTasks");
56 send(sender, "BirdCourier reloaded.");
57 return true;
58 }
59 Object shipments = getField(plugin, "shipments");
60 int size = ((Map<?,?>) shipments).size();
61 send(sender, "BirdCourier: " + size + " active shipment(s).");
62 return true;
63 } catch (Throwable t) {
64 log(plugin, "Command failed: " + t.getClass().getSimpleName() + (t.getMessage()==null?"":": "+t.getMessage()), t);
65 return true;
66 }
67 }
68
69 private static boolean handleCourier(Object plugin, Object sender, String[] args) throws Exception {
70 Class<?> playerType = classFor("org.bukkit.entity.Player");
71 if (!playerType.isInstance(sender)) {
72 send(sender, "This command can only be used by a player.");
73 return true;
74 }
75 if (args.length != 1) {
76 send(sender, "Usage: /courier <" + String.join("|", ALLOWED) + ">");
77 return true;
78 }
79 String choice = args[0].toLowerCase(Locale.ROOT);
80 if (!ALLOWED.contains(choice)) {
81 send(sender, "Unknown courier type. Allowed: " + String.join(", ", ALLOWED));
82 return true;
83 }
84 UUID playerId = (UUID) call(sender, "getUniqueId");
85 CHOICES.put(playerId, choice);
86 saveChoices();
87 send(sender, "Courier set to " + displayChoice(choice) + ".");
88 return true;
89 }
90
91 private static boolean handleSend(Object plugin, Object sender, String[] args) throws Exception {
92 Class<?> playerType = classFor("org.bukkit.entity.Player");
93 if (!playerType.isInstance(sender)) return true;
94 Object from = sender;
95 if (args.length != 1) { send(from, msg(plugin, "target-required")); return true; }
96 Object target = callStatic("org.bukkit.Bukkit", "getPlayerExact", new Class<?>[]{String.class}, args[0]);
97 if (target == null || !(boolean) call(target, "isOnline")) { send(from, msg(plugin, "target-offline")); return true; }
98 UUID fromId = (UUID) call(from, "getUniqueId");
99 UUID targetId = (UUID) call(target, "getUniqueId");
100 if (targetId.equals(fromId)) { send(from, msg(plugin, "cannot-send-self")); return true; }
101
102 Object inventory = call(from, "getInventory");
103 Object held = call(inventory, "getItemInMainHand");
104 if (!validItem(held)) { send(from, msg(plugin, "empty-hand")); return true; }
105 Object payload = call(held, "clone");
106
107 AtomicLong nextId = (AtomicLong) getField(plugin, "nextId");
108 long id = nextId.getAndIncrement();
109 Object start = call(from, "getEyeLocation");
110 call(start, "add", new Class<?>[]{double.class,double.class,double.class}, 0.0, 0.4, 0.0);
111 Object world = call(start, "getWorld");
112 UUID worldId = (UUID) call(world, "getUID");
113
114 String choice = CHOICES.get(fromId);
115 if (choice == null) {
116 Object config = call(plugin, "getConfig");
117 choice = String.valueOf(call(config, "getString", new Class<?>[]{String.class,String.class}, "visual.entity-type", "PARROT")).toLowerCase(Locale.ROOT);
118 if (!ALLOWED.contains(choice)) choice = "parrot";
119 }
120 String visualType = storageType(choice);
121 String variant;
122 if ("PARROT".equals(visualType)) {
123 variant = String.valueOf(invokePrivate(plugin, "chooseVisualVariant", new Class<?>[]{String.class}, visualType));
124 } else if ("baby_chicken".equals(choice)) {
125 variant = "BABY";
126 } else {
127 variant = "";
128 }
129
130 Class<?> shipmentClass = nested(plugin.getClass(), "Shipment");
131 Class<?> stateClass = nested(plugin.getClass(), "State");
132 @SuppressWarnings({"unchecked","rawtypes"})
133 Object state = Enum.valueOf((Class<? extends Enum>) stateClass.asSubclass(Enum.class), "TO_TARGET");
134 Constructor<?> ctor = Arrays.stream(shipmentClass.getDeclaredConstructors()).filter(c -> c.getParameterCount() == 11).findFirst().orElseThrow();
135 ctor.setAccessible(true);
136 Object shipment = ctor.newInstance(id, fromId, targetId, payload, worldId,
137 ((Number)call(start,"getX")).doubleValue(), ((Number)call(start,"getY")).doubleValue(), ((Number)call(start,"getZ")).doubleValue(),
138 state, visualType, variant);
139 @SuppressWarnings("unchecked") Map<Long,Object> shipments = (Map<Long,Object>) getField(plugin, "shipments");
140 shipments.put(id, shipment);
141 invokePrivate(plugin, "saveShipments");
142 setMainHand(inventory, null);
143 send(from, msg(plugin, "sent").replace("{player}", String.valueOf(call(target, "getName"))));
144 return true;
145 }
146
147 public static void ensureVisual(Object plugin, Object shipment, Object world, Object at) {
148 try {
149 UUID current = (UUID) getField(shipment, "visualId");
150 if (current != null) {
151 Object existing = callStatic("org.bukkit.Bukkit", "getEntity", new Class<?>[]{UUID.class}, current);
152 if (existing != null && (boolean) call(existing, "isValid")) return;
153 }
154
155 String visualType = String.valueOf(getField(shipment, "visualType"));
156 Object entityType = enumValue("org.bukkit.entity.EntityType", visualType);
157 Object entity = call(world, "spawnEntity", new Class<?>[]{classFor("org.bukkit.Location"), classFor("org.bukkit.entity.EntityType")}, at, entityType);
158
159 call(entity, "setInvulnerable", new Class<?>[]{boolean.class}, true);
160 Object config = call(plugin, "getConfig");
161 boolean silent = (boolean) call(config, "getBoolean", new Class<?>[]{String.class,boolean.class}, "visual.silent", false);
162 call(entity, "setSilent", new Class<?>[]{boolean.class}, silent);
163 call(entity, "setGravity", new Class<?>[]{boolean.class}, false);
164 call(entity, "setPersistent", new Class<?>[]{boolean.class}, false);
165
166 if (isInstance("org.bukkit.entity.Mob", entity)) safeCall(entity, "setAI", new Class<?>[]{boolean.class}, false);
167 if ("BAT".equalsIgnoreCase(visualType)) {
168 safeCall(entity, "setAwake", new Class<?>[]{boolean.class}, true);
169 }
170 if ("CHICKEN".equalsIgnoreCase(visualType)) {
171 if ("BABY".equalsIgnoreCase(String.valueOf(getField(shipment, "visualVariant")))) safeCall(entity, "setBaby");
172 else safeCall(entity, "setAdult");
173 safeCall(entity, "setAgeLock", new Class<?>[]{boolean.class}, true);
174 }
175 if ("HAPPY_GHAST".equalsIgnoreCase(visualType)) {
176 safeCall(entity, "setBaby");
177 safeCall(entity, "setAgeLock", new Class<?>[]{boolean.class}, true);
178 }
179
180 String variant = String.valueOf(getField(shipment, "visualVariant"));
181 if (!variant.isBlank()) invokePrivate(plugin, "applyVisualVariant", new Class<?>[]{classFor("org.bukkit.entity.Entity"), String.class}, entity, variant);
182
183 Object payload = getField(shipment, "payload");
184 equipHeldItem(entity, payload);
185
186 call(entity, "addScoreboardTag", new Class<?>[]{String.class}, "birdcourier");
187 long id = ((Number)getField(shipment, "id")).longValue();
188 call(entity, "addScoreboardTag", new Class<?>[]{String.class}, "birdcourier-shipment:" + id);
189 setField(shipment, "visualId", call(entity, "getUniqueId"));
190 } catch (Throwable t) {
191 log(plugin, "Could not create courier visual", t);
192 }
193 }
194
195 private static void equipHeldItem(Object entity, Object payload) {
196 try {
197 Object equipment = call(entity, "getEquipment");
198 if (equipment == null || payload == null) return;
199 Object copy = call(payload, "clone");
200 Method setter = Arrays.stream(equipment.getClass().getMethods())
201 .filter(m -> m.getName().equals("setItemInMainHand") && m.getParameterCount() == 1)
202 .findFirst().orElse(null);
203 if (setter != null) setter.invoke(equipment, copy);
204 } catch (Throwable ignored) {
205 // Courier type has no usable/rendered hand slot.
206 }
207 }
208
209 private static String storageType(String choice) { if ("ghast".equals(choice)) return "HAPPY_GHAST"; if ("baby_chicken".equals(choice)) return "CHICKEN"; return choice.toUpperCase(Locale.ROOT); }
210 private static String displayChoice(String choice) { if ("ghast".equals(choice)) return "Ghastling"; if ("baby_chicken".equals(choice)) return "Baby Chicken"; return Character.toUpperCase(choice.charAt(0)) + choice.substring(1); }
211
212 private static void loadChoices() {
213 CHOICES.clear();
214 if (choicesFile == null || !Files.exists(choicesFile)) return;
215 Properties p = new Properties();
216 try (Reader r = Files.newBufferedReader(choicesFile, StandardCharsets.UTF_8)) {
217 p.load(r);
218 for (String k : p.stringPropertyNames()) {
219 String v = p.getProperty(k, "").toLowerCase(Locale.ROOT);
220 if (ALLOWED.contains(v)) CHOICES.put(UUID.fromString(k), v);
221 }
222 } catch (Exception ignored) {}
223 }
224
225 private static void saveChoices() {
226 if (choicesFile == null) return;
227 Properties p = new Properties();
228 CHOICES.forEach((k,v) -> p.setProperty(k.toString(), v));
229 try {
230 Path tmp = Path.of(choicesFile + ".tmp");
231 try (Writer w = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8)) { p.store(w, "BirdCourier per-player courier choices"); }
232 Files.move(tmp, choicesFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
233 } catch (Exception ignored) {}
234 }
235
236 private static String msg(Object plugin, String key) throws Exception { return String.valueOf(invokePrivate(plugin, "msg", new Class<?>[]{String.class}, key)); }
237 private static void send(Object sender, String text) { try { call(sender, "sendMessage", new Class<?>[]{String.class}, text); } catch (Throwable ignored) {} }
238 private static boolean validItem(Object item) throws Exception { if (item == null) return false; Object type = call(item,"getType"); return !(boolean)call(type,"isAir") && ((Number)call(item,"getAmount")).intValue() > 0; }
239 private static void setMainHand(Object inv, Object item) throws Exception { Method m = Arrays.stream(inv.getClass().getMethods()).filter(x -> x.getName().equals("setItemInMainHand") && x.getParameterCount()==1).findFirst().orElseThrow(); m.invoke(inv,item); }
240 private static Class<?> nested(Class<?> owner, String simple) { return Arrays.stream(owner.getDeclaredClasses()).filter(c -> c.getSimpleName().equals(simple)).findFirst().orElseThrow(); }
241 @SuppressWarnings({"unchecked","rawtypes"}) private static Object enumValue(String className, String value) throws Exception { Class<?> c=classFor(className); return Enum.valueOf((Class<? extends Enum>)c.asSubclass(Enum.class), value); }
242 private static boolean isInstance(String className,Object o)throws Exception{return classFor(className).isInstance(o);}
243 private static Class<?> classFor(String n)throws ClassNotFoundException{return Class.forName(n,false,CourierChoicePatch.class.getClassLoader());}
244 private static Object getField(Object o,String n)throws Exception{for(Class<?> c=o.getClass();c!=null;c=c.getSuperclass())try{Field f=c.getDeclaredField(n);f.setAccessible(true);return f.get(o);}catch(NoSuchFieldException ignored){}throw new NoSuchFieldException(n);}
245 private static void setField(Object o,String n,Object v)throws Exception{for(Class<?> c=o.getClass();c!=null;c=c.getSuperclass())try{Field f=c.getDeclaredField(n);f.setAccessible(true);f.set(o,v);return;}catch(NoSuchFieldException ignored){}throw new NoSuchFieldException(n);}
246 private static Object invokePrivate(Object o,String n,Object...args)throws Exception{return invokePrivate(o,n,new Class<?>[0],args);}
247 private static Object invokePrivate(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}
248 private static Object call(Object o,String n,Object...args)throws Exception{return call(o,n,new Class<?>[0],args);}
249 private static Object call(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}
250 private static Object safeCall(Object o,String n,Object...args){try{return call(o,n,new Class<?>[0],args);}catch(Throwable ignored){return null;}}
251 private static Object safeCall(Object o,String n,Class<?>[]types,Object...args){try{return call(o,n,types,args);}catch(Throwable ignored){return null;}}
252 private static Object callStatic(String cn,String n,Class<?>[]types,Object...args)throws Exception{Class<?> c=classFor(cn);Method m=findMethod(c,n,types);m.setAccessible(true);return m.invoke(null,args);}
253 private static Method findMethod(Class<?> c,String n,Class<?>[]types)throws NoSuchMethodException{for(Class<?> k=c;k!=null;k=k.getSuperclass()){for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),types))return m;for(Class<?> i:k.getInterfaces())for(Method m:i.getMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),types))return m;}throw new NoSuchMethodException(c.getName()+"."+n);}
254 private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}
255 private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==double.class)return Double.class;if(c==boolean.class)return Boolean.class;if(c==float.class)return Float.class;return c;}
256 private static void log(Object plugin,String msg,Throwable t){try{Object l=call(plugin,"getLogger");call(l,"log",new Class<?>[]{java.util.logging.Level.class,String.class,Throwable.class},java.util.logging.Level.WARNING,msg,t);}catch(Throwable ignored){}}
257}
src/main/resources/config.yml added +84 −0
@@ -0,0 +1,84 @@
1 visual:
2 entity-type: PARROT
3 silent: false
4
5 flight:
6 speed-blocks-per-second: 10.0
7 # Virtual travel through unloaded chunks is this many times faster.
8 unloaded-speed-multiplier: 5.0
9 visible-chunk-margin: 0
10 preferred-height-above-ground: 10
11 direct-approach-distance: 15.0
12 delivery-distance: 2.0
13 # Allowed vertical band relative to the recipient's feet. This includes body/head
14 # height without allowing delivery from a normal floor above or below.
15 delivery-min-relative-y: -0.5
16 delivery-max-relative-y: 2.25
17 route-search-radius: 48
18 # Long trips are split into local pathfinding stages.
19 local-stage-distance: 28.0
20 # Inside this distance the courier computes the final detailed route.
21 local-approach-distance: 36.0
22
23 # Begin reverse pathfinding from the recipient toward a reachable loaded-region edge.
24 virtual-arrival-trigger-distance: 72.0
25 # Weighted A* explores fewer nodes at the cost of a slightly less optimal route.
26 # 1.0 is classic A*; 1.25-1.5 is usually a good performance range.
27 weighted-a-star: 1.35
28 maximum-path-nodes: 12000
29
30 # Limit expensive new route calculations across all active couriers.
31 maximum-pathfinds-per-tick: 1
32
33 # Delay before retrying after the actual movement corridor becomes blocked.
34 blocked-retry-delay-ticks: 4
35 path-recalculate-ticks: 14
36 water-cost: 6.0
37 lava-cost: 20.0
38
39 unreachable:
40 wait-seconds: 20
41 retry-interval-ticks: 20
42 orbit-radius: 2.5
43
44 portals:
45 enabled: true
46 search-radius: 100
47 # Dimension transfer happens only after the visible courier reaches this distance.
48 enter-distance: 3.0
49
50 persistence:
51 autosave-interval-ticks: 100
52
53 messages:
54 target-required: 'Usage: /send <online player>'
55 target-offline: 'That player is not online.'
56 cannot-send-self: 'You cannot send an item to yourself.'
57 empty-hand: 'Hold the item stack you want to send.'
58 sent: 'Your courier is on its way to {player}.'
59 returned: 'The courier is returning to you.'
60 delivered: 'A courier from {player} delivered {amount}x {item}.'
61 lost: 'The courier shipment was lost because neither player was available.'
62
63 # Pathfinding failures inside loaded chunks stay visible and retry after this delay.
64 # This also prevents one unreachable courier from consuming every pathfinding slot.
65 # The existing unreachable.retry-interval-ticks value is used as the cooldown.
66
67
68 # Delayed chunk cleanup gives Paper time to activate all entities after loading.
69 # 60 ticks = 3 seconds.
70 cleanup:
71 # Sweep all loaded worlds every 5 seconds as a second cleanup layer.
72 periodic-interval-ticks: 100
73
74 # Wait after a chunk loads before scanning it. 60 ticks = 3 seconds.
75 chunk-load-delay-ticks: 60
76
77 # Legacy ghost cleanup. Only courier-capable mobs with AI explicitly disabled
78 # are removed (unless they are the current visual of an active shipment).
79 # Legitimate mobs with normal AI are never removed by this fallback.
80 remove-all-ai-disabled-configured-type: true
81
82 # Deprecated unsafe heuristics. Kept for config compatibility but ignored by 1.1.3+.
83 remove-configured-type-with-any-courier-flag: false
84 remove-untagged-courier-like-entities: false
@@ -0,0 +1,84 @@
1visual:
2 entity-type: PARROT
3 silent: false
4
5flight:
6 speed-blocks-per-second: 10.0
7 # Virtual travel through unloaded chunks is this many times faster.
8 unloaded-speed-multiplier: 5.0
9 visible-chunk-margin: 0
10 preferred-height-above-ground: 10
11 direct-approach-distance: 15.0
12 delivery-distance: 2.0
13 # Allowed vertical band relative to the recipient's feet. This includes body/head
14 # height without allowing delivery from a normal floor above or below.
15 delivery-min-relative-y: -0.5
16 delivery-max-relative-y: 2.25
17 route-search-radius: 48
18 # Long trips are split into local pathfinding stages.
19 local-stage-distance: 28.0
20 # Inside this distance the courier computes the final detailed route.
21 local-approach-distance: 36.0
22
23 # Begin reverse pathfinding from the recipient toward a reachable loaded-region edge.
24 virtual-arrival-trigger-distance: 72.0
25 # Weighted A* explores fewer nodes at the cost of a slightly less optimal route.
26 # 1.0 is classic A*; 1.25-1.5 is usually a good performance range.
27 weighted-a-star: 1.35
28 maximum-path-nodes: 12000
29
30 # Limit expensive new route calculations across all active couriers.
31 maximum-pathfinds-per-tick: 1
32
33 # Delay before retrying after the actual movement corridor becomes blocked.
34 blocked-retry-delay-ticks: 4
35 path-recalculate-ticks: 14
36 water-cost: 6.0
37 lava-cost: 20.0
38
39unreachable:
40 wait-seconds: 20
41 retry-interval-ticks: 20
42 orbit-radius: 2.5
43
44portals:
45 enabled: true
46 search-radius: 100
47 # Dimension transfer happens only after the visible courier reaches this distance.
48 enter-distance: 3.0
49
50persistence:
51 autosave-interval-ticks: 100
52
53messages:
54 target-required: 'Usage: /send <online player>'
55 target-offline: 'That player is not online.'
56 cannot-send-self: 'You cannot send an item to yourself.'
57 empty-hand: 'Hold the item stack you want to send.'
58 sent: 'Your courier is on its way to {player}.'
59 returned: 'The courier is returning to you.'
60 delivered: 'A courier from {player} delivered {amount}x {item}.'
61 lost: 'The courier shipment was lost because neither player was available.'
62
63# Pathfinding failures inside loaded chunks stay visible and retry after this delay.
64# This also prevents one unreachable courier from consuming every pathfinding slot.
65# The existing unreachable.retry-interval-ticks value is used as the cooldown.
66
67
68# Delayed chunk cleanup gives Paper time to activate all entities after loading.
69# 60 ticks = 3 seconds.
70cleanup:
71 # Sweep all loaded worlds every 5 seconds as a second cleanup layer.
72 periodic-interval-ticks: 100
73
74 # Wait after a chunk loads before scanning it. 60 ticks = 3 seconds.
75 chunk-load-delay-ticks: 60
76
77 # Legacy ghost cleanup. Only courier-capable mobs with AI explicitly disabled
78 # are removed (unless they are the current visual of an active shipment).
79 # Legitimate mobs with normal AI are never removed by this fallback.
80 remove-all-ai-disabled-configured-type: true
81
82 # Deprecated unsafe heuristics. Kept for config compatibility but ignored by 1.1.3+.
83 remove-configured-type-with-any-courier-flag: false
84 remove-untagged-courier-like-entities: false
src/main/resources/plugin.yml added +26 −0
@@ -0,0 +1,26 @@
1 name: BirdCourier
2 version: 1.1.3
3 main: nl.timfalken.birdcourier.BirdCourierPlugin
4 api-version: '26.2'
5 author: Tim Falken
6 description: Server-side flying item courier between online players.
7 commands:
8 send:
9 description: Send the held stack to an online player.
10 usage: /send <player>
11 permission: birdcourier.send
12 courier:
13 description: Choose your personal courier mob.
14 usage: /courier <type>
15 permission: birdcourier.courier
16 birdcourier:
17 description: Manage BirdCourier.
18 usage: /birdcourier <status|reload>
19 permission: birdcourier.admin
20 permissions:
21 birdcourier.courier:
22 default: true
23 birdcourier.send:
24 default: true
25 birdcourier.admin:
26 default: op
@@ -0,0 +1,26 @@
1name: BirdCourier
2version: 1.1.3
3main: nl.timfalken.birdcourier.BirdCourierPlugin
4api-version: '26.2'
5author: Tim Falken
6description: Server-side flying item courier between online players.
7commands:
8 send:
9 description: Send the held stack to an online player.
10 usage: /send <player>
11 permission: birdcourier.send
12 courier:
13 description: Choose your personal courier mob.
14 usage: /courier <type>
15 permission: birdcourier.courier
16 birdcourier:
17 description: Manage BirdCourier.
18 usage: /birdcourier <status|reload>
19 permission: birdcourier.admin
20permissions:
21 birdcourier.courier:
22 default: true
23 birdcourier.send:
24 default: true
25 birdcourier.admin:
26 default: op