BlueGit

timfa chestpreviews

Initial import of ChestPreview 1.0.10 with GitLab release pipeline.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-20 · 2 months ago

Hash
8d7cadf9546bcc964d9bfca50311b5dc8d4aa571
15 files changed +1526 −0
.cursor/rules/release-tags.mdc added +38 −0
@@ -0,0 +1,38 @@
1 ---
2 description: Release-tag format, when to create tags, and what the GitLab release pipeline does
3 alwaysApply: true
4 ---
5
6 # Release tags (ChestPreview)
7
8 ## Tag format
9
10 - Allowed: `X.Y.Z` or `vX.Y.Z` (digits only, no prerelease suffix).
11 - Valid: `1.0.10`, `v1.0.10`, `1.0.11`, `1.1.0`
12 - Invalid: `1.0`, `v1.0.10-beta`, `release-1.0.10`, `1.00.10` (no leading zeros in a segment)
13
14 ## Creating a release
15
16 1. Ensure release-related changes are on `master` and pushed.
17 2. Create the tag on the intended commit (usually `HEAD` of `master`).
18 3. Push only the new tag: `git push origin <tag>`.
19 4. Do **not** force-update or move an existing protected tag. If a retry is needed on the same version, delete the tag in the GitLab UI first, then recreate it.
20
21 The new version must be **strictly greater** than the previous release tag (semver compare). The pipeline fails otherwise.
22
23 ## What the pipeline does on a version tag
24
25 Triggered by `.gitlab-ci.yml` when any tag is pushed:
26
27 1. **validate** — check format and that the version is newer than prior release tags
28 2. **bump** — set version in project files (`build.gradle.kts`, `plugin.yml`, READMEs, plugin log string), commit, push to default branch with `ci.skip` (tag is **not** moved; protected tags cannot be updated)
29 3. **build** — produce `ChestPreview-<version>.jar`, upload to Package Registry
30 4. **release** — publish a GitLab Release with that jar
31 5. **rotate-token** — self-rotate `CI_PUSH_TOKEN` and write it back to CI/CD variables
32
33 ## Agent do / don't
34
35 - Do create/push a **new** version tag when the user asks to release or retag after they deleted the old tag.
36 - Do not rewrite/force-push protected tags; ask the user to delete via GitLab UI first.
37 - Do not invent non-semver tags for releases.
38 - After a failed release fix, push the fix to `master`, then recreate the version tag only if the remote tag is gone (or the user deleted it).
@@ -0,0 +1,38 @@
1---
2description: Release-tag format, when to create tags, and what the GitLab release pipeline does
3alwaysApply: true
4---
5
6# Release tags (ChestPreview)
7
8## Tag format
9
10- Allowed: `X.Y.Z` or `vX.Y.Z` (digits only, no prerelease suffix).
11- Valid: `1.0.10`, `v1.0.10`, `1.0.11`, `1.1.0`
12- Invalid: `1.0`, `v1.0.10-beta`, `release-1.0.10`, `1.00.10` (no leading zeros in a segment)
13
14## Creating a release
15
161. Ensure release-related changes are on `master` and pushed.
172. Create the tag on the intended commit (usually `HEAD` of `master`).
183. Push only the new tag: `git push origin <tag>`.
194. Do **not** force-update or move an existing protected tag. If a retry is needed on the same version, delete the tag in the GitLab UI first, then recreate it.
20
21The new version must be **strictly greater** than the previous release tag (semver compare). The pipeline fails otherwise.
22
23## What the pipeline does on a version tag
24
25Triggered by `.gitlab-ci.yml` when any tag is pushed:
26
271. **validate** — check format and that the version is newer than prior release tags
282. **bump** — set version in project files (`build.gradle.kts`, `plugin.yml`, READMEs, plugin log string), commit, push to default branch with `ci.skip` (tag is **not** moved; protected tags cannot be updated)
293. **build** — produce `ChestPreview-<version>.jar`, upload to Package Registry
304. **release** — publish a GitLab Release with that jar
315. **rotate-token** — self-rotate `CI_PUSH_TOKEN` and write it back to CI/CD variables
32
33## Agent do / don't
34
35- Do create/push a **new** version tag when the user asks to release or retag after they deleted the old tag.
36- Do not rewrite/force-push protected tags; ask the user to delete via GitLab UI first.
37- Do not invent non-semver tags for releases.
38- After a failed release fix, push the fix to `master`, then recreate the version tag only if the remote tag is gone (or the user deleted it).
.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 +120 −0
@@ -0,0 +1,120 @@
1 # Release pipeline: runs when a version tag is created (e.g. v1.0.10 or 1.0.10).
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 ChestPreview-<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/README-*.md
66 - src/main/java/nl/timfalken/chestpreview/ChestPreviewPlugin.java
67
68 build:jar:
69 stage: build
70 image: gradle:jdk21
71 needs:
72 - job: bump:version
73 artifacts: true
74 before_script:
75 - apt-get update -qq && apt-get install -y -qq curl >/dev/null
76 - chmod +x scripts/release.sh
77 # Checkout may still contain a previous src/README-*.md; keep only the bumped one.
78 - find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete
79 script:
80 - test -n "${VERSION}"
81 - gradle --no-daemon clean shadowJar
82 - test -f "build/libs/ChestPreview-${VERSION}.jar"
83 - ls -la "build/libs/ChestPreview-${VERSION}.jar"
84 - ./scripts/release.sh upload
85 artifacts:
86 reports:
87 dotenv: version.env
88 paths:
89 - "build/libs/ChestPreview-*.jar"
90 - version.env
91 expire_in: 30 days
92
93 release:gitlab:
94 stage: release
95 image: registry.gitlab.com/gitlab-org/release-cli:latest
96 needs:
97 - job: build:jar
98 artifacts: true
99 script:
100 - echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"
101 release:
102 name: "ChestPreview $VERSION"
103 tag_name: "$TAG"
104 description: "Release $VERSION of ChestPreview."
105 assets:
106 links:
107 - name: "ChestPreview-$VERSION.jar"
108 url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/chestpreviews/$VERSION/ChestPreview-$VERSION.jar"
109 link_type: package
110
111 rotate:push-token:
112 image: alpine:3.20
113 stage: rotate
114 needs:
115 - job: release:gitlab
116 before_script:
117 - apk add --no-cache bash curl jq coreutils
118 - chmod +x scripts/release.sh
119 script:
120 - ./scripts/release.sh rotate-token
@@ -0,0 +1,120 @@
1# Release pipeline: runs when a version tag is created (e.g. v1.0.10 or 1.0.10).
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 ChestPreview-<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/README-*.md
66 - src/main/java/nl/timfalken/chestpreview/ChestPreviewPlugin.java
67
68build:jar:
69 stage: build
70 image: gradle:jdk21
71 needs:
72 - job: bump:version
73 artifacts: true
74 before_script:
75 - apt-get update -qq && apt-get install -y -qq curl >/dev/null
76 - chmod +x scripts/release.sh
77 # Checkout may still contain a previous src/README-*.md; keep only the bumped one.
78 - find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete
79 script:
80 - test -n "${VERSION}"
81 - gradle --no-daemon clean shadowJar
82 - test -f "build/libs/ChestPreview-${VERSION}.jar"
83 - ls -la "build/libs/ChestPreview-${VERSION}.jar"
84 - ./scripts/release.sh upload
85 artifacts:
86 reports:
87 dotenv: version.env
88 paths:
89 - "build/libs/ChestPreview-*.jar"
90 - version.env
91 expire_in: 30 days
92
93release:gitlab:
94 stage: release
95 image: registry.gitlab.com/gitlab-org/release-cli:latest
96 needs:
97 - job: build:jar
98 artifacts: true
99 script:
100 - echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"
101 release:
102 name: "ChestPreview $VERSION"
103 tag_name: "$TAG"
104 description: "Release $VERSION of ChestPreview."
105 assets:
106 links:
107 - name: "ChestPreview-$VERSION.jar"
108 url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/chestpreviews/$VERSION/ChestPreview-$VERSION.jar"
109 link_type: package
110
111rotate:push-token:
112 image: alpine:3.20
113 stage: rotate
114 needs:
115 - job: release:gitlab
116 before_script:
117 - apk add --no-cache bash curl jq coreutils
118 - chmod +x scripts/release.sh
119 script:
120 - ./scripts/release.sh rotate-token
README.md added +41 −0
@@ -0,0 +1,41 @@
1 # ChestPreview 1.0.10
2
3 Paper 26.2 plugin that renders container previews as client-only ItemDisplay packets.
4
5 ## PacketEvents is bundled
6
7 ChestPreview shades PacketEvents 2.13.0 into the release JAR. A separate PacketEvents plugin is not required.
8
9 The build follows PacketEvents' bundling guidance and relocates the bundled libraries into ChestPreview's private namespace:
10
11 - `com.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
12 - `io.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
13 - `net.kyori` -> `nl.timfalken.chestpreview.libs.kyori`
14 - `com.google.gson` -> `nl.timfalken.chestpreview.libs.gson`
15 - `org.bstats` -> `nl.timfalken.chestpreview.libs.bstats`
16
17 PacketEvents is initialized by ChestPreview itself:
18
19 - `onLoad()`: build + `load()`
20 - `onEnable()`: `init()`
21 - `onDisable()`: `terminate()`
22
23 The embedded PacketEvents update checker is disabled.
24
25 ## Build
26
27 ```bash
28 gradle shadowJar
29 ```
30
31 Output:
32
33 ```text
34 build/libs/ChestPreview-<version>.jar
35 ```
36
37 Do not use `minimize()` for this build; PacketEvents warns that minimization can cause classloading issues.
38
39 ## Releases
40
41 Releases are tagged as `X.Y.Z` (optional `v` prefix). The GitLab pipeline validates the tag, bumps version files, builds the jar, and publishes a GitLab Release.
@@ -0,0 +1,41 @@
1# ChestPreview 1.0.10
2
3Paper 26.2 plugin that renders container previews as client-only ItemDisplay packets.
4
5## PacketEvents is bundled
6
7ChestPreview shades PacketEvents 2.13.0 into the release JAR. A separate PacketEvents plugin is not required.
8
9The build follows PacketEvents' bundling guidance and relocates the bundled libraries into ChestPreview's private namespace:
10
11- `com.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
12- `io.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
13- `net.kyori` -> `nl.timfalken.chestpreview.libs.kyori`
14- `com.google.gson` -> `nl.timfalken.chestpreview.libs.gson`
15- `org.bstats` -> `nl.timfalken.chestpreview.libs.bstats`
16
17PacketEvents is initialized by ChestPreview itself:
18
19- `onLoad()`: build + `load()`
20- `onEnable()`: `init()`
21- `onDisable()`: `terminate()`
22
23The embedded PacketEvents update checker is disabled.
24
25## Build
26
27```bash
28gradle shadowJar
29```
30
31Output:
32
33```text
34build/libs/ChestPreview-<version>.jar
35```
36
37Do not use `minimize()` for this build; PacketEvents warns that minimization can cause classloading issues.
38
39## Releases
40
41Releases are tagged as `X.Y.Z` (optional `v` prefix). The GitLab pipeline validates the tag, bumps version files, builds the jar, and publishes a GitLab Release.
build.gradle.kts added +55 −0
@@ -0,0 +1,55 @@
1 plugins {
2 java
3 id("com.gradleup.shadow") version "9.3.1"
4 }
5
6 group = "nl.timfalken"
7 version = "1.0.10"
8
9 repositories {
10 mavenCentral()
11 maven("https://repo.papermc.io/repository/maven-public/")
12 maven("https://repo.codemc.io/repository/maven-releases/")
13 maven("https://repo.codemc.io/repository/maven-snapshots/")
14 }
15
16 dependencies {
17 compileOnly("io.papermc.paper:paper-api:26.2-R0.1-SNAPSHOT")
18
19 // Bundled into ChestPreview by shadowJar.
20 implementation("com.github.retrooper:packetevents-spigot:2.13.0")
21 }
22
23 java {
24 toolchain.languageVersion.set(JavaLanguageVersion.of(21))
25 }
26
27 tasks.jar {
28 enabled = false
29 }
30
31 tasks.shadowJar {
32 archiveClassifier.set("")
33 archiveFileName.set("ChestPreview-${project.version}.jar")
34
35 // PacketEvents' current bundling guide explicitly requires these relocations.
36 relocate("com.github.retrooper", "nl.timfalken.chestpreview.libs.packetevents")
37 relocate("io.github.retrooper", "nl.timfalken.chestpreview.libs.packetevents")
38 relocate("net.kyori", "nl.timfalken.chestpreview.libs.kyori")
39 relocate("com.google.gson", "nl.timfalken.chestpreview.libs.gson")
40
41 // PacketEvents embeds bStats in the Spigot implementation. Keep our private copy private too.
42 relocate("org.bstats", "nl.timfalken.chestpreview.libs.bstats")
43
44 mergeServiceFiles()
45
46 // Intentionally do NOT call minimize(): PacketEvents warns this can cause classloading issues.
47 }
48
49 tasks.assemble {
50 dependsOn(tasks.shadowJar)
51 }
52
53 tasks.build {
54 dependsOn(tasks.shadowJar)
55 }
@@ -0,0 +1,55 @@
1plugins {
2 java
3 id("com.gradleup.shadow") version "9.3.1"
4}
5
6group = "nl.timfalken"
7version = "1.0.10"
8
9repositories {
10 mavenCentral()
11 maven("https://repo.papermc.io/repository/maven-public/")
12 maven("https://repo.codemc.io/repository/maven-releases/")
13 maven("https://repo.codemc.io/repository/maven-snapshots/")
14}
15
16dependencies {
17 compileOnly("io.papermc.paper:paper-api:26.2-R0.1-SNAPSHOT")
18
19 // Bundled into ChestPreview by shadowJar.
20 implementation("com.github.retrooper:packetevents-spigot:2.13.0")
21}
22
23java {
24 toolchain.languageVersion.set(JavaLanguageVersion.of(21))
25}
26
27tasks.jar {
28 enabled = false
29}
30
31tasks.shadowJar {
32 archiveClassifier.set("")
33 archiveFileName.set("ChestPreview-${project.version}.jar")
34
35 // PacketEvents' current bundling guide explicitly requires these relocations.
36 relocate("com.github.retrooper", "nl.timfalken.chestpreview.libs.packetevents")
37 relocate("io.github.retrooper", "nl.timfalken.chestpreview.libs.packetevents")
38 relocate("net.kyori", "nl.timfalken.chestpreview.libs.kyori")
39 relocate("com.google.gson", "nl.timfalken.chestpreview.libs.gson")
40
41 // PacketEvents embeds bStats in the Spigot implementation. Keep our private copy private too.
42 relocate("org.bstats", "nl.timfalken.chestpreview.libs.bstats")
43
44 mergeServiceFiles()
45
46 // Intentionally do NOT call minimize(): PacketEvents warns this can cause classloading issues.
47}
48
49tasks.assemble {
50 dependsOn(tasks.shadowJar)
51}
52
53tasks.build {
54 dependsOn(tasks.shadowJar)
55}
scripts/release.sh added +232 −0
@@ -0,0 +1,232 @@
1 #!/usr/bin/env bash
2 # Release helpers for GitLab CI (ChestPreview).
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.0.10, 1.0.11, 1.1.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 local readme
73
74 sed -i "s/^version = \".*\"/version = \"${version}\"/" build.gradle.kts
75 sed -i "s/^version: .*/version: '${version}'/" src/main/resources/plugin.yml
76 sed -i "1s/.*/# ChestPreview ${version}/" README.md
77 sed -i -E "s/ChestPreview [0-9]+\.[0-9]+\.[0-9]+ enabled/ChestPreview ${version} enabled/" \
78 src/main/java/nl/timfalken/chestpreview/ChestPreviewPlugin.java
79
80 shopt -s nullglob
81 for readme in src/README-*.md; do
82 sed -i "1s/.*/# ChestPreview ${version}/" "$readme"
83 if [[ "$readme" != "src/README-${version}.md" ]]; then
84 git mv "$readme" "src/README-${version}.md"
85 fi
86 done
87 shopt -u nullglob
88
89 echo "Updated project files to version ${version}"
90 }
91
92 require_push_token() {
93 if [[ -n "${CI_PUSH_TOKEN:-}" ]]; then
94 return 0
95 fi
96
97 cat <<'EOF' >&2
98 ERROR: CI_PUSH_TOKEN is not available in this job.
99
100 The variable may exist in Settings → CI/CD → Variables but still be hidden here if:
101 1. It is Protected, while this tag/branch is not protected
102 → Protect tag pattern (e.g. *) or uncheck Protected on the variable
103 2. Its Environment scope is not "*"
104 3. The key is misspelled (must be exactly CI_PUSH_TOKEN)
105
106 EOF
107 exit 1
108 }
109
110 bump_and_push() {
111 local version="${1:?version required}"
112 local tag="${2:?tag required}"
113 local token branch
114
115 require_push_token
116 token="${CI_PUSH_TOKEN}"
117 branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"
118
119 git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"
120 git config user.name "GitLab CI"
121
122 bump_files "$version"
123
124 # Stage only versioned project files (never CI artifacts like version.env).
125 git add -- \
126 build.gradle.kts \
127 src/main/resources/plugin.yml \
128 README.md \
129 src/main/java/nl/timfalken/chestpreview/ChestPreviewPlugin.java
130 git add -A -- src/README-*.md 2>/dev/null || true
131
132 if git diff --cached --quiet; then
133 echo "No version file changes to commit (already at ${version})."
134 else
135 git commit -m "chore: bump version to ${version}"
136 fi
137
138 git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
139
140 # Push version bump only. Protected tags cannot be moved/updated.
141 git push origin "HEAD:refs/heads/${branch}" -o ci.skip
142
143 echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."
144 }
145
146 upload_package() {
147 local version="${1:?version required}"
148 local jar="build/libs/ChestPreview-${version}.jar"
149 local package_url
150
151 if [[ ! -f "$jar" ]]; then
152 echo "ERROR: Expected jar not found: ${jar}"
153 ls -la build/libs/ || true
154 exit 1
155 fi
156
157 package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/chestpreviews/${version}/ChestPreview-${version}.jar"
158 curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
159 --upload-file "$jar" \
160 "$package_url"
161
162 echo "Uploaded ${jar}"
163 echo "PACKAGE_URL=${package_url}" > package.env
164 }
165
166 # Self-rotate CI_PUSH_TOKEN and write the new value back to the CI/CD variable.
167 # Requires scopes: write_repository + self_rotate (or api), and api to update variables.
168 # Project access token role should be Maintainer (needed to edit CI/CD variables).
169 rotate_push_token() {
170 local old_token expires_at response new_token var_meta protected masked raw scope
171
172 require_push_token
173 old_token="${CI_PUSH_TOKEN}"
174
175 expires_at="$(date -u -d '+365 days' +%Y-%m-%d)"
176 echo "Rotating CI_PUSH_TOKEN (new expiry ${expires_at})..."
177
178 response="$(curl --fail --silent --show-error \
179 --request POST \
180 --header "PRIVATE-TOKEN: ${old_token}" \
181 --header "Content-Type: application/json" \
182 --data "{\"expires_at\":\"${expires_at}\"}" \
183 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/access_tokens/self/rotate")"
184
185 new_token="$(jq -er '.token' <<<"${response}")"
186 if [[ -z "${new_token}" || "${new_token}" == "null" ]]; then
187 echo "ERROR: Token rotation response did not include a new token."
188 echo "${response}"
189 exit 1
190 fi
191
192 var_meta="$(curl --fail --silent --show-error \
193 --header "PRIVATE-TOKEN: ${new_token}" \
194 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN")"
195
196 protected="$(jq -r '.protected' <<<"${var_meta}")"
197 masked="$(jq -r '.masked' <<<"${var_meta}")"
198 raw="$(jq -r '.raw // false' <<<"${var_meta}")"
199 scope="$(jq -r '.environment_scope // "*"' <<<"${var_meta}")"
200
201 curl --fail --silent --show-error \
202 --request PUT \
203 --header "PRIVATE-TOKEN: ${new_token}" \
204 --form "value=${new_token}" \
205 --form "protected=${protected}" \
206 --form "masked=${masked}" \
207 --form "raw=${raw}" \
208 --form "environment_scope=${scope}" \
209 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN" \
210 >/dev/null
211
212 echo "CI_PUSH_TOKEN rotated and CI/CD variable updated."
213 }
214
215 case "${1:-}" in
216 validate) validate ;;
217 bump)
218 # shellcheck disable=SC1091
219 source version.env
220 bump_and_push "$VERSION" "$TAG"
221 ;;
222 upload)
223 # shellcheck disable=SC1091
224 source version.env
225 upload_package "$VERSION"
226 ;;
227 rotate-token) rotate_push_token ;;
228 *)
229 echo "Usage: $0 {validate|bump|upload|rotate-token}"
230 exit 1
231 ;;
232 esac
@@ -0,0 +1,232 @@
1#!/usr/bin/env bash
2# Release helpers for GitLab CI (ChestPreview).
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.0.10, 1.0.11, 1.1.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 local readme
73
74 sed -i "s/^version = \".*\"/version = \"${version}\"/" build.gradle.kts
75 sed -i "s/^version: .*/version: '${version}'/" src/main/resources/plugin.yml
76 sed -i "1s/.*/# ChestPreview ${version}/" README.md
77 sed -i -E "s/ChestPreview [0-9]+\.[0-9]+\.[0-9]+ enabled/ChestPreview ${version} enabled/" \
78 src/main/java/nl/timfalken/chestpreview/ChestPreviewPlugin.java
79
80 shopt -s nullglob
81 for readme in src/README-*.md; do
82 sed -i "1s/.*/# ChestPreview ${version}/" "$readme"
83 if [[ "$readme" != "src/README-${version}.md" ]]; then
84 git mv "$readme" "src/README-${version}.md"
85 fi
86 done
87 shopt -u nullglob
88
89 echo "Updated project files to version ${version}"
90}
91
92require_push_token() {
93 if [[ -n "${CI_PUSH_TOKEN:-}" ]]; then
94 return 0
95 fi
96
97 cat <<'EOF' >&2
98ERROR: CI_PUSH_TOKEN is not available in this job.
99
100The variable may exist in Settings → CI/CD → Variables but still be hidden here if:
101 1. It is Protected, while this tag/branch is not protected
102 → Protect tag pattern (e.g. *) or uncheck Protected on the variable
103 2. Its Environment scope is not "*"
104 3. The key is misspelled (must be exactly CI_PUSH_TOKEN)
105
106EOF
107 exit 1
108}
109
110bump_and_push() {
111 local version="${1:?version required}"
112 local tag="${2:?tag required}"
113 local token branch
114
115 require_push_token
116 token="${CI_PUSH_TOKEN}"
117 branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"
118
119 git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"
120 git config user.name "GitLab CI"
121
122 bump_files "$version"
123
124 # Stage only versioned project files (never CI artifacts like version.env).
125 git add -- \
126 build.gradle.kts \
127 src/main/resources/plugin.yml \
128 README.md \
129 src/main/java/nl/timfalken/chestpreview/ChestPreviewPlugin.java
130 git add -A -- src/README-*.md 2>/dev/null || true
131
132 if git diff --cached --quiet; then
133 echo "No version file changes to commit (already at ${version})."
134 else
135 git commit -m "chore: bump version to ${version}"
136 fi
137
138 git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
139
140 # Push version bump only. Protected tags cannot be moved/updated.
141 git push origin "HEAD:refs/heads/${branch}" -o ci.skip
142
143 echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."
144}
145
146upload_package() {
147 local version="${1:?version required}"
148 local jar="build/libs/ChestPreview-${version}.jar"
149 local package_url
150
151 if [[ ! -f "$jar" ]]; then
152 echo "ERROR: Expected jar not found: ${jar}"
153 ls -la build/libs/ || true
154 exit 1
155 fi
156
157 package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/chestpreviews/${version}/ChestPreview-${version}.jar"
158 curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
159 --upload-file "$jar" \
160 "$package_url"
161
162 echo "Uploaded ${jar}"
163 echo "PACKAGE_URL=${package_url}" > package.env
164}
165
166# Self-rotate CI_PUSH_TOKEN and write the new value back to the CI/CD variable.
167# Requires scopes: write_repository + self_rotate (or api), and api to update variables.
168# Project access token role should be Maintainer (needed to edit CI/CD variables).
169rotate_push_token() {
170 local old_token expires_at response new_token var_meta protected masked raw scope
171
172 require_push_token
173 old_token="${CI_PUSH_TOKEN}"
174
175 expires_at="$(date -u -d '+365 days' +%Y-%m-%d)"
176 echo "Rotating CI_PUSH_TOKEN (new expiry ${expires_at})..."
177
178 response="$(curl --fail --silent --show-error \
179 --request POST \
180 --header "PRIVATE-TOKEN: ${old_token}" \
181 --header "Content-Type: application/json" \
182 --data "{\"expires_at\":\"${expires_at}\"}" \
183 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/access_tokens/self/rotate")"
184
185 new_token="$(jq -er '.token' <<<"${response}")"
186 if [[ -z "${new_token}" || "${new_token}" == "null" ]]; then
187 echo "ERROR: Token rotation response did not include a new token."
188 echo "${response}"
189 exit 1
190 fi
191
192 var_meta="$(curl --fail --silent --show-error \
193 --header "PRIVATE-TOKEN: ${new_token}" \
194 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN")"
195
196 protected="$(jq -r '.protected' <<<"${var_meta}")"
197 masked="$(jq -r '.masked' <<<"${var_meta}")"
198 raw="$(jq -r '.raw // false' <<<"${var_meta}")"
199 scope="$(jq -r '.environment_scope // "*"' <<<"${var_meta}")"
200
201 curl --fail --silent --show-error \
202 --request PUT \
203 --header "PRIVATE-TOKEN: ${new_token}" \
204 --form "value=${new_token}" \
205 --form "protected=${protected}" \
206 --form "masked=${masked}" \
207 --form "raw=${raw}" \
208 --form "environment_scope=${scope}" \
209 "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN" \
210 >/dev/null
211
212 echo "CI_PUSH_TOKEN rotated and CI/CD variable updated."
213}
214
215case "${1:-}" in
216 validate) validate ;;
217 bump)
218 # shellcheck disable=SC1091
219 source version.env
220 bump_and_push "$VERSION" "$TAG"
221 ;;
222 upload)
223 # shellcheck disable=SC1091
224 source version.env
225 upload_package "$VERSION"
226 ;;
227 rotate-token) rotate_push_token ;;
228 *)
229 echo "Usage: $0 {validate|bump|upload|rotate-token}"
230 exit 1
231 ;;
232esac
settings.gradle.kts added +1 −0
@@ -0,0 +1 @@
1 rootProject.name = "ChestPreview"
@@ -0,0 +1 @@
1rootProject.name = "ChestPreview"
src/README-1.0.10.md added +41 −0
@@ -0,0 +1,41 @@
1 # ChestPreview 1.0.10
2
3 Paper 26.2 plugin that renders container previews as client-only ItemDisplay packets.
4
5 ## PacketEvents is bundled
6
7 ChestPreview 1.0.10 shades PacketEvents 2.13.0 into the release JAR. A separate PacketEvents plugin is not required.
8
9 The build follows PacketEvents' bundling guidance and relocates the bundled libraries into ChestPreview's private namespace:
10
11 - `com.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
12 - `io.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
13 - `net.kyori` -> `nl.timfalken.chestpreview.libs.kyori`
14 - `com.google.gson` -> `nl.timfalken.chestpreview.libs.gson`
15 - `org.bstats` -> `nl.timfalken.chestpreview.libs.bstats`
16
17 PacketEvents is initialized by ChestPreview itself:
18
19 - `onLoad()`: build + `load()`
20 - `onEnable()`: `init()`
21 - `onDisable()`: `terminate()`
22
23 The embedded PacketEvents update checker is disabled.
24
25 ## Build
26
27 Use Gradle with a version compatible with Shadow 9.3.1, then run:
28
29 ```bash
30 gradle shadowJar
31 ```
32
33 or your CI's existing `shadowJar` task.
34
35 The output is:
36
37 ```text
38 build/libs/ChestPreview-1.0.10.jar
39 ```
40
41 Do not use `minimize()` for this build; PacketEvents warns that minimization can cause classloading issues.
@@ -0,0 +1,41 @@
1# ChestPreview 1.0.10
2
3Paper 26.2 plugin that renders container previews as client-only ItemDisplay packets.
4
5## PacketEvents is bundled
6
7ChestPreview 1.0.10 shades PacketEvents 2.13.0 into the release JAR. A separate PacketEvents plugin is not required.
8
9The build follows PacketEvents' bundling guidance and relocates the bundled libraries into ChestPreview's private namespace:
10
11- `com.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
12- `io.github.retrooper` -> `nl.timfalken.chestpreview.libs.packetevents`
13- `net.kyori` -> `nl.timfalken.chestpreview.libs.kyori`
14- `com.google.gson` -> `nl.timfalken.chestpreview.libs.gson`
15- `org.bstats` -> `nl.timfalken.chestpreview.libs.bstats`
16
17PacketEvents is initialized by ChestPreview itself:
18
19- `onLoad()`: build + `load()`
20- `onEnable()`: `init()`
21- `onDisable()`: `terminate()`
22
23The embedded PacketEvents update checker is disabled.
24
25## Build
26
27Use Gradle with a version compatible with Shadow 9.3.1, then run:
28
29```bash
30gradle shadowJar
31```
32
33or your CI's existing `shadowJar` task.
34
35The output is:
36
37```text
38build/libs/ChestPreview-1.0.10.jar
39```
40
41Do not use `minimize()` for this build; PacketEvents warns that minimization can cause classloading issues.
src/main/java/nl/timfalken/chestpreview/BlockKey.java added +35 −0
@@ -0,0 +1,35 @@
1 package nl.timfalken.chestpreview;
2
3 import org.bukkit.Location;
4 import org.bukkit.World;
5 import org.bukkit.block.Block;
6
7 import java.util.Objects;
8 import java.util.UUID;
9
10 record BlockKey(UUID worldId, int x, int y, int z) implements Comparable<BlockKey> {
11 static BlockKey of(Block block) {
12 return new BlockKey(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
13 }
14
15 Block getBlock() {
16 World world = org.bukkit.Bukkit.getWorld(worldId);
17 return world == null ? null : world.getBlockAt(x, y, z);
18 }
19
20 Location center() {
21 World world = org.bukkit.Bukkit.getWorld(worldId);
22 return world == null ? null : new Location(world, x + 0.5, y + 0.5, z + 0.5);
23 }
24
25 @Override
26 public int compareTo(BlockKey other) {
27 int c = worldId.compareTo(other.worldId);
28 if (c != 0) return c;
29 c = Integer.compare(x, other.x);
30 if (c != 0) return c;
31 c = Integer.compare(y, other.y);
32 if (c != 0) return c;
33 return Integer.compare(z, other.z);
34 }
35 }
@@ -0,0 +1,35 @@
1package nl.timfalken.chestpreview;
2
3import org.bukkit.Location;
4import org.bukkit.World;
5import org.bukkit.block.Block;
6
7import java.util.Objects;
8import java.util.UUID;
9
10record BlockKey(UUID worldId, int x, int y, int z) implements Comparable<BlockKey> {
11 static BlockKey of(Block block) {
12 return new BlockKey(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
13 }
14
15 Block getBlock() {
16 World world = org.bukkit.Bukkit.getWorld(worldId);
17 return world == null ? null : world.getBlockAt(x, y, z);
18 }
19
20 Location center() {
21 World world = org.bukkit.Bukkit.getWorld(worldId);
22 return world == null ? null : new Location(world, x + 0.5, y + 0.5, z + 0.5);
23 }
24
25 @Override
26 public int compareTo(BlockKey other) {
27 int c = worldId.compareTo(other.worldId);
28 if (c != 0) return c;
29 c = Integer.compare(x, other.x);
30 if (c != 0) return c;
31 c = Integer.compare(y, other.y);
32 if (c != 0) return c;
33 return Integer.compare(z, other.z);
34 }
35}
src/main/java/nl/timfalken/chestpreview/ChestPreviewListener.java added +129 −0
@@ -0,0 +1,129 @@
1 package nl.timfalken.chestpreview;
2
3 import org.bukkit.Bukkit;
4 import org.bukkit.block.Block;
5 import org.bukkit.block.BlockState;
6 import org.bukkit.block.DoubleChest;
7 import org.bukkit.event.EventHandler;
8 import org.bukkit.event.EventPriority;
9 import org.bukkit.event.Listener;
10 import org.bukkit.event.block.BlockBreakEvent;
11 import org.bukkit.event.block.BlockExplodeEvent;
12 import org.bukkit.event.block.BlockPlaceEvent;
13 import org.bukkit.event.entity.EntityExplodeEvent;
14 import org.bukkit.event.inventory.FurnaceExtractEvent;
15 import org.bukkit.event.inventory.FurnaceSmeltEvent;
16 import org.bukkit.event.inventory.InventoryClickEvent;
17 import org.bukkit.event.inventory.InventoryCloseEvent;
18 import org.bukkit.event.inventory.InventoryDragEvent;
19 import org.bukkit.event.inventory.InventoryMoveItemEvent;
20 import org.bukkit.event.inventory.InventoryPickupItemEvent;
21 import org.bukkit.event.world.ChunkLoadEvent;
22 import org.bukkit.event.world.ChunkUnloadEvent;
23 import org.bukkit.inventory.DoubleChestInventory;
24 import org.bukkit.inventory.Inventory;
25 import org.bukkit.inventory.InventoryHolder;
26
27 final class ChestPreviewListener implements Listener {
28 private final ChestPreviewPlugin plugin;
29 private final PreviewManager manager;
30
31 ChestPreviewListener(ChestPreviewPlugin plugin, PreviewManager manager) {
32 this.plugin = plugin;
33 this.manager = manager;
34 }
35
36 private void later(Block block) {
37 Bukkit.getScheduler().runTask(plugin, () -> manager.enqueue(block));
38 }
39
40 private void later(Inventory inventory) {
41 if (inventory instanceof DoubleChestInventory doubleInventory) {
42 InventoryHolder left = doubleInventory.getLeftSide().getHolder();
43 if (left instanceof BlockState state) later(state.getBlock());
44 return;
45 }
46 InventoryHolder holder = inventory.getHolder();
47 if (holder instanceof BlockState state) later(state.getBlock());
48 else if (holder instanceof DoubleChest doubleChest && doubleChest.getLeftSide() instanceof BlockState state) later(state.getBlock());
49 }
50
51 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
52 public void onClick(InventoryClickEvent event) {
53 later(event.getView().getTopInventory());
54 }
55
56 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
57 public void onDrag(InventoryDragEvent event) {
58 later(event.getView().getTopInventory());
59 }
60
61 @EventHandler(priority = EventPriority.MONITOR)
62 public void onClose(InventoryCloseEvent event) {
63 later(event.getInventory());
64 }
65
66 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
67 public void onMove(InventoryMoveItemEvent event) {
68 later(event.getSource());
69 later(event.getDestination());
70 }
71
72 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
73 public void onPickup(InventoryPickupItemEvent event) {
74 later(event.getInventory());
75 }
76
77 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
78 public void onSmelt(FurnaceSmeltEvent event) {
79 later(event.getBlock());
80 }
81
82 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
83 public void onExtract(FurnaceExtractEvent event) {
84 later(event.getBlock());
85 }
86
87 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
88 public void onPlace(BlockPlaceEvent event) {
89 later(event.getBlockPlaced());
90 for (Block adjacent : adjacent(event.getBlockPlaced())) later(adjacent);
91 }
92
93 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
94 public void onBreak(BlockBreakEvent event) {
95 Block block = event.getBlock();
96 manager.removeForPhysicalBlock(BlockKey.of(block));
97 for (Block adjacent : adjacent(block)) later(adjacent);
98 }
99
100 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
101 public void onBlockExplode(BlockExplodeEvent event) {
102 for (Block block : event.blockList()) manager.removeForPhysicalBlock(BlockKey.of(block));
103 }
104
105 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
106 public void onEntityExplode(EntityExplodeEvent event) {
107 for (Block block : event.blockList()) manager.removeForPhysicalBlock(BlockKey.of(block));
108 }
109
110 @EventHandler
111 public void onChunkLoad(ChunkLoadEvent event) {
112 Bukkit.getScheduler().runTask(plugin, () -> {
113 if (plugin.getConfig().getBoolean("updates.rebuild-chunk-on-load", true)) {
114 manager.rebuildChunk(event.getChunk());
115 } else {
116 manager.discoverChunk(event.getChunk());
117 }
118 });
119 }
120
121 @EventHandler
122 public void onChunkUnload(ChunkUnloadEvent event) {
123 manager.forgetChunk(event.getChunk());
124 }
125
126 private static Block[] adjacent(Block block) {
127 return new Block[]{block.getRelative(1,0,0), block.getRelative(-1,0,0), block.getRelative(0,0,1), block.getRelative(0,0,-1)};
128 }
129 }
@@ -0,0 +1,129 @@
1package nl.timfalken.chestpreview;
2
3import org.bukkit.Bukkit;
4import org.bukkit.block.Block;
5import org.bukkit.block.BlockState;
6import org.bukkit.block.DoubleChest;
7import org.bukkit.event.EventHandler;
8import org.bukkit.event.EventPriority;
9import org.bukkit.event.Listener;
10import org.bukkit.event.block.BlockBreakEvent;
11import org.bukkit.event.block.BlockExplodeEvent;
12import org.bukkit.event.block.BlockPlaceEvent;
13import org.bukkit.event.entity.EntityExplodeEvent;
14import org.bukkit.event.inventory.FurnaceExtractEvent;
15import org.bukkit.event.inventory.FurnaceSmeltEvent;
16import org.bukkit.event.inventory.InventoryClickEvent;
17import org.bukkit.event.inventory.InventoryCloseEvent;
18import org.bukkit.event.inventory.InventoryDragEvent;
19import org.bukkit.event.inventory.InventoryMoveItemEvent;
20import org.bukkit.event.inventory.InventoryPickupItemEvent;
21import org.bukkit.event.world.ChunkLoadEvent;
22import org.bukkit.event.world.ChunkUnloadEvent;
23import org.bukkit.inventory.DoubleChestInventory;
24import org.bukkit.inventory.Inventory;
25import org.bukkit.inventory.InventoryHolder;
26
27final class ChestPreviewListener implements Listener {
28 private final ChestPreviewPlugin plugin;
29 private final PreviewManager manager;
30
31 ChestPreviewListener(ChestPreviewPlugin plugin, PreviewManager manager) {
32 this.plugin = plugin;
33 this.manager = manager;
34 }
35
36 private void later(Block block) {
37 Bukkit.getScheduler().runTask(plugin, () -> manager.enqueue(block));
38 }
39
40 private void later(Inventory inventory) {
41 if (inventory instanceof DoubleChestInventory doubleInventory) {
42 InventoryHolder left = doubleInventory.getLeftSide().getHolder();
43 if (left instanceof BlockState state) later(state.getBlock());
44 return;
45 }
46 InventoryHolder holder = inventory.getHolder();
47 if (holder instanceof BlockState state) later(state.getBlock());
48 else if (holder instanceof DoubleChest doubleChest && doubleChest.getLeftSide() instanceof BlockState state) later(state.getBlock());
49 }
50
51 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
52 public void onClick(InventoryClickEvent event) {
53 later(event.getView().getTopInventory());
54 }
55
56 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
57 public void onDrag(InventoryDragEvent event) {
58 later(event.getView().getTopInventory());
59 }
60
61 @EventHandler(priority = EventPriority.MONITOR)
62 public void onClose(InventoryCloseEvent event) {
63 later(event.getInventory());
64 }
65
66 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
67 public void onMove(InventoryMoveItemEvent event) {
68 later(event.getSource());
69 later(event.getDestination());
70 }
71
72 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
73 public void onPickup(InventoryPickupItemEvent event) {
74 later(event.getInventory());
75 }
76
77 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
78 public void onSmelt(FurnaceSmeltEvent event) {
79 later(event.getBlock());
80 }
81
82 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
83 public void onExtract(FurnaceExtractEvent event) {
84 later(event.getBlock());
85 }
86
87 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
88 public void onPlace(BlockPlaceEvent event) {
89 later(event.getBlockPlaced());
90 for (Block adjacent : adjacent(event.getBlockPlaced())) later(adjacent);
91 }
92
93 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
94 public void onBreak(BlockBreakEvent event) {
95 Block block = event.getBlock();
96 manager.removeForPhysicalBlock(BlockKey.of(block));
97 for (Block adjacent : adjacent(block)) later(adjacent);
98 }
99
100 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
101 public void onBlockExplode(BlockExplodeEvent event) {
102 for (Block block : event.blockList()) manager.removeForPhysicalBlock(BlockKey.of(block));
103 }
104
105 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
106 public void onEntityExplode(EntityExplodeEvent event) {
107 for (Block block : event.blockList()) manager.removeForPhysicalBlock(BlockKey.of(block));
108 }
109
110 @EventHandler
111 public void onChunkLoad(ChunkLoadEvent event) {
112 Bukkit.getScheduler().runTask(plugin, () -> {
113 if (plugin.getConfig().getBoolean("updates.rebuild-chunk-on-load", true)) {
114 manager.rebuildChunk(event.getChunk());
115 } else {
116 manager.discoverChunk(event.getChunk());
117 }
118 });
119 }
120
121 @EventHandler
122 public void onChunkUnload(ChunkUnloadEvent event) {
123 manager.forgetChunk(event.getChunk());
124 }
125
126 private static Block[] adjacent(Block block) {
127 return new Block[]{block.getRelative(1,0,0), block.getRelative(-1,0,0), block.getRelative(0,0,1), block.getRelative(0,0,-1)};
128 }
129}
src/main/java/nl/timfalken/chestpreview/ChestPreviewPlugin.java added +99 −0
@@ -0,0 +1,99 @@
1 package nl.timfalken.chestpreview;
2
3 import com.github.retrooper.packetevents.PacketEvents;
4 import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
5 import org.bukkit.Bukkit;
6 import org.bukkit.ChatColor;
7 import org.bukkit.command.Command;
8 import org.bukkit.command.CommandSender;
9 import org.bukkit.plugin.java.JavaPlugin;
10
11 public final class ChestPreviewPlugin extends JavaPlugin {
12 private boolean packetEventsLoaded;
13 private PreviewManager manager;
14 private int batchTaskId = -1;
15 private int cycleTaskId = -1;
16
17 @Override
18 public void onLoad() {
19 // PacketEvents 2.13.0 is shaded and relocated into this plugin, so ChestPreview owns
20 // this private PacketEvents instance and must manage its lifecycle itself.
21 PacketEvents.setAPI(SpigotPacketEventsBuilder.build(this));
22 PacketEvents.getAPI().getSettings().checkForUpdates(false);
23 PacketEvents.getAPI().load();
24 packetEventsLoaded = true;
25 }
26
27 @Override
28 public void onEnable() {
29 if (!packetEventsLoaded || PacketEvents.getAPI() == null) {
30 getLogger().severe("Embedded PacketEvents failed to load; disabling ChestPreview.");
31 Bukkit.getPluginManager().disablePlugin(this);
32 return;
33 }
34 PacketEvents.getAPI().init();
35
36 saveDefaultConfig();
37 manager = new PreviewManager(this);
38 Bukkit.getPluginManager().registerEvents(new ChestPreviewListener(this, manager), this);
39 scheduleTasks();
40 if (getConfig().getBoolean("updates.scan-loaded-chunks-on-startup", true)) {
41 Bukkit.getScheduler().runTask(this, manager::enqueueLoadedChunks);
42 }
43 getLogger().info("ChestPreview 1.0.10 enabled (client-only packet previews; embedded PacketEvents 2.13.0).");
44 }
45
46 @Override
47 public void onDisable() {
48 cancelTasks();
49 if (manager != null) manager.shutdown();
50
51 if (packetEventsLoaded && PacketEvents.getAPI() != null && PacketEvents.getAPI().isInitialized()) {
52 PacketEvents.getAPI().terminate();
53 }
54 packetEventsLoaded = false;
55 SpigotPacketEventsBuilder.clearBuildCache();
56 }
57
58 private void cancelTasks() {
59 if (batchTaskId != -1) Bukkit.getScheduler().cancelTask(batchTaskId);
60 if (cycleTaskId != -1) Bukkit.getScheduler().cancelTask(cycleTaskId);
61 batchTaskId = -1;
62 cycleTaskId = -1;
63 }
64
65 private void scheduleTasks() {
66 cancelTasks();
67 long batchInterval = Math.max(1L, getConfig().getLong("updates.batch-interval-ticks", 3L));
68 long cycleInterval = Math.max(1L, getConfig().getLong("cycling.interval-ticks", 20L));
69 batchTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, manager::processScanBatch, 1L, batchInterval);
70 cycleTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, manager::cycleNearbyContainers, cycleInterval, cycleInterval);
71 }
72
73 @Override
74 public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
75 if (args.length == 0) {
76 sender.sendMessage(ChatColor.YELLOW + "/chestpreview <reload|refresh|cleanup>");
77 return true;
78 }
79 switch (args[0].toLowerCase()) {
80 case "reload" -> {
81 reloadConfig();
82 scheduleTasks();
83 manager.enqueueLoadedChunks();
84 sender.sendMessage(ChatColor.GREEN + "ChestPreview configuration reloaded; loaded containers queued for refresh.");
85 }
86 case "refresh" -> {
87 manager.enqueueLoadedChunks();
88 sender.sendMessage(ChatColor.GREEN + "Loaded containers queued for refresh.");
89 }
90 case "cleanup" -> {
91 manager.cleanupAll();
92 manager.enqueueLoadedChunks();
93 sender.sendMessage(ChatColor.GREEN + "Managed displays removed and queued for rebuilding.");
94 }
95 default -> sender.sendMessage(ChatColor.RED + "Unknown subcommand.");
96 }
97 return true;
98 }
99 }
@@ -0,0 +1,99 @@
1package nl.timfalken.chestpreview;
2
3import com.github.retrooper.packetevents.PacketEvents;
4import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
5import org.bukkit.Bukkit;
6import org.bukkit.ChatColor;
7import org.bukkit.command.Command;
8import org.bukkit.command.CommandSender;
9import org.bukkit.plugin.java.JavaPlugin;
10
11public final class ChestPreviewPlugin extends JavaPlugin {
12 private boolean packetEventsLoaded;
13 private PreviewManager manager;
14 private int batchTaskId = -1;
15 private int cycleTaskId = -1;
16
17 @Override
18 public void onLoad() {
19 // PacketEvents 2.13.0 is shaded and relocated into this plugin, so ChestPreview owns
20 // this private PacketEvents instance and must manage its lifecycle itself.
21 PacketEvents.setAPI(SpigotPacketEventsBuilder.build(this));
22 PacketEvents.getAPI().getSettings().checkForUpdates(false);
23 PacketEvents.getAPI().load();
24 packetEventsLoaded = true;
25 }
26
27 @Override
28 public void onEnable() {
29 if (!packetEventsLoaded || PacketEvents.getAPI() == null) {
30 getLogger().severe("Embedded PacketEvents failed to load; disabling ChestPreview.");
31 Bukkit.getPluginManager().disablePlugin(this);
32 return;
33 }
34 PacketEvents.getAPI().init();
35
36 saveDefaultConfig();
37 manager = new PreviewManager(this);
38 Bukkit.getPluginManager().registerEvents(new ChestPreviewListener(this, manager), this);
39 scheduleTasks();
40 if (getConfig().getBoolean("updates.scan-loaded-chunks-on-startup", true)) {
41 Bukkit.getScheduler().runTask(this, manager::enqueueLoadedChunks);
42 }
43 getLogger().info("ChestPreview 1.0.10 enabled (client-only packet previews; embedded PacketEvents 2.13.0).");
44 }
45
46 @Override
47 public void onDisable() {
48 cancelTasks();
49 if (manager != null) manager.shutdown();
50
51 if (packetEventsLoaded && PacketEvents.getAPI() != null && PacketEvents.getAPI().isInitialized()) {
52 PacketEvents.getAPI().terminate();
53 }
54 packetEventsLoaded = false;
55 SpigotPacketEventsBuilder.clearBuildCache();
56 }
57
58 private void cancelTasks() {
59 if (batchTaskId != -1) Bukkit.getScheduler().cancelTask(batchTaskId);
60 if (cycleTaskId != -1) Bukkit.getScheduler().cancelTask(cycleTaskId);
61 batchTaskId = -1;
62 cycleTaskId = -1;
63 }
64
65 private void scheduleTasks() {
66 cancelTasks();
67 long batchInterval = Math.max(1L, getConfig().getLong("updates.batch-interval-ticks", 3L));
68 long cycleInterval = Math.max(1L, getConfig().getLong("cycling.interval-ticks", 20L));
69 batchTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, manager::processScanBatch, 1L, batchInterval);
70 cycleTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, manager::cycleNearbyContainers, cycleInterval, cycleInterval);
71 }
72
73 @Override
74 public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
75 if (args.length == 0) {
76 sender.sendMessage(ChatColor.YELLOW + "/chestpreview <reload|refresh|cleanup>");
77 return true;
78 }
79 switch (args[0].toLowerCase()) {
80 case "reload" -> {
81 reloadConfig();
82 scheduleTasks();
83 manager.enqueueLoadedChunks();
84 sender.sendMessage(ChatColor.GREEN + "ChestPreview configuration reloaded; loaded containers queued for refresh.");
85 }
86 case "refresh" -> {
87 manager.enqueueLoadedChunks();
88 sender.sendMessage(ChatColor.GREEN + "Loaded containers queued for refresh.");
89 }
90 case "cleanup" -> {
91 manager.cleanupAll();
92 manager.enqueueLoadedChunks();
93 sender.sendMessage(ChatColor.GREEN + "Managed displays removed and queued for rebuilding.");
94 }
95 default -> sender.sendMessage(ChatColor.RED + "Unknown subcommand.");
96 }
97 return true;
98 }
99}
src/main/java/nl/timfalken/chestpreview/ContainerTarget.java added +89 −0
@@ -0,0 +1,89 @@
1 package nl.timfalken.chestpreview;
2
3 import org.bukkit.Location;
4 import org.bukkit.block.Block;
5 import org.bukkit.block.BlockState;
6 import org.bukkit.block.Container;
7 import org.bukkit.block.DoubleChest;
8 import org.bukkit.block.data.Directional;
9 import org.bukkit.inventory.DoubleChestInventory;
10 import org.bukkit.inventory.Inventory;
11 import org.bukkit.inventory.InventoryHolder;
12 import org.bukkit.util.Vector;
13
14 import java.util.ArrayList;
15 import java.util.Comparator;
16 import java.util.List;
17
18 final class ContainerTarget {
19 private final BlockKey key;
20 private final List<Block> blocks;
21 private final Inventory inventory;
22 private final org.bukkit.block.BlockFace facing;
23
24 private ContainerTarget(BlockKey key, List<Block> blocks, Inventory inventory, org.bukkit.block.BlockFace facing) {
25 this.key = key;
26 this.blocks = blocks;
27 this.inventory = inventory;
28 this.facing = facing;
29 }
30
31 static ContainerTarget fromBlock(Block block) {
32 if (!(block.getState() instanceof Container container)) return null;
33 Inventory inventory = container.getInventory();
34 List<Block> blocks = new ArrayList<>();
35
36 if (inventory instanceof DoubleChestInventory doubleInventory) {
37 addHolderBlock(blocks, doubleInventory.getLeftSide().getHolder());
38 addHolderBlock(blocks, doubleInventory.getRightSide().getHolder());
39 } else {
40 InventoryHolder holder = inventory.getHolder();
41 if (holder instanceof DoubleChest doubleChest) {
42 addHolderBlock(blocks, doubleChest.getLeftSide());
43 addHolderBlock(blocks, doubleChest.getRightSide());
44 } else {
45 blocks.add(block);
46 }
47 }
48
49 if (blocks.isEmpty()) blocks.add(block);
50 blocks.sort(Comparator.comparing(BlockKey::of));
51
52 org.bukkit.block.BlockFace facing = org.bukkit.block.BlockFace.SOUTH;
53 if (blocks.getFirst().getBlockData() instanceof Directional directional) facing = directional.getFacing();
54 return new ContainerTarget(BlockKey.of(blocks.getFirst()), List.copyOf(blocks), inventory, facing);
55 }
56
57 private static void addHolderBlock(List<Block> blocks, InventoryHolder holder) {
58 if (holder instanceof BlockState state) blocks.add(state.getBlock());
59 }
60
61 BlockKey key() { return key; }
62 Inventory inventory() { return inventory; }
63
64 Location displayLocation(double forwardOffset, double verticalOffset, double sidewaysOffset, double yawOffset, double pitch) {
65 double x = 0, y = 0, z = 0;
66 for (Block block : blocks) {
67 x += block.getX() + 0.5;
68 y += block.getY() + verticalOffset;
69 z += block.getZ() + 0.5;
70 }
71 int count = blocks.size();
72 Vector forward = facing.getDirection().normalize().multiply(forwardOffset);
73 Vector sideways = new Vector(-forward.getZ(), 0, forward.getX());
74 if (sideways.lengthSquared() > 0) sideways.normalize().multiply(sidewaysOffset);
75 return new Location(blocks.getFirst().getWorld(),
76 x / count + forward.getX() + sideways.getX(), y / count,
77 z / count + forward.getZ() + sideways.getZ(),
78 yaw(facing) + (float) yawOffset, (float) pitch);
79 }
80
81 private static float yaw(org.bukkit.block.BlockFace face) {
82 return switch (face) {
83 case NORTH -> 180f;
84 case EAST -> -90f;
85 case WEST -> 90f;
86 default -> 0f;
87 };
88 }
89 }
@@ -0,0 +1,89 @@
1package nl.timfalken.chestpreview;
2
3import org.bukkit.Location;
4import org.bukkit.block.Block;
5import org.bukkit.block.BlockState;
6import org.bukkit.block.Container;
7import org.bukkit.block.DoubleChest;
8import org.bukkit.block.data.Directional;
9import org.bukkit.inventory.DoubleChestInventory;
10import org.bukkit.inventory.Inventory;
11import org.bukkit.inventory.InventoryHolder;
12import org.bukkit.util.Vector;
13
14import java.util.ArrayList;
15import java.util.Comparator;
16import java.util.List;
17
18final class ContainerTarget {
19 private final BlockKey key;
20 private final List<Block> blocks;
21 private final Inventory inventory;
22 private final org.bukkit.block.BlockFace facing;
23
24 private ContainerTarget(BlockKey key, List<Block> blocks, Inventory inventory, org.bukkit.block.BlockFace facing) {
25 this.key = key;
26 this.blocks = blocks;
27 this.inventory = inventory;
28 this.facing = facing;
29 }
30
31 static ContainerTarget fromBlock(Block block) {
32 if (!(block.getState() instanceof Container container)) return null;
33 Inventory inventory = container.getInventory();
34 List<Block> blocks = new ArrayList<>();
35
36 if (inventory instanceof DoubleChestInventory doubleInventory) {
37 addHolderBlock(blocks, doubleInventory.getLeftSide().getHolder());
38 addHolderBlock(blocks, doubleInventory.getRightSide().getHolder());
39 } else {
40 InventoryHolder holder = inventory.getHolder();
41 if (holder instanceof DoubleChest doubleChest) {
42 addHolderBlock(blocks, doubleChest.getLeftSide());
43 addHolderBlock(blocks, doubleChest.getRightSide());
44 } else {
45 blocks.add(block);
46 }
47 }
48
49 if (blocks.isEmpty()) blocks.add(block);
50 blocks.sort(Comparator.comparing(BlockKey::of));
51
52 org.bukkit.block.BlockFace facing = org.bukkit.block.BlockFace.SOUTH;
53 if (blocks.getFirst().getBlockData() instanceof Directional directional) facing = directional.getFacing();
54 return new ContainerTarget(BlockKey.of(blocks.getFirst()), List.copyOf(blocks), inventory, facing);
55 }
56
57 private static void addHolderBlock(List<Block> blocks, InventoryHolder holder) {
58 if (holder instanceof BlockState state) blocks.add(state.getBlock());
59 }
60
61 BlockKey key() { return key; }
62 Inventory inventory() { return inventory; }
63
64 Location displayLocation(double forwardOffset, double verticalOffset, double sidewaysOffset, double yawOffset, double pitch) {
65 double x = 0, y = 0, z = 0;
66 for (Block block : blocks) {
67 x += block.getX() + 0.5;
68 y += block.getY() + verticalOffset;
69 z += block.getZ() + 0.5;
70 }
71 int count = blocks.size();
72 Vector forward = facing.getDirection().normalize().multiply(forwardOffset);
73 Vector sideways = new Vector(-forward.getZ(), 0, forward.getX());
74 if (sideways.lengthSquared() > 0) sideways.normalize().multiply(sidewaysOffset);
75 return new Location(blocks.getFirst().getWorld(),
76 x / count + forward.getX() + sideways.getX(), y / count,
77 z / count + forward.getZ() + sideways.getZ(),
78 yaw(facing) + (float) yawOffset, (float) pitch);
79 }
80
81 private static float yaw(org.bukkit.block.BlockFace face) {
82 return switch (face) {
83 case NORTH -> 180f;
84 case EAST -> -90f;
85 case WEST -> 90f;
86 default -> 0f;
87 };
88 }
89}
src/main/java/nl/timfalken/chestpreview/PreviewManager.java added +567 −0
@@ -0,0 +1,567 @@
1 package nl.timfalken.chestpreview;
2
3 import com.github.retrooper.packetevents.PacketEvents;
4 import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
5 import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes;
6 import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
7 import com.github.retrooper.packetevents.util.Quaternion4f;
8 import com.github.retrooper.packetevents.util.Vector3f;
9 import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
10 import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
11 import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
12 import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
13 import io.github.retrooper.packetevents.util.SpigotConversionUtil;
14 import org.bukkit.Bukkit;
15 import org.bukkit.Chunk;
16 import org.bukkit.Location;
17 import org.bukkit.Material;
18 import org.bukkit.NamespacedKey;
19 import org.bukkit.World;
20 import org.bukkit.block.Block;
21 import org.bukkit.block.BlockState;
22 import org.bukkit.entity.Entity;
23 import org.bukkit.entity.ItemDisplay;
24 import org.bukkit.entity.Player;
25 import org.bukkit.inventory.FurnaceInventory;
26 import org.bukkit.inventory.Inventory;
27 import org.bukkit.inventory.ItemStack;
28 import org.bukkit.persistence.PersistentDataType;
29
30 import java.util.ArrayDeque;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Queue;
38 import java.util.Set;
39 import java.util.UUID;
40 import java.util.concurrent.ThreadLocalRandom;
41 import java.util.concurrent.atomic.AtomicInteger;
42
43 /**
44 * Maintains logical previews and sends them as packet-only ItemDisplay entities.
45 * No ItemDisplay is spawned into the Bukkit world by this version.
46 */
47 final class PreviewManager {
48 // Minecraft 26.2 metadata indices for Display / ItemDisplay entities.
49 // Base Entity occupies 0..7, Display 8..22, ItemDisplay 23..24.
50 private static final int META_ENTITY_FLAGS = 0;
51 private static final int META_NO_GRAVITY = 5;
52 private static final int META_SCALE = 12;
53 private static final int META_LEFT_ROTATION = 13;
54 private static final int META_RIGHT_ROTATION = 14;
55 private static final int META_BILLBOARD = 15;
56 private static final int META_ITEM = 23;
57 private static final int META_ITEM_TRANSFORM = 24;
58
59 private static final byte ENTITY_FLAG_GLOWING = 0x40;
60 private static final byte BILLBOARD_FIXED = 0;
61 private static final byte ITEM_TRANSFORM_GUI = 6;
62 private static final byte ITEM_TRANSFORM_FIXED = 8;
63
64 // Client-only IDs live far above normal server entity IDs to avoid collisions.
65 private static final AtomicInteger NEXT_FAKE_ENTITY_ID = new AtomicInteger(2_000_000_000);
66
67 private final ChestPreviewPlugin plugin;
68 private final NamespacedKey legacyManagedKey;
69 private final Map<BlockKey, PreviewState> previews = new HashMap<>();
70 private final Queue<BlockKey> scanQueue = new ArrayDeque<>();
71 private final Set<BlockKey> queued = new HashSet<>();
72 private final Map<ChunkKey, Set<BlockKey>> knownContainers = new HashMap<>();
73
74 PreviewManager(ChestPreviewPlugin plugin) {
75 this.plugin = plugin;
76 // Used only to remove persisted server-side displays left by ChestPreview <= 1.0.8.
77 this.legacyManagedKey = new NamespacedKey("chestpreview", "managed");
78 }
79
80 boolean isSupported(Block block) {
81 return switch (block.getType()) {
82 case CHEST -> plugin.getConfig().getBoolean("containers.chest", true);
83 case TRAPPED_CHEST -> plugin.getConfig().getBoolean("containers.trapped-chest", true);
84 case BARREL -> plugin.getConfig().getBoolean("containers.barrel", true);
85 case FURNACE -> plugin.getConfig().getBoolean("output-containers.furnace", true);
86 case BLAST_FURNACE -> plugin.getConfig().getBoolean("output-containers.blast-furnace", true);
87 case SMOKER -> plugin.getConfig().getBoolean("output-containers.smoker", true);
88 default -> false;
89 };
90 }
91
92 void refresh(Block block) {
93 if (!isSupported(block)) {
94 removeForPhysicalBlock(BlockKey.of(block));
95 return;
96 }
97 ContainerTarget target = ContainerTarget.fromBlock(block);
98 if (target != null) refresh(target);
99 }
100
101 void refresh(ContainerTarget target) {
102 rememberTarget(target);
103 ItemStack selected = selectItem(target);
104 BlockKey key = target.key();
105
106 if (selected == null) {
107 destroyPreview(key);
108 return;
109 }
110
111 Location location = target.displayLocation(
112 plugin.getConfig().getDouble("display.forward-offset", 0.515),
113 plugin.getConfig().getDouble("display.vertical-offset", 0.42),
114 plugin.getConfig().getDouble("display.sideways-offset", 0.0),
115 plugin.getConfig().getDouble("display.rotation.yaw", 0.0),
116 plugin.getConfig().getDouble("display.rotation.pitch", 0.0));
117
118 ItemStack shown = selected.clone();
119 shown.setAmount(1);
120 VisualSpec visual = visualSpec(shown.getType());
121
122 PreviewState state = previews.get(key);
123 boolean newlyCreated = false;
124 boolean moved = false;
125 boolean metadataChanged = false;
126
127 if (state == null) {
128 state = new PreviewState(
129 NEXT_FAKE_ENTITY_ID.getAndDecrement(),
130 UUID.randomUUID(),
131 copyLocation(location),
132 shown,
133 visual);
134 previews.put(key, state);
135 newlyCreated = true;
136 } else {
137 moved = !sameLocation(state.location, location);
138 metadataChanged = !sameItem(state.item, shown) || !state.visual.equals(visual);
139 state.location = copyLocation(location);
140 state.item = shown;
141 state.visual = visual;
142 }
143
144 syncViewers(key, state, newlyCreated, moved, metadataChanged);
145 }
146
147 private ItemStack selectItem(ContainerTarget target) {
148 Inventory inventory = target.inventory();
149 if (inventory instanceof FurnaceInventory furnaceInventory) {
150 ItemStack result = furnaceInventory.getResult();
151 if (usable(result)) return result;
152
153 ItemStack input = furnaceInventory.getSmelting();
154 return usable(input) ? input : null;
155 }
156
157 ItemStack[] contents = inventory.getStorageContents();
158 int usableCount = 0;
159 for (ItemStack item : contents) {
160 if (usable(item)) usableCount++;
161 }
162 if (usableCount == 0) return null;
163
164 int selectedIndex = ThreadLocalRandom.current().nextInt(usableCount);
165 for (ItemStack item : contents) {
166 if (!usable(item)) continue;
167 if (selectedIndex-- == 0) return item;
168 }
169 return null;
170 }
171
172 private static boolean usable(ItemStack item) {
173 return item != null && item.getType() != Material.AIR && item.getAmount() > 0;
174 }
175
176 private VisualSpec visualSpec(Material material) {
177 float scale = (float) plugin.getConfig().getDouble("display.scale", 0.40);
178 float roll = radians(plugin.getConfig().getDouble("display.rotation.roll", 0.0));
179 boolean block = material.isBlock();
180
181 float modelYaw = block ? 0.0f : radians(180.0);
182 float modelPitch = 0.0f;
183
184 if (material.name().endsWith("_STAIRS")) {
185 modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-yaw", 0.0));
186 modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-pitch", 0.0));
187 } else if (block) {
188 modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.default-yaw", 0.0));
189 modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.default-pitch", 0.0));
190 }
191
192 byte transform = block ? ITEM_TRANSFORM_FIXED : ITEM_TRANSFORM_GUI;
193 boolean glowing = plugin.getConfig().getBoolean("display.glowing", false);
194 return new VisualSpec(scale, modelPitch, modelYaw, roll, transform, glowing);
195 }
196
197 private void syncViewers(BlockKey key, PreviewState state, boolean newlyCreated, boolean moved, boolean metadataChanged) {
198 Set<UUID> stillVisible = new HashSet<>();
199
200 for (Player player : Bukkit.getOnlinePlayers()) {
201 if (!shouldView(player, state.location)) continue;
202 UUID playerId = player.getUniqueId();
203 stillVisible.add(playerId);
204
205 if (state.viewers.add(playerId)) {
206 sendSpawn(player, state);
207 } else {
208 if (moved) sendTeleport(player, state);
209 if (metadataChanged || newlyCreated) sendMetadata(player, state);
210 }
211 }
212
213 Iterator<UUID> iterator = state.viewers.iterator();
214 while (iterator.hasNext()) {
215 UUID viewerId = iterator.next();
216 if (stillVisible.contains(viewerId)) continue;
217 Player viewer = Bukkit.getPlayer(viewerId);
218 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
219 iterator.remove();
220 }
221 }
222
223 private boolean shouldView(Player player, Location location) {
224 if (location.getWorld() == null || !player.getWorld().getUID().equals(location.getWorld().getUID())) return false;
225 int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4));
226 int playerChunkX = player.getLocation().getChunk().getX();
227 int playerChunkZ = player.getLocation().getChunk().getZ();
228 int previewChunkX = ((int) Math.floor(location.getX())) >> 4;
229 int previewChunkZ = ((int) Math.floor(location.getZ())) >> 4;
230 return Math.abs(playerChunkX - previewChunkX) <= radius && Math.abs(playerChunkZ - previewChunkZ) <= radius;
231 }
232
233 private void sendSpawn(Player player, PreviewState state) {
234 WrapperPlayServerSpawnEntity spawn = new WrapperPlayServerSpawnEntity(
235 state.entityId,
236 state.entityUuid,
237 EntityTypes.ITEM_DISPLAY,
238 SpigotConversionUtil.fromBukkitLocation(state.location),
239 state.location.getYaw(),
240 0,
241 null);
242 PacketEvents.getAPI().getPlayerManager().sendPacket(player, spawn);
243 sendMetadata(player, state);
244 }
245
246 private void sendMetadata(Player player, PreviewState state) {
247 List<EntityData<?>> data = new ArrayList<>(8);
248 byte flags = state.visual.glowing ? ENTITY_FLAG_GLOWING : 0;
249 data.add(new EntityData<>(META_ENTITY_FLAGS, EntityDataTypes.BYTE, flags));
250 data.add(new EntityData<>(META_NO_GRAVITY, EntityDataTypes.BOOLEAN, true));
251 data.add(new EntityData<>(META_SCALE, EntityDataTypes.VECTOR3F,
252 new Vector3f(state.visual.scale, state.visual.scale, state.visual.scale)));
253 data.add(new EntityData<>(META_LEFT_ROTATION, EntityDataTypes.QUATERNION,
254 quaternionXYZ(state.visual.pitch, state.visual.yaw, state.visual.roll)));
255 data.add(new EntityData<>(META_RIGHT_ROTATION, EntityDataTypes.QUATERNION,
256 new Quaternion4f(0.0f, 0.0f, 0.0f, 1.0f)));
257 data.add(new EntityData<>(META_BILLBOARD, EntityDataTypes.BYTE, BILLBOARD_FIXED));
258 data.add(new EntityData<>(META_ITEM, EntityDataTypes.ITEMSTACK,
259 SpigotConversionUtil.fromBukkitItemStack(state.item)));
260 data.add(new EntityData<>(META_ITEM_TRANSFORM, EntityDataTypes.BYTE, state.visual.itemTransform));
261
262 PacketEvents.getAPI().getPlayerManager().sendPacket(
263 player,
264 new WrapperPlayServerEntityMetadata(state.entityId, data));
265 }
266
267 private void sendTeleport(Player player, PreviewState state) {
268 PacketEvents.getAPI().getPlayerManager().sendPacket(
269 player,
270 new WrapperPlayServerEntityTeleport(
271 state.entityId,
272 SpigotConversionUtil.fromBukkitLocation(state.location),
273 false));
274 }
275
276 private void sendDestroy(Player player, int entityId) {
277 PacketEvents.getAPI().getPlayerManager().sendPacket(
278 player,
279 new WrapperPlayServerDestroyEntities(entityId));
280 }
281
282 private void destroyPreview(BlockKey key) {
283 PreviewState state = previews.remove(key);
284 if (state == null) return;
285 for (UUID viewerId : new HashSet<>(state.viewers)) {
286 Player viewer = Bukkit.getPlayer(viewerId);
287 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
288 }
289 state.viewers.clear();
290 }
291
292 private void pruneViewers() {
293 for (PreviewState state : previews.values()) {
294 Iterator<UUID> iterator = state.viewers.iterator();
295 while (iterator.hasNext()) {
296 UUID viewerId = iterator.next();
297 Player viewer = Bukkit.getPlayer(viewerId);
298 if (viewer != null && viewer.isOnline() && shouldView(viewer, state.location)) continue;
299 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
300 iterator.remove();
301 }
302 }
303 }
304
305 /**
306 * Register containers once when a chunk is discovered. Legacy Bukkit ItemDisplays from
307 * ChestPreview <= 1.0.8 are removed as a migration step, but no new Bukkit entity is spawned.
308 */
309 void discoverChunk(Chunk chunk) {
310 cleanupLegacyDisplays(chunk);
311 registerContainersInChunk(chunk, true);
312 }
313
314 void rebuildChunk(Chunk chunk) {
315 int chunkX = chunk.getX();
316 int chunkZ = chunk.getZ();
317 World world = chunk.getWorld();
318 ChunkKey chunkKey = ChunkKey.of(chunk);
319
320 cleanupLegacyDisplays(chunk);
321
322 List<BlockKey> toDestroy = new ArrayList<>();
323 for (BlockKey key : previews.keySet()) {
324 if (isInChunk(key, world, chunkX, chunkZ)) toDestroy.add(key);
325 }
326 for (BlockKey key : toDestroy) destroyPreview(key);
327
328 scanQueue.removeIf(key -> isInChunk(key, world, chunkX, chunkZ));
329 queued.removeIf(key -> isInChunk(key, world, chunkX, chunkZ));
330 knownContainers.remove(chunkKey);
331
332 registerContainersInChunk(chunk, true);
333 }
334
335 void forgetChunk(Chunk chunk) {
336 ChunkKey chunkKey = ChunkKey.of(chunk);
337 Set<BlockKey> forgotten = knownContainers.remove(chunkKey);
338 if (forgotten == null) return;
339
340 for (BlockKey key : forgotten) {
341 destroyPreview(key);
342 queued.remove(key);
343 }
344 scanQueue.removeIf(forgotten::contains);
345 }
346
347 private void cleanupLegacyDisplays(Chunk chunk) {
348 for (Entity entity : chunk.getEntities()) {
349 if (!(entity instanceof ItemDisplay display)) continue;
350 if (display.getPersistentDataContainer().has(legacyManagedKey, PersistentDataType.BYTE)) {
351 display.remove();
352 }
353 }
354 }
355
356 private void registerContainersInChunk(Chunk chunk, boolean enqueueForRefresh) {
357 for (BlockState state : chunk.getTileEntities()) {
358 Block block = state.getBlock();
359 if (!isSupported(block)) continue;
360 ContainerTarget target = ContainerTarget.fromBlock(block);
361 if (target == null) continue;
362 rememberTarget(target);
363 if (enqueueForRefresh) enqueue(target.key());
364 }
365 }
366
367 private void rememberTarget(ContainerTarget target) {
368 BlockKey key = target.key();
369 knownContainers.computeIfAbsent(ChunkKey.of(key), ignored -> new HashSet<>()).add(key);
370 }
371
372 private void forgetKnownKey(BlockKey key) {
373 Set<BlockKey> keys = knownContainers.get(ChunkKey.of(key));
374 if (keys == null) return;
375 keys.remove(key);
376 if (keys.isEmpty()) knownContainers.remove(ChunkKey.of(key));
377 }
378
379 private static boolean isInChunk(BlockKey key, World world, int chunkX, int chunkZ) {
380 return key.worldId().equals(world.getUID()) && (key.x() >> 4) == chunkX && (key.z() >> 4) == chunkZ;
381 }
382
383 void enqueue(BlockKey key) {
384 if (queued.add(key)) scanQueue.offer(key);
385 }
386
387 void enqueue(Block block) {
388 if (!isSupported(block)) return;
389 ContainerTarget target = ContainerTarget.fromBlock(block);
390 if (target == null) return;
391 rememberTarget(target);
392 enqueue(target.key());
393 }
394
395 void processScanBatch() {
396 int maximum = Math.max(1, plugin.getConfig().getInt("updates.containers-per-batch", 5));
397 for (int i = 0; i < maximum; i++) {
398 BlockKey key = scanQueue.poll();
399 if (key == null) return;
400 queued.remove(key);
401 World world = Bukkit.getWorld(key.worldId());
402 if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue;
403 refresh(world.getBlockAt(key.x(), key.y(), key.z()));
404 }
405 }
406
407 /**
408 * Every interval, already-known containers near players are visited. If cycling is enabled,
409 * the preview item is reselected. The same pass also creates/removes client-only viewers as
410 * players enter or leave the configured four-chunk radius. No chunk tile-entity scan occurs.
411 */
412 void cycleNearbyContainers() {
413 int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4));
414 boolean cycling = plugin.getConfig().getBoolean("cycling.enabled", true);
415 Set<BlockKey> targets = new HashSet<>();
416 Set<ChunkKey> visitedChunks = new HashSet<>();
417
418 for (Player player : Bukkit.getOnlinePlayers()) {
419 Chunk center = player.getLocation().getChunk();
420 World world = player.getWorld();
421 for (int dx = -radius; dx <= radius; dx++) {
422 for (int dz = -radius; dz <= radius; dz++) {
423 int chunkX = center.getX() + dx;
424 int chunkZ = center.getZ() + dz;
425 if (!world.isChunkLoaded(chunkX, chunkZ)) continue;
426 ChunkKey chunkKey = new ChunkKey(world.getUID(), chunkX, chunkZ);
427 if (!visitedChunks.add(chunkKey)) continue;
428 Set<BlockKey> known = knownContainers.get(chunkKey);
429 if (known != null) targets.addAll(known);
430 }
431 }
432 }
433
434 for (BlockKey key : targets) {
435 World world = Bukkit.getWorld(key.worldId());
436 if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue;
437 Block block = world.getBlockAt(key.x(), key.y(), key.z());
438 if (!isSupported(block)) {
439 removeForPhysicalBlock(key);
440 continue;
441 }
442
443 if (cycling || !previews.containsKey(key)) {
444 refresh(block);
445 } else {
446 PreviewState state = previews.get(key);
447 if (state != null) syncViewers(key, state, false, false, false);
448 }
449 }
450
451 pruneViewers();
452 }
453
454 void enqueueLoadedChunks() {
455 for (World world : Bukkit.getWorlds()) {
456 for (Chunk chunk : world.getLoadedChunks()) discoverChunk(chunk);
457 }
458 }
459
460 void cleanupAll() {
461 destroyAllPacketDisplays();
462 scanQueue.clear();
463 queued.clear();
464 knownContainers.clear();
465 for (World world : Bukkit.getWorlds()) {
466 for (Chunk chunk : world.getLoadedChunks()) cleanupLegacyDisplays(chunk);
467 }
468 }
469
470 void shutdown() {
471 destroyAllPacketDisplays();
472 scanQueue.clear();
473 queued.clear();
474 knownContainers.clear();
475 }
476
477 private void destroyAllPacketDisplays() {
478 for (PreviewState state : previews.values()) {
479 for (UUID viewerId : new HashSet<>(state.viewers)) {
480 Player viewer = Bukkit.getPlayer(viewerId);
481 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
482 }
483 state.viewers.clear();
484 }
485 previews.clear();
486 }
487
488 void removeForPhysicalBlock(BlockKey physical) {
489 Block block = physical.getBlock();
490 if (block != null && isSupported(block)) {
491 ContainerTarget target = ContainerTarget.fromBlock(block);
492 if (target != null) {
493 forgetKnownKey(target.key());
494 destroyPreview(target.key());
495 }
496 }
497 forgetKnownKey(physical);
498 destroyPreview(physical);
499 }
500
501 private static Location copyLocation(Location source) {
502 return new Location(source.getWorld(), source.getX(), source.getY(), source.getZ(), source.getYaw(), source.getPitch());
503 }
504
505 private static boolean sameLocation(Location a, Location b) {
506 if (a.getWorld() == null || b.getWorld() == null) return false;
507 return a.getWorld().getUID().equals(b.getWorld().getUID())
508 && Double.compare(a.getX(), b.getX()) == 0
509 && Double.compare(a.getY(), b.getY()) == 0
510 && Double.compare(a.getZ(), b.getZ()) == 0
511 && Float.compare(a.getYaw(), b.getYaw()) == 0
512 && Float.compare(a.getPitch(), b.getPitch()) == 0;
513 }
514
515 private static boolean sameItem(ItemStack a, ItemStack b) {
516 return a.getAmount() == b.getAmount() && a.isSimilar(b);
517 }
518
519 private static float radians(double degrees) {
520 return (float) Math.toRadians(degrees);
521 }
522
523 /** Equivalent to JOML Quaternionf().rotateXYZ(x, y, z) used by 1.0.8. */
524 private static Quaternion4f quaternionXYZ(float x, float y, float z) {
525 float sx = (float) Math.sin(x * 0.5f);
526 float cx = (float) Math.cos(x * 0.5f);
527 float sy = (float) Math.sin(y * 0.5f);
528 float cy = (float) Math.cos(y * 0.5f);
529 float sz = (float) Math.sin(z * 0.5f);
530 float cz = (float) Math.cos(z * 0.5f);
531
532 float qx = sx * cy * cz + cx * sy * sz;
533 float qy = cx * sy * cz - sx * cy * sz;
534 float qz = cx * cy * sz + sx * sy * cz;
535 float qw = cx * cy * cz - sx * sy * sz;
536 return new Quaternion4f(qx, qy, qz, qw);
537 }
538
539 private static final class PreviewState {
540 private final int entityId;
541 private final UUID entityUuid;
542 private final Set<UUID> viewers = new HashSet<>();
543 private Location location;
544 private ItemStack item;
545 private VisualSpec visual;
546
547 private PreviewState(int entityId, UUID entityUuid, Location location, ItemStack item, VisualSpec visual) {
548 this.entityId = entityId;
549 this.entityUuid = entityUuid;
550 this.location = location;
551 this.item = item;
552 this.visual = visual;
553 }
554 }
555
556 private record VisualSpec(float scale, float pitch, float yaw, float roll, byte itemTransform, boolean glowing) {}
557
558 private record ChunkKey(UUID worldId, int x, int z) {
559 static ChunkKey of(Chunk chunk) {
560 return new ChunkKey(chunk.getWorld().getUID(), chunk.getX(), chunk.getZ());
561 }
562
563 static ChunkKey of(BlockKey key) {
564 return new ChunkKey(key.worldId(), key.x() >> 4, key.z() >> 4);
565 }
566 }
567 }
@@ -0,0 +1,567 @@
1package nl.timfalken.chestpreview;
2
3import com.github.retrooper.packetevents.PacketEvents;
4import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
5import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes;
6import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
7import com.github.retrooper.packetevents.util.Quaternion4f;
8import com.github.retrooper.packetevents.util.Vector3f;
9import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
10import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
11import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
12import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
13import io.github.retrooper.packetevents.util.SpigotConversionUtil;
14import org.bukkit.Bukkit;
15import org.bukkit.Chunk;
16import org.bukkit.Location;
17import org.bukkit.Material;
18import org.bukkit.NamespacedKey;
19import org.bukkit.World;
20import org.bukkit.block.Block;
21import org.bukkit.block.BlockState;
22import org.bukkit.entity.Entity;
23import org.bukkit.entity.ItemDisplay;
24import org.bukkit.entity.Player;
25import org.bukkit.inventory.FurnaceInventory;
26import org.bukkit.inventory.Inventory;
27import org.bukkit.inventory.ItemStack;
28import org.bukkit.persistence.PersistentDataType;
29
30import java.util.ArrayDeque;
31import java.util.ArrayList;
32import java.util.HashMap;
33import java.util.HashSet;
34import java.util.Iterator;
35import java.util.List;
36import java.util.Map;
37import java.util.Queue;
38import java.util.Set;
39import java.util.UUID;
40import java.util.concurrent.ThreadLocalRandom;
41import java.util.concurrent.atomic.AtomicInteger;
42
43/**
44 * Maintains logical previews and sends them as packet-only ItemDisplay entities.
45 * No ItemDisplay is spawned into the Bukkit world by this version.
46 */
47final class PreviewManager {
48 // Minecraft 26.2 metadata indices for Display / ItemDisplay entities.
49 // Base Entity occupies 0..7, Display 8..22, ItemDisplay 23..24.
50 private static final int META_ENTITY_FLAGS = 0;
51 private static final int META_NO_GRAVITY = 5;
52 private static final int META_SCALE = 12;
53 private static final int META_LEFT_ROTATION = 13;
54 private static final int META_RIGHT_ROTATION = 14;
55 private static final int META_BILLBOARD = 15;
56 private static final int META_ITEM = 23;
57 private static final int META_ITEM_TRANSFORM = 24;
58
59 private static final byte ENTITY_FLAG_GLOWING = 0x40;
60 private static final byte BILLBOARD_FIXED = 0;
61 private static final byte ITEM_TRANSFORM_GUI = 6;
62 private static final byte ITEM_TRANSFORM_FIXED = 8;
63
64 // Client-only IDs live far above normal server entity IDs to avoid collisions.
65 private static final AtomicInteger NEXT_FAKE_ENTITY_ID = new AtomicInteger(2_000_000_000);
66
67 private final ChestPreviewPlugin plugin;
68 private final NamespacedKey legacyManagedKey;
69 private final Map<BlockKey, PreviewState> previews = new HashMap<>();
70 private final Queue<BlockKey> scanQueue = new ArrayDeque<>();
71 private final Set<BlockKey> queued = new HashSet<>();
72 private final Map<ChunkKey, Set<BlockKey>> knownContainers = new HashMap<>();
73
74 PreviewManager(ChestPreviewPlugin plugin) {
75 this.plugin = plugin;
76 // Used only to remove persisted server-side displays left by ChestPreview <= 1.0.8.
77 this.legacyManagedKey = new NamespacedKey("chestpreview", "managed");
78 }
79
80 boolean isSupported(Block block) {
81 return switch (block.getType()) {
82 case CHEST -> plugin.getConfig().getBoolean("containers.chest", true);
83 case TRAPPED_CHEST -> plugin.getConfig().getBoolean("containers.trapped-chest", true);
84 case BARREL -> plugin.getConfig().getBoolean("containers.barrel", true);
85 case FURNACE -> plugin.getConfig().getBoolean("output-containers.furnace", true);
86 case BLAST_FURNACE -> plugin.getConfig().getBoolean("output-containers.blast-furnace", true);
87 case SMOKER -> plugin.getConfig().getBoolean("output-containers.smoker", true);
88 default -> false;
89 };
90 }
91
92 void refresh(Block block) {
93 if (!isSupported(block)) {
94 removeForPhysicalBlock(BlockKey.of(block));
95 return;
96 }
97 ContainerTarget target = ContainerTarget.fromBlock(block);
98 if (target != null) refresh(target);
99 }
100
101 void refresh(ContainerTarget target) {
102 rememberTarget(target);
103 ItemStack selected = selectItem(target);
104 BlockKey key = target.key();
105
106 if (selected == null) {
107 destroyPreview(key);
108 return;
109 }
110
111 Location location = target.displayLocation(
112 plugin.getConfig().getDouble("display.forward-offset", 0.515),
113 plugin.getConfig().getDouble("display.vertical-offset", 0.42),
114 plugin.getConfig().getDouble("display.sideways-offset", 0.0),
115 plugin.getConfig().getDouble("display.rotation.yaw", 0.0),
116 plugin.getConfig().getDouble("display.rotation.pitch", 0.0));
117
118 ItemStack shown = selected.clone();
119 shown.setAmount(1);
120 VisualSpec visual = visualSpec(shown.getType());
121
122 PreviewState state = previews.get(key);
123 boolean newlyCreated = false;
124 boolean moved = false;
125 boolean metadataChanged = false;
126
127 if (state == null) {
128 state = new PreviewState(
129 NEXT_FAKE_ENTITY_ID.getAndDecrement(),
130 UUID.randomUUID(),
131 copyLocation(location),
132 shown,
133 visual);
134 previews.put(key, state);
135 newlyCreated = true;
136 } else {
137 moved = !sameLocation(state.location, location);
138 metadataChanged = !sameItem(state.item, shown) || !state.visual.equals(visual);
139 state.location = copyLocation(location);
140 state.item = shown;
141 state.visual = visual;
142 }
143
144 syncViewers(key, state, newlyCreated, moved, metadataChanged);
145 }
146
147 private ItemStack selectItem(ContainerTarget target) {
148 Inventory inventory = target.inventory();
149 if (inventory instanceof FurnaceInventory furnaceInventory) {
150 ItemStack result = furnaceInventory.getResult();
151 if (usable(result)) return result;
152
153 ItemStack input = furnaceInventory.getSmelting();
154 return usable(input) ? input : null;
155 }
156
157 ItemStack[] contents = inventory.getStorageContents();
158 int usableCount = 0;
159 for (ItemStack item : contents) {
160 if (usable(item)) usableCount++;
161 }
162 if (usableCount == 0) return null;
163
164 int selectedIndex = ThreadLocalRandom.current().nextInt(usableCount);
165 for (ItemStack item : contents) {
166 if (!usable(item)) continue;
167 if (selectedIndex-- == 0) return item;
168 }
169 return null;
170 }
171
172 private static boolean usable(ItemStack item) {
173 return item != null && item.getType() != Material.AIR && item.getAmount() > 0;
174 }
175
176 private VisualSpec visualSpec(Material material) {
177 float scale = (float) plugin.getConfig().getDouble("display.scale", 0.40);
178 float roll = radians(plugin.getConfig().getDouble("display.rotation.roll", 0.0));
179 boolean block = material.isBlock();
180
181 float modelYaw = block ? 0.0f : radians(180.0);
182 float modelPitch = 0.0f;
183
184 if (material.name().endsWith("_STAIRS")) {
185 modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-yaw", 0.0));
186 modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-pitch", 0.0));
187 } else if (block) {
188 modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.default-yaw", 0.0));
189 modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.default-pitch", 0.0));
190 }
191
192 byte transform = block ? ITEM_TRANSFORM_FIXED : ITEM_TRANSFORM_GUI;
193 boolean glowing = plugin.getConfig().getBoolean("display.glowing", false);
194 return new VisualSpec(scale, modelPitch, modelYaw, roll, transform, glowing);
195 }
196
197 private void syncViewers(BlockKey key, PreviewState state, boolean newlyCreated, boolean moved, boolean metadataChanged) {
198 Set<UUID> stillVisible = new HashSet<>();
199
200 for (Player player : Bukkit.getOnlinePlayers()) {
201 if (!shouldView(player, state.location)) continue;
202 UUID playerId = player.getUniqueId();
203 stillVisible.add(playerId);
204
205 if (state.viewers.add(playerId)) {
206 sendSpawn(player, state);
207 } else {
208 if (moved) sendTeleport(player, state);
209 if (metadataChanged || newlyCreated) sendMetadata(player, state);
210 }
211 }
212
213 Iterator<UUID> iterator = state.viewers.iterator();
214 while (iterator.hasNext()) {
215 UUID viewerId = iterator.next();
216 if (stillVisible.contains(viewerId)) continue;
217 Player viewer = Bukkit.getPlayer(viewerId);
218 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
219 iterator.remove();
220 }
221 }
222
223 private boolean shouldView(Player player, Location location) {
224 if (location.getWorld() == null || !player.getWorld().getUID().equals(location.getWorld().getUID())) return false;
225 int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4));
226 int playerChunkX = player.getLocation().getChunk().getX();
227 int playerChunkZ = player.getLocation().getChunk().getZ();
228 int previewChunkX = ((int) Math.floor(location.getX())) >> 4;
229 int previewChunkZ = ((int) Math.floor(location.getZ())) >> 4;
230 return Math.abs(playerChunkX - previewChunkX) <= radius && Math.abs(playerChunkZ - previewChunkZ) <= radius;
231 }
232
233 private void sendSpawn(Player player, PreviewState state) {
234 WrapperPlayServerSpawnEntity spawn = new WrapperPlayServerSpawnEntity(
235 state.entityId,
236 state.entityUuid,
237 EntityTypes.ITEM_DISPLAY,
238 SpigotConversionUtil.fromBukkitLocation(state.location),
239 state.location.getYaw(),
240 0,
241 null);
242 PacketEvents.getAPI().getPlayerManager().sendPacket(player, spawn);
243 sendMetadata(player, state);
244 }
245
246 private void sendMetadata(Player player, PreviewState state) {
247 List<EntityData<?>> data = new ArrayList<>(8);
248 byte flags = state.visual.glowing ? ENTITY_FLAG_GLOWING : 0;
249 data.add(new EntityData<>(META_ENTITY_FLAGS, EntityDataTypes.BYTE, flags));
250 data.add(new EntityData<>(META_NO_GRAVITY, EntityDataTypes.BOOLEAN, true));
251 data.add(new EntityData<>(META_SCALE, EntityDataTypes.VECTOR3F,
252 new Vector3f(state.visual.scale, state.visual.scale, state.visual.scale)));
253 data.add(new EntityData<>(META_LEFT_ROTATION, EntityDataTypes.QUATERNION,
254 quaternionXYZ(state.visual.pitch, state.visual.yaw, state.visual.roll)));
255 data.add(new EntityData<>(META_RIGHT_ROTATION, EntityDataTypes.QUATERNION,
256 new Quaternion4f(0.0f, 0.0f, 0.0f, 1.0f)));
257 data.add(new EntityData<>(META_BILLBOARD, EntityDataTypes.BYTE, BILLBOARD_FIXED));
258 data.add(new EntityData<>(META_ITEM, EntityDataTypes.ITEMSTACK,
259 SpigotConversionUtil.fromBukkitItemStack(state.item)));
260 data.add(new EntityData<>(META_ITEM_TRANSFORM, EntityDataTypes.BYTE, state.visual.itemTransform));
261
262 PacketEvents.getAPI().getPlayerManager().sendPacket(
263 player,
264 new WrapperPlayServerEntityMetadata(state.entityId, data));
265 }
266
267 private void sendTeleport(Player player, PreviewState state) {
268 PacketEvents.getAPI().getPlayerManager().sendPacket(
269 player,
270 new WrapperPlayServerEntityTeleport(
271 state.entityId,
272 SpigotConversionUtil.fromBukkitLocation(state.location),
273 false));
274 }
275
276 private void sendDestroy(Player player, int entityId) {
277 PacketEvents.getAPI().getPlayerManager().sendPacket(
278 player,
279 new WrapperPlayServerDestroyEntities(entityId));
280 }
281
282 private void destroyPreview(BlockKey key) {
283 PreviewState state = previews.remove(key);
284 if (state == null) return;
285 for (UUID viewerId : new HashSet<>(state.viewers)) {
286 Player viewer = Bukkit.getPlayer(viewerId);
287 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
288 }
289 state.viewers.clear();
290 }
291
292 private void pruneViewers() {
293 for (PreviewState state : previews.values()) {
294 Iterator<UUID> iterator = state.viewers.iterator();
295 while (iterator.hasNext()) {
296 UUID viewerId = iterator.next();
297 Player viewer = Bukkit.getPlayer(viewerId);
298 if (viewer != null && viewer.isOnline() && shouldView(viewer, state.location)) continue;
299 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
300 iterator.remove();
301 }
302 }
303 }
304
305 /**
306 * Register containers once when a chunk is discovered. Legacy Bukkit ItemDisplays from
307 * ChestPreview <= 1.0.8 are removed as a migration step, but no new Bukkit entity is spawned.
308 */
309 void discoverChunk(Chunk chunk) {
310 cleanupLegacyDisplays(chunk);
311 registerContainersInChunk(chunk, true);
312 }
313
314 void rebuildChunk(Chunk chunk) {
315 int chunkX = chunk.getX();
316 int chunkZ = chunk.getZ();
317 World world = chunk.getWorld();
318 ChunkKey chunkKey = ChunkKey.of(chunk);
319
320 cleanupLegacyDisplays(chunk);
321
322 List<BlockKey> toDestroy = new ArrayList<>();
323 for (BlockKey key : previews.keySet()) {
324 if (isInChunk(key, world, chunkX, chunkZ)) toDestroy.add(key);
325 }
326 for (BlockKey key : toDestroy) destroyPreview(key);
327
328 scanQueue.removeIf(key -> isInChunk(key, world, chunkX, chunkZ));
329 queued.removeIf(key -> isInChunk(key, world, chunkX, chunkZ));
330 knownContainers.remove(chunkKey);
331
332 registerContainersInChunk(chunk, true);
333 }
334
335 void forgetChunk(Chunk chunk) {
336 ChunkKey chunkKey = ChunkKey.of(chunk);
337 Set<BlockKey> forgotten = knownContainers.remove(chunkKey);
338 if (forgotten == null) return;
339
340 for (BlockKey key : forgotten) {
341 destroyPreview(key);
342 queued.remove(key);
343 }
344 scanQueue.removeIf(forgotten::contains);
345 }
346
347 private void cleanupLegacyDisplays(Chunk chunk) {
348 for (Entity entity : chunk.getEntities()) {
349 if (!(entity instanceof ItemDisplay display)) continue;
350 if (display.getPersistentDataContainer().has(legacyManagedKey, PersistentDataType.BYTE)) {
351 display.remove();
352 }
353 }
354 }
355
356 private void registerContainersInChunk(Chunk chunk, boolean enqueueForRefresh) {
357 for (BlockState state : chunk.getTileEntities()) {
358 Block block = state.getBlock();
359 if (!isSupported(block)) continue;
360 ContainerTarget target = ContainerTarget.fromBlock(block);
361 if (target == null) continue;
362 rememberTarget(target);
363 if (enqueueForRefresh) enqueue(target.key());
364 }
365 }
366
367 private void rememberTarget(ContainerTarget target) {
368 BlockKey key = target.key();
369 knownContainers.computeIfAbsent(ChunkKey.of(key), ignored -> new HashSet<>()).add(key);
370 }
371
372 private void forgetKnownKey(BlockKey key) {
373 Set<BlockKey> keys = knownContainers.get(ChunkKey.of(key));
374 if (keys == null) return;
375 keys.remove(key);
376 if (keys.isEmpty()) knownContainers.remove(ChunkKey.of(key));
377 }
378
379 private static boolean isInChunk(BlockKey key, World world, int chunkX, int chunkZ) {
380 return key.worldId().equals(world.getUID()) && (key.x() >> 4) == chunkX && (key.z() >> 4) == chunkZ;
381 }
382
383 void enqueue(BlockKey key) {
384 if (queued.add(key)) scanQueue.offer(key);
385 }
386
387 void enqueue(Block block) {
388 if (!isSupported(block)) return;
389 ContainerTarget target = ContainerTarget.fromBlock(block);
390 if (target == null) return;
391 rememberTarget(target);
392 enqueue(target.key());
393 }
394
395 void processScanBatch() {
396 int maximum = Math.max(1, plugin.getConfig().getInt("updates.containers-per-batch", 5));
397 for (int i = 0; i < maximum; i++) {
398 BlockKey key = scanQueue.poll();
399 if (key == null) return;
400 queued.remove(key);
401 World world = Bukkit.getWorld(key.worldId());
402 if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue;
403 refresh(world.getBlockAt(key.x(), key.y(), key.z()));
404 }
405 }
406
407 /**
408 * Every interval, already-known containers near players are visited. If cycling is enabled,
409 * the preview item is reselected. The same pass also creates/removes client-only viewers as
410 * players enter or leave the configured four-chunk radius. No chunk tile-entity scan occurs.
411 */
412 void cycleNearbyContainers() {
413 int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4));
414 boolean cycling = plugin.getConfig().getBoolean("cycling.enabled", true);
415 Set<BlockKey> targets = new HashSet<>();
416 Set<ChunkKey> visitedChunks = new HashSet<>();
417
418 for (Player player : Bukkit.getOnlinePlayers()) {
419 Chunk center = player.getLocation().getChunk();
420 World world = player.getWorld();
421 for (int dx = -radius; dx <= radius; dx++) {
422 for (int dz = -radius; dz <= radius; dz++) {
423 int chunkX = center.getX() + dx;
424 int chunkZ = center.getZ() + dz;
425 if (!world.isChunkLoaded(chunkX, chunkZ)) continue;
426 ChunkKey chunkKey = new ChunkKey(world.getUID(), chunkX, chunkZ);
427 if (!visitedChunks.add(chunkKey)) continue;
428 Set<BlockKey> known = knownContainers.get(chunkKey);
429 if (known != null) targets.addAll(known);
430 }
431 }
432 }
433
434 for (BlockKey key : targets) {
435 World world = Bukkit.getWorld(key.worldId());
436 if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue;
437 Block block = world.getBlockAt(key.x(), key.y(), key.z());
438 if (!isSupported(block)) {
439 removeForPhysicalBlock(key);
440 continue;
441 }
442
443 if (cycling || !previews.containsKey(key)) {
444 refresh(block);
445 } else {
446 PreviewState state = previews.get(key);
447 if (state != null) syncViewers(key, state, false, false, false);
448 }
449 }
450
451 pruneViewers();
452 }
453
454 void enqueueLoadedChunks() {
455 for (World world : Bukkit.getWorlds()) {
456 for (Chunk chunk : world.getLoadedChunks()) discoverChunk(chunk);
457 }
458 }
459
460 void cleanupAll() {
461 destroyAllPacketDisplays();
462 scanQueue.clear();
463 queued.clear();
464 knownContainers.clear();
465 for (World world : Bukkit.getWorlds()) {
466 for (Chunk chunk : world.getLoadedChunks()) cleanupLegacyDisplays(chunk);
467 }
468 }
469
470 void shutdown() {
471 destroyAllPacketDisplays();
472 scanQueue.clear();
473 queued.clear();
474 knownContainers.clear();
475 }
476
477 private void destroyAllPacketDisplays() {
478 for (PreviewState state : previews.values()) {
479 for (UUID viewerId : new HashSet<>(state.viewers)) {
480 Player viewer = Bukkit.getPlayer(viewerId);
481 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
482 }
483 state.viewers.clear();
484 }
485 previews.clear();
486 }
487
488 void removeForPhysicalBlock(BlockKey physical) {
489 Block block = physical.getBlock();
490 if (block != null && isSupported(block)) {
491 ContainerTarget target = ContainerTarget.fromBlock(block);
492 if (target != null) {
493 forgetKnownKey(target.key());
494 destroyPreview(target.key());
495 }
496 }
497 forgetKnownKey(physical);
498 destroyPreview(physical);
499 }
500
501 private static Location copyLocation(Location source) {
502 return new Location(source.getWorld(), source.getX(), source.getY(), source.getZ(), source.getYaw(), source.getPitch());
503 }
504
505 private static boolean sameLocation(Location a, Location b) {
506 if (a.getWorld() == null || b.getWorld() == null) return false;
507 return a.getWorld().getUID().equals(b.getWorld().getUID())
508 && Double.compare(a.getX(), b.getX()) == 0
509 && Double.compare(a.getY(), b.getY()) == 0
510 && Double.compare(a.getZ(), b.getZ()) == 0
511 && Float.compare(a.getYaw(), b.getYaw()) == 0
512 && Float.compare(a.getPitch(), b.getPitch()) == 0;
513 }
514
515 private static boolean sameItem(ItemStack a, ItemStack b) {
516 return a.getAmount() == b.getAmount() && a.isSimilar(b);
517 }
518
519 private static float radians(double degrees) {
520 return (float) Math.toRadians(degrees);
521 }
522
523 /** Equivalent to JOML Quaternionf().rotateXYZ(x, y, z) used by 1.0.8. */
524 private static Quaternion4f quaternionXYZ(float x, float y, float z) {
525 float sx = (float) Math.sin(x * 0.5f);
526 float cx = (float) Math.cos(x * 0.5f);
527 float sy = (float) Math.sin(y * 0.5f);
528 float cy = (float) Math.cos(y * 0.5f);
529 float sz = (float) Math.sin(z * 0.5f);
530 float cz = (float) Math.cos(z * 0.5f);
531
532 float qx = sx * cy * cz + cx * sy * sz;
533 float qy = cx * sy * cz - sx * cy * sz;
534 float qz = cx * cy * sz + sx * sy * cz;
535 float qw = cx * cy * cz - sx * sy * sz;
536 return new Quaternion4f(qx, qy, qz, qw);
537 }
538
539 private static final class PreviewState {
540 private final int entityId;
541 private final UUID entityUuid;
542 private final Set<UUID> viewers = new HashSet<>();
543 private Location location;
544 private ItemStack item;
545 private VisualSpec visual;
546
547 private PreviewState(int entityId, UUID entityUuid, Location location, ItemStack item, VisualSpec visual) {
548 this.entityId = entityId;
549 this.entityUuid = entityUuid;
550 this.location = location;
551 this.item = item;
552 this.visual = visual;
553 }
554 }
555
556 private record VisualSpec(float scale, float pitch, float yaw, float roll, byte itemTransform, boolean glowing) {}
557
558 private record ChunkKey(UUID worldId, int x, int z) {
559 static ChunkKey of(Chunk chunk) {
560 return new ChunkKey(chunk.getWorld().getUID(), chunk.getX(), chunk.getZ());
561 }
562
563 static ChunkKey of(BlockKey key) {
564 return new ChunkKey(key.worldId(), key.x() >> 4, key.z() >> 4);
565 }
566 }
567}
src/main/resources/config.yml added +49 −0
@@ -0,0 +1,49 @@
1 containers:
2 chest: true
3 trapped-chest: true
4 barrel: true
5
6 # These machines show their output/result slot, or their input slot while output is empty.
7 output-containers:
8 furnace: true
9 blast-furnace: true
10 smoker: true
11
12 display:
13 scale: 0.40
14 forward-offset: 0.515
15 vertical-offset: 0.42
16 sideways-offset: 0.0
17
18 rotation:
19 yaw: 0.0
20 pitch: 0.0
21 roll: 0.0
22
23 # Flat/2D items are automatically rotated 180 degrees to face outward.
24 block-rotation:
25 default-yaw: 0.0
26 default-pitch: 0.0
27 stairs-yaw: 0.0
28 stairs-pitch: 0.0
29
30 glowing: false
31
32 updates:
33 # Event-triggered refreshes are deduplicated and processed in small batches.
34 containers-per-batch: 5
35 batch-interval-ticks: 3
36
37 # Register and queue all already-loaded containers once when the plugin starts.
38 scan-loaded-chunks-on-startup: true
39
40 # Reconcile and rebuild a chunk once whenever it loads again.
41 rebuild-chunk-on-load: true
42
43 cycling:
44 # Randomly choose another occupied slot once per second. This timer also handles packet-only
45 # viewer tracking: previews are sent only to players within this many loaded chunks.
46 # No chunk tile-entity rescan is performed here.
47 enabled: true
48 interval-ticks: 20
49 player-chunk-radius: 4
@@ -0,0 +1,49 @@
1containers:
2 chest: true
3 trapped-chest: true
4 barrel: true
5
6# These machines show their output/result slot, or their input slot while output is empty.
7output-containers:
8 furnace: true
9 blast-furnace: true
10 smoker: true
11
12display:
13 scale: 0.40
14 forward-offset: 0.515
15 vertical-offset: 0.42
16 sideways-offset: 0.0
17
18 rotation:
19 yaw: 0.0
20 pitch: 0.0
21 roll: 0.0
22
23 # Flat/2D items are automatically rotated 180 degrees to face outward.
24 block-rotation:
25 default-yaw: 0.0
26 default-pitch: 0.0
27 stairs-yaw: 0.0
28 stairs-pitch: 0.0
29
30 glowing: false
31
32updates:
33 # Event-triggered refreshes are deduplicated and processed in small batches.
34 containers-per-batch: 5
35 batch-interval-ticks: 3
36
37 # Register and queue all already-loaded containers once when the plugin starts.
38 scan-loaded-chunks-on-startup: true
39
40 # Reconcile and rebuild a chunk once whenever it loads again.
41 rebuild-chunk-on-load: true
42
43cycling:
44 # Randomly choose another occupied slot once per second. This timer also handles packet-only
45 # viewer tracking: previews are sent only to players within this many loaded chunks.
46 # No chunk tile-entity rescan is performed here.
47 enabled: true
48 interval-ticks: 20
49 player-chunk-radius: 4
src/main/resources/plugin.yml added +23 −0
@@ -0,0 +1,23 @@
1 name: ChestPreview
2 version: '1.0.10'
3 main: nl.timfalken.chestpreview.ChestPreviewPlugin
4 api-version: '26.2'
5 author: Tim Falken
6 website: https://timfalken.com
7 description: Shows container contents as client-only packet previews on their front.
8 softdepend:
9 - ProtocolLib
10 - ProtocolSupport
11 - ViaVersion
12 - ViaBackwards
13 - ViaRewind
14 - Geyser-Spigot
15 commands:
16 chestpreview:
17 description: Manage ChestPreview
18 usage: /chestpreview <reload|refresh|cleanup>
19 permission: chestpreview.admin
20 permissions:
21 chestpreview.admin:
22 description: Allows management of ChestPreview
23 default: op
@@ -0,0 +1,23 @@
1name: ChestPreview
2version: '1.0.10'
3main: nl.timfalken.chestpreview.ChestPreviewPlugin
4api-version: '26.2'
5author: Tim Falken
6website: https://timfalken.com
7description: Shows container contents as client-only packet previews on their front.
8softdepend:
9 - ProtocolLib
10 - ProtocolSupport
11 - ViaVersion
12 - ViaBackwards
13 - ViaRewind
14 - Geyser-Spigot
15commands:
16 chestpreview:
17 description: Manage ChestPreview
18 usage: /chestpreview <reload|refresh|cleanup>
19 permission: chestpreview.admin
20permissions:
21 chestpreview.admin:
22 description: Allows management of ChestPreview
23 default: op