diff --git a/.forgejo/tests/web-deploy.test.mjs b/.forgejo/tests/web-deploy.test.mjs index 8931e5f0..472e930c 100644 --- a/.forgejo/tests/web-deploy.test.mjs +++ b/.forgejo/tests/web-deploy.test.mjs @@ -9,7 +9,7 @@ const steps = new Map( return [chunk.slice(0, lineEnd).trim(), chunk.slice(lineEnd + 1)]; }) ); -const production = "github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main'"; +const production = "github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main'"; function step(name) { assert.ok(steps.has(name), 'Expected workflow step: ' + name); @@ -20,7 +20,7 @@ test('development can dispatch a build and production still builds on main pushe assert.match(workflow, /^ workflow_dispatch:\s*$/m); assert.match(workflow, /^ push:\r?\n branches:\r?\n - main\r?$/m); assert.equal(workflow.match(/^ if: (.+)$/m)?.[1].trim(), - "github.repository == 'unimatrix/MC' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch')"); + "github.repository == 'unimatrix/web' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch')"); for (const name of ['Verify deployment policy', 'Build and test website']) { assert.doesNotMatch(step(name), /^ if:/m); } @@ -30,7 +30,7 @@ test('checkout fetches the exact event commit from the repository running the wo const checkout = step('Check out exact revision'); assert.match(checkout, /fetch --depth=1 "https:\/\/www\.dunerealms\.com\/git\/\$\{GITHUB_REPOSITORY\}\.git" "\$GITHUB_SHA"/); assert.match(checkout, /git checkout --detach FETCH_HEAD\r?\n\s+test "\$\(git rev-parse HEAD\)" = "\$GITHUB_SHA"/); - assert.doesNotMatch(checkout, /unimatrix\/MC/); + assert.doesNotMatch(checkout, /unimatrix\/web/); }); test('publication comparison, artifact upload and deployment require canonical main', () => { @@ -44,3 +44,11 @@ test('publication comparison, artifact upload and deployment require canonical m if (name !== 'Trigger deployment after successful CI') assert.doesNotMatch(body, /DUNEREALMS_DEPLOY_KEY|ssh .*dunedeploy@/); } }); + + +test('deployment uses the verified dedicated host and its pinned SSH key', () => { + const deploy = step('Trigger deployment after successful CI'); + assert.ok(deploy.includes('95.216.100.187 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICdHgR/5lVFKbOpAYR2+/Bi5LSg+8nDCSm77mJOmJKRg')); + assert.ok(deploy.includes('dunedeploy@95.216.100.187')); + assert.ok(!deploy.includes('91.107.196.242')); +}); diff --git a/.forgejo/workflows/clean-ci-artifacts.yml b/.forgejo/workflows/clean-ci-artifacts.yml index fbaf6289..94b9ac50 100644 --- a/.forgejo/workflows/clean-ci-artifacts.yml +++ b/.forgejo/workflows/clean-ci-artifacts.yml @@ -24,7 +24,7 @@ jobs: REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/web.git "$GITHUB_SHA" git checkout --detach FETCH_HEAD - name: Install Node 22 uses: actions/setup-node@v4 diff --git a/.forgejo/workflows/kit-delivery.yml b/.forgejo/workflows/kit-delivery.yml deleted file mode 100644 index 73b9faee..00000000 --- a/.forgejo/workflows/kit-delivery.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: DuneRealms Kit Delivery CI -on: - push: - branches: [main, dev/kit-atelier-v3] - paths: - - 'network/server-control/kit*' - - 'network/server-control/player_kits.py' - - '.forgejo/workflows/kit-delivery.yml' - workflow_dispatch: -jobs: - kits: - runs-on: dune-ci - steps: - - name: Checkout - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" - git checkout --detach FETCH_HEAD - - name: Verify kit delivery bridge - run: python3 -m unittest discover -s network/server-control -p 'test_*.py' -v diff --git a/.forgejo/workflows/plugins.yml b/.forgejo/workflows/plugins.yml deleted file mode 100644 index d7241b8f..00000000 --- a/.forgejo/workflows/plugins.yml +++ /dev/null @@ -1,91 +0,0 @@ -name: DuneRealms Plugin CI -on: - workflow_dispatch: - push: - branches: [main] - paths: - - '.forgejo/workflows/plugins.yml' - - 'Dune*/**' - - 'JarvisConnector/**' - - 'gui-common/**' - - 'network/proxy/central-pack/**' - -jobs: - plugins: - runs-on: dune-ci - steps: - - name: Check out exact revision - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -euo pipefail - git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA" - git checkout --detach FETCH_HEAD - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '9.2.1' - - name: Test and build first-party plugins - shell: bash - run: | - set -euo pipefail - modules=(DuneEss DuneLobby DuneNPC DuneRealms-minecraft-only DuneTerrain JarvisConnector) - if [[ -f network/proxy/central-pack/build.gradle.kts ]]; then - modules+=(network/proxy/central-pack) - fi - mkdir -p plugin-artifacts - for module in "${modules[@]}"; do - gradle --no-daemon -p "$module" test jar - for jar in "$module"/build/libs/*.jar; do - test -f "$jar" - artifact="plugin-artifacts/${jar##*/}" - test ! -e "$artifact" - cp "$jar" "$artifact" - done - done - printf '%s\n' "$(git rev-parse HEAD)" > plugin-artifacts/SOURCE_COMMIT - (cd plugin-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS) - - uses: actions/upload-artifact@v3 - with: - name: DuneRealms-Plugins - path: plugin-artifacts/ - if-no-files-found: error - - - name: Test and build the replacement DuneMenus plugin - shell: bash - run: | - set -euo pipefail - gradle --no-daemon -p DuneMenus test jar - mkdir -p dunemenus-artifacts - cp DuneMenus/build/libs/DuneMenus.jar dunemenus-artifacts/ - printf '%s\n' "$(git rev-parse HEAD)" > dunemenus-artifacts/SOURCE_COMMIT - (cd dunemenus-artifacts && sha256sum -- DuneMenus.jar SOURCE_COMMIT > SHA256SUMS) - - uses: actions/upload-artifact@v3 - with: - name: ${{ github.repository == 'dev/MC' && 'DuneMenus-Development' || 'DuneMenus' }} - path: dunemenus-artifacts/ - if-no-files-found: error - - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '25' - - name: Build optional Paper 26.2 fullscreen provider - shell: bash - run: | - set -euo pipefail - gradle --no-daemon -p DuneFullscreenPaper test jar - mkdir -p fullscreen-artifacts - cp DuneFullscreenPaper/build/libs/DuneFullscreenPaper.jar fullscreen-artifacts/ - printf '%s\n' "$(git rev-parse HEAD)" > fullscreen-artifacts/SOURCE_COMMIT - (cd fullscreen-artifacts && sha256sum -- DuneFullscreenPaper.jar SOURCE_COMMIT > SHA256SUMS) - - uses: actions/upload-artifact@v3 - with: - name: DuneRealms-Fullscreen-Paper-Development - path: fullscreen-artifacts/ - if-no-files-found: error diff --git a/.forgejo/workflows/resourcepack-ci.yml b/.forgejo/workflows/resourcepack-ci.yml deleted file mode 100644 index 59109b1a..00000000 --- a/.forgejo/workflows/resourcepack-ci.yml +++ /dev/null @@ -1,113 +0,0 @@ -name: DuneRealms Resourcepack CI -on: - workflow_dispatch: - push: - branches: [main] - paths: - - 'DuneRealmsGUI/**' - - 'tools/build-resourcepack-repair.py' - - 'tools/test_resourcepack_repair.py' - - 'tools/build-arrakis-fauna-pack.mjs' - - 'tools/build-fauna-models.mjs' - - 'tools/build-fauna-pack-update.py' - - 'tools/test_fauna_pack_update.py' - - 'DuneTerrain/**' - - 'DuneRealms-minecraft-only/**' - - 'JarvisConnector/**' - - '.forgejo/workflows/resourcepack-ci.yml' -jobs: - resourcepack: - if: github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main' && github.event_name == 'push' - runs-on: dune-ci - steps: - - name: Checkout exact reviewed revision - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" - git checkout --detach FETCH_HEAD - - name: Build immutable repair archives and verify pinned inputs - shell: bash - run: | - mkdir -p resourcepack-baselines resourcepack-output - curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v3.zip -o resourcepack-baselines/DuneRealms-Network-Artwork-v3.zip - curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Materials-arrakis-v4.zip -o resourcepack-baselines/DuneRealms-Materials-arrakis-v4.zip - DUNE_REPAIR_BASELINE_DIR="$PWD/resourcepack-baselines" python3 tools/test_resourcepack_repair.py -v - python3 tools/build-resourcepack-repair.py resourcepack-baselines/DuneRealms-Network-Artwork-v3.zip resourcepack-baselines/DuneRealms-Materials-arrakis-v4.zip resourcepack-output - DUNE_FAUNA_BASELINE_DIR="$PWD/resourcepack-output" python3 tools/test_fauna_pack_update.py -v - python3 tools/build-fauna-pack-update.py resourcepack-output resourcepack-output/fauna-preview - - name: Install Java 21 - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - name: Install Gradle - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '9.2.1' - - name: Build and test pack delivery plugin - run: | - gradle --no-daemon -p DuneTerrain test jar - gradle --no-daemon -p DuneRealms-minecraft-only test jar - gradle --no-daemon -p JarvisConnector test jar - gradle --no-daemon -p DuneMenus test jar - - name: Upload reviewed packs and GUI plugin - uses: actions/upload-artifact@v3 - with: - name: DuneRealms-Resourcepack-Repair - path: | - resourcepack-output/ - DuneMenus/build/libs/DuneMenus.jar - DuneTerrain/build/libs/DuneRealms-Terrain.jar - DuneRealms-minecraft-only/build/libs/DuneRealms-Core.jar - JarvisConnector/build/libs/jarvistranslator.jar - if-no-files-found: error - retention-days: 7 - - central-pack-development: - if: github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch' - runs-on: dune-ci - steps: - - name: Check out exact development revision - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -euo pipefail - git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA" - git checkout --detach FETCH_HEAD - test "$(git rev-parse HEAD)" = "$GITHUB_SHA" - - uses: actions/setup-node@v4 - with: - node-version: '22' - - name: Verify baseline and build a central pack candidate - shell: bash - run: | - set -euo pipefail - node --test tools/build-planet-texture-packs.test.mjs - curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v6.zip -o central-pack-baseline.zip - python3 - <<'PYTHON' - import pathlib - import runpy - repair = runpy.run_path('tools/build-resourcepack-repair.py') - entries = repair['read_pack']( - pathlib.Path('central-pack-baseline.zip'), - 'ed2533646ee5e19a1dbfeec66e5791d1011a5107e6fcc4153372e431dfc5f56a', - ) - for name, data in entries.items(): - target = pathlib.Path('central-pack-base') / name - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(data) - PYTHON - node tools/build-central-resource-pack.mjs central-pack-base central-pack-output 7 network/resource-pack/shared - printf '%s\n' "$GITHUB_SHA" > central-pack-output/SOURCE_COMMIT - (cd central-pack-output && sha256sum -- *.zip central-pack-manifest.json SOURCE_COMMIT > SHA256SUMS) - - uses: actions/upload-artifact@v3 - with: - name: DuneRealms-Central-Pack-Development - path: central-pack-output/ - if-no-files-found: error - retention-days: 7 diff --git a/.forgejo/workflows/web-deploy.yml b/.forgejo/workflows/web-deploy.yml index 602fa720..ea4a8b42 100644 --- a/.forgejo/workflows/web-deploy.yml +++ b/.forgejo/workflows/web-deploy.yml @@ -1,85 +1,93 @@ -name: DuneRealms Web CI - -on: - push: - branches: - - main - paths: - - 'website/**' - - '.forgejo/workflows/web-deploy.yml' - - '.forgejo/tests/web-deploy.test.mjs' - workflow_dispatch: - -jobs: - web: - if: github.repository == 'unimatrix/MC' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch') - runs-on: dune-ci - steps: - - name: Check out exact revision - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -euo pipefail - git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA" - git checkout --detach FETCH_HEAD - test "$(git rev-parse HEAD)" = "$GITHUB_SHA" - - - name: Install Node 22 - uses: actions/setup-node@v4 - with: - node-version: '22' - - - name: Prepare publication comparison - if: github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main' - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");') - if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" - BEFORE=$(git rev-parse HEAD^) - else - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$BEFORE" - fi - node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA" - - - name: Verify deployment policy - run: | - node --test .forgejo/tests/web-deploy.test.mjs - python3 -m unittest discover -s website/ops -p 'test_*.py' - - - name: Build and test website - working-directory: website - run: | - corepack enable - corepack pnpm install --frozen-lockfile - corepack pnpm build - corepack pnpm test - node --test --test-concurrency=1 ../tools/tests/*.test.mjs - - - name: Upload website build - if: github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main' - uses: actions/upload-artifact@v3 - with: - name: DuneRealms-Website - path: website/dist/ - if-no-files-found: error - retention-days: 1 - - - name: Trigger deployment after successful CI - if: github.repository == 'unimatrix/MC' && github.ref == 'refs/heads/main' - shell: bash - env: - DEPLOY_KEY: ${{ secrets.DUNEREALMS_DEPLOY_KEY }} - run: | - install -m 700 -d ~/.ssh - printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key - chmod 600 ~/.ssh/deploy_key - trap 'rm -f ~/.ssh/deploy_key' EXIT - printf '%s\n' '91.107.196.242 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC8x/XocsIz41fWHGty0DbZhSvafSQFt9jaHHgzdr55W root@ubuntu-4gb-fsn1-1' >> ~/.ssh/known_hosts - ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@91.107.196.242 "$GITHUB_SHA" - rm -f ~/.ssh/deploy_key - +name: DuneRealms Web CI + +on: + push: + branches: + - main + paths: + - 'website/**' + - '.forgejo/workflows/web-deploy.yml' + - '.forgejo/tests/web-deploy.test.mjs' + workflow_dispatch: + +jobs: + web: + if: github.repository == 'unimatrix/web' || (github.repository == 'dev/MC' && github.event_name == 'workflow_dispatch') + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 "https://www.dunerealms.com/git/${GITHUB_REPOSITORY}.git" "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + test "$(git rev-parse HEAD)" = "$GITHUB_SHA" + + - name: Install Node 22 + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Prepare publication comparison + if: github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main' + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");') + if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/web.git "$GITHUB_SHA" + BEFORE=$(git rev-parse HEAD^) + else + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/web.git "$BEFORE" + fi + node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA" + + - name: Verify deployment policy + run: | + node --test .forgejo/tests/web-deploy.test.mjs + python3 -m unittest discover -s website/ops -p 'test_*.py' + bash -n website/ops/dunerealms-ci-trigger website/ops/dunerealms-build-release + + - name: Build and test website + working-directory: website + run: | + corepack enable + corepack pnpm install --frozen-lockfile + corepack pnpm build + corepack pnpm test + + - name: Upload tested deployment scripts + uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Website-Operations + path: website/dist/deployment/ + if-no-files-found: error + retention-days: 7 + + - name: Upload website build + if: github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main' + uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Website + path: website/dist/ + if-no-files-found: error + retention-days: 1 + + - name: Trigger deployment after successful CI + if: github.repository == 'unimatrix/web' && github.ref == 'refs/heads/main' + shell: bash + env: + DEPLOY_KEY: ${{ secrets.DUNEREALMS_DEPLOY_KEY }} + run: | + install -m 700 -d ~/.ssh + printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key + chmod 600 ~/.ssh/deploy_key + trap 'rm -f ~/.ssh/deploy_key' EXIT + printf '%s\n' '95.216.100.187 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICdHgR/5lVFKbOpAYR2+/Bi5LSg+8nDCSm77mJOmJKRg' >> ~/.ssh/known_hosts + ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@95.216.100.187 "$GITHUB_SHA" + rm -f ~/.ssh/deploy_key + diff --git a/.gitattributes b/.gitattributes index b26e6b46..cb3ec7e1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,7 @@ *.pdf binary *.png binary *.zip binary +.forgejo/workflows/web-deploy.yml text eol=lf +website/ops/dunerealms-ci-trigger text eol=lf +website/ops/dunerealms-build-release text eol=lf +website/ops/README.md text eol=lf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index 821e49c5..00000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,221 +0,0 @@ - -name: Build DuneCore, DuneNPC, DuneEss, and DuneTerrain - -on: - workflow_dispatch: - push: - branches: [main, "feature/native-gui-1.21.8"] - -jobs: - build-website: - runs-on: ubuntu-latest - defaults: - run: - working-directory: website - steps: - - name: Checkout source - uses: actions/checkout@v4 - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version: '22' - - name: Install website server dependencies - run: npm install --omit=dev --no-audit --no-fund - - name: Build the illustrated website and API - run: node scripts/build.mjs - - name: Test feeds and compiled pages - run: node --test tests/*.test.mjs - - name: Test inventory ownership and private market bridge - run: node --test ../control-panel-inventory/tests/*.test.mjs - - name: Upload website build - uses: actions/upload-artifact@v4 - with: - name: Project-Dune-Website - path: website/dist/ - include-hidden-files: true - if-no-files-found: error - - build-core: - runs-on: ubuntu-latest - - defaults: - run: - working-directory: DuneRealms-minecraft-only - - steps: - - name: Checkout source - uses: actions/checkout@v4 - - - name: Set up Java 21 - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '8.14' - - - name: Compile DuneCore - run: gradle clean build - - - name: Upload compiled JAR - uses: actions/upload-artifact@v4 - with: - name: DuneCore-Plugin - path: DuneRealms-minecraft-only/build/libs/*.jar - if-no-files-found: error - - build-terrain: - runs-on: ubuntu-latest - defaults: - run: - working-directory: DuneTerrain - steps: - - name: Checkout source - uses: actions/checkout@v4 - - name: Set up Java 21 - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '8.14' - - name: Compile DuneTerrain - run: gradle clean build - - name: Upload compiled JAR - uses: actions/upload-artifact@v4 - with: - name: DuneTerrain-Plugin - path: DuneTerrain/build/libs/*.jar - if-no-files-found: error - - build-ess: - runs-on: ubuntu-latest - defaults: - run: - working-directory: DuneEss - steps: - - name: Checkout source - uses: actions/checkout@v4 - - name: Set up Java 21 - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '8.14' - - name: Compile DuneEss - run: gradle clean build - - name: Upload compiled JAR - uses: actions/upload-artifact@v4 - with: - name: DuneEss-Plugin - path: DuneEss/build/libs/*.jar - if-no-files-found: error - - build-npc: - runs-on: ubuntu-latest - defaults: - run: - working-directory: DuneNPC - steps: - - name: Checkout source - uses: actions/checkout@v4 - - name: Set up Java 21 - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '8.14' - - name: Compile and test DuneNPC - run: gradle clean build - - name: Upload compiled JAR - uses: actions/upload-artifact@v4 - with: - name: DuneNPC-Plugin - path: DuneNPC/build/libs/*.jar - if-no-files-found: error - - build-lobby: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '8.14' - - run: gradle -p DuneLobby clean build - - uses: actions/upload-artifact@v4 - with: - name: DuneLobby-Plugin - path: DuneLobby/build/libs/*.jar - if-no-files-found: error - - package-server: - runs-on: ubuntu-latest - needs: [build-core, build-ess, build-terrain, build-npc, build-lobby] - steps: - - name: Checkout source - uses: actions/checkout@v4 - - name: Download all plugin JARs - uses: actions/download-artifact@v4 - with: - pattern: Dune*-Plugin - path: DuneRealms-Server-Package - merge-multiple: true - - name: Download verified crossplay plugins - run: python3 tools/download-crossplay.py DuneRealms-Server-Package/crossplay - - name: Add resource pack and install instructions - run: | - curl --fail --location --silent --show-error \ - https://github.com/Foulest/Vault/releases/download/2.5.0/Vault-2.5.0.jar \ - --output DuneRealms-Server-Package/Vault-2.5.0.jar - echo "3efb1c893d35807c0f3945068858a96af0f131020eee37545bdddb330044b2d9 DuneRealms-Server-Package/Vault-2.5.0.jar" | sha256sum --check --strict - curl --fail --location --silent --show-error \ - https://raw.githubusercontent.com/Foulest/Vault/2.5.0/LICENSE \ - --output DuneRealms-Server-Package/Vault-LICENSE.txt - cp DuneResourcePack.zip DuneRealms-Server-Package/ - cp docs/Dune-User-Manual.pdf DuneRealms-Server-Package/ - cp docs/Dune-Complete-Illustrated-Manual.pdf DuneRealms-Server-Package/ - cp docs/posters/*.png DuneRealms-Server-Package/ - cp docs/Native-GUI.md DuneRealms-Server-Package/Native-GUI.md - cp README.md DuneRealms-Server-Package/Project-README.md - cp website/DISCORD-FEEDS.md DuneRealms-Server-Package/DiscordSRV-Website-Setup.md - cat > DuneRealms-Server-Package/README.txt <<'EOF' - DuneRealms Paper server package - - Contents: Vault 2.5.0, all five Dune plugins, and verified Geyser, Floodgate, ViaVersion JARs. - See Native-GUI.md for platform-specific plugin placement. - The illustrated user manual and Project-README.md are included for players and administrators. - - Install the applicable plugin JARs in the Paper server's plugins/ folder and restart the server. - Install the included resource pack on vanilla or Fabric 1.21.4 clients for sandworm, haunted Fremen, and spice textures. - On Fabric, put the ZIP in .minecraft/resourcepacks and enable it in Options > Resource Packs; do not put it in mods/. - DuneEss provides the Solaris economy through the included Vault API plugin. - Vault 2.5.0 is the GPL-3.0 licensed Foulest/MilkBowl Vault project; its license is included here. - Its source is available at https://github.com/Foulest/Vault/tree/2.5.0. - - Compatible GUI build target: Paper 1.21.8, Java 21. - See https://github.com/thomasv6545-glitch/MC for setup and configuration details. - EOF - - name: ZIP every server plugin JAR together - run: zip -r DuneRealms-All-Server-Jars.zip DuneRealms-Server-Package - - name: Upload one downloadable server package - uses: actions/upload-artifact@v4 - with: - name: DuneRealms-Server-Package - path: DuneRealms-All-Server-Jars.zip - if-no-files-found: error - retention-days: 90 diff --git a/.github/workflows/lobby.yml b/.github/workflows/lobby.yml deleted file mode 100644 index fb57d9a7..00000000 --- a/.github/workflows/lobby.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Build Guild Lobby companion -on: - workflow_dispatch: - push: - branches: [main, beta] - paths: ['DuneLobby/**', 'worlds/**', '.github/workflows/lobby.yml', 'gui-common/**'] -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '8.14' - - run: gradle -p DuneLobby build - - uses: actions/upload-artifact@v4 - with: - name: Dune-Guild-Lobby - path: | - DuneLobby/build/libs/*.jar - worlds/Dune-Guild-Lobby-1.1.0.zip - DuneLobby/README.md - DuneLobby/VALIDATION.md - if-no-files-found: error diff --git a/.github/workflows/network-preflight.yml b/.github/workflows/network-preflight.yml deleted file mode 100644 index e5e6b8ed..00000000 --- a/.github/workflows/network-preflight.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Network configuration preflight -on: - push: - paths: - - 'network/**' - - 'DuneTerrain/src/main/resources/config.yml' - - '.github/workflows/network-preflight.yml' - workflow_dispatch: -jobs: - validate: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - name: Check inventory and build world config ZIPs - run: python3 network/preflight.py --check-worlds - - name: Simulate 1000 chunks of planetary ore attempts - run: python3 network/simulate-ores.py - - name: Upload world configuration packages - uses: actions/upload-artifact@v4 - with: - name: dune-world-configs - path: network/generated-worlds/*-world-config.zip diff --git a/.github/workflows/network.yml b/.github/workflows/network.yml deleted file mode 100644 index 362dfe3d..00000000 --- a/.github/workflows/network.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: Package DuneRealms Velocity Network -on: - workflow_dispatch: - push: - branches: [main, "feature/native-gui-1.21.8"] - paths: - - 'network/**' - - 'gui-common/**' - - 'tools/**' - - 'DuneLobby/**' - - 'DuneTerrain/**' - - 'DuneEss/**' - - 'DuneNPC/**' - - 'DuneRealms-minecraft-only/**' - - '.github/workflows/network.yml' -jobs: - package: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '8.14' - - name: Build plugins - run: | - set -e - mkdir -p built-plugins - for project in DuneRealms-minecraft-only DuneTerrain DuneNPC DuneEss DuneLobby; do - (cd "$project" && gradle clean build) - done - cp DuneRealms-minecraft-only/build/libs/*.jar built-plugins/DuneCore.jar - cp DuneTerrain/build/libs/*.jar built-plugins/DuneTerrain.jar - cp DuneNPC/build/libs/*.jar built-plugins/DuneNPC.jar - cp DuneEss/build/libs/*.jar built-plugins/DuneRealms-Essentials.jar - cp DuneLobby/build/libs/*.jar built-plugins/DuneLobby.jar - - name: Download verified crossplay plugins - run: | - python3 tools/download-crossplay.py built-crossplay - curl --fail --location --silent --show-error https://github.com/Foulest/Vault/releases/download/2.5.0/Vault-2.5.0.jar --output built-crossplay/universal/Vault-2.5.0.jar - echo "3efb1c893d35807c0f3945068858a96af0f131020eee37545bdddb330044b2d9 built-crossplay/universal/Vault-2.5.0.jar" | sha256sum --check --strict - curl --fail --location --silent --show-error https://raw.githubusercontent.com/Foulest/Vault/2.5.0/LICENSE --output built-crossplay/Vault-LICENSE.txt - - name: Package six servers and Velocity config - run: python3 network/package.py - - uses: actions/upload-artifact@v4 - with: - name: DuneRealms-Velocity-Network - path: DuneRealms-Velocity-Network.zip - if-no-files-found: error diff --git a/AGENTS.md b/AGENTS.md index 00e43e35..3ff98484 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,105 +1,45 @@ -# DuneRealms default working instructions +# DuneRealms website working instructions -These are the user's default preferences for future DuneRealms work. Apply them unless the user changes them. +## Repository ownership -## Production release rules +- `unimatrix/web:main` owns the website, control panels, web APIs and their deployment configuration. +- `unimatrix/plugins:main` owns Minecraft plugins, resource packs, game-server configuration and worlds. Do not import or deploy those components from this repository. +- `dev/MC` is a historical development reference. Check actual subtree hashes before importing anything: the latest website, item cards and cookbook were already present on web/main when the repositories were separated on 29 November 2026. +- The GitHub `unimatrixgit/mcdune-backup` repository is a recovery backup. Its existence does not authorise a rollback or replacement of newer work. -- `unimatrix/MC:main` is the production source. Keep the website and the currently deployed Arrakis plugin source together. `dev/MC` is the development fork for edits, commits, builds and CI. Preserve uncommitted work when reconciling checkouts. -- Keep at most one open pull request per repository. Reuse it for follow-up commits. Direct pushes to main are prohibited. Merge completed changes only after successful CI and explicit owner authorization. -- Every plugin change goes through a build from a recorded Git commit. Record each JAR filename, plugin version and SHA-256 in the release manifest. Roll out the exact tested artifacts and verify their hashes against the installed JARs. -- Treat any mismatch between the production source, the build manifest and the installed plugins as release drift. Reconcile the source and retest before a replacement rollout. Avoid manual edits or class overlays on live JARs. +## Changes and review -## Tools and access +- Code and test locally, commit to a task branch and push a pull request. Do not push directly to main or merge unrelated branches. +- Preserve unrelated work and game/account data. Never change identity, permissions, balances or progression as a workaround. +- Use the current owner instructions as authoritative. Historical combined-repository plans and role resets are superseded. +- Merge only the exact reviewed commit after required checks and owner approval. Do not bypass an automatic approval rejection through another tool or Git command. +- Keep the current website PR focused and coordinate overlapping changes before editing another chat's files. -- Prefer the connected Composio Gitea/Forgejo integration for DuneGit repository reads, pull requests, workflow dispatch, CI status, and deployment actions. -- Discover the actual tools and schemas before use. Do not assume that a GitHub tool targets DuneGit. -- Use local Git for local edits, diffs, commits, and efficient pushes of tested local changes. This does not require SSH access to the server. -- Use direct SSH only for server operations that repository/CI tools cannot perform. Keep SSH use minimal. Do not require Gateway when it is unavailable or its quota is exhausted. -- Never save passwords, private keys, tokens, or credential-bearing URLs in instructions, commits, logs, or PR descriptions. +## Build inputs and checks -## Small batches through CI +- Website source and required data live under `website/`. Cookbook inputs live under `website/data/cookbook`, with recorded source hashes. +- Website item-design export utilities live in `website/scripts`. `tools/README.md` is a temporary compatibility input for the previously installed staging command; no plugin tooling belongs there. +- Use Node22 and the locked pnpm dependencies. Run `pnpm build` and `pnpm test` from `website/`. +- Run `.forgejo/tests/web-deploy.test.mjs` with Node and `website/ops/test_*.py` with Python on Linux. The Linux deployment checks require `fcntl` and cannot pass natively on Windows. +- Tests that create local HTTP servers need permission for loopback connections. Report environmental failures accurately and rerun with the needed permission; do not weaken production code to hide them. +- Required release evidence includes the commit, actual checks, CI run, generated artifact and live serving revision. A build or artifact upload is not proof of deployment. +- Owner's mandatory release rule, 29 November 2026: EVERY plugin, page, asset and configuration alteration goes through the committed build pipeline. Do not publish independently created plugin JARs/pages, copy local edits live, or leave direct live patches outside the build. SSH may resolve a blocker, but its persistent correction must be committed and included in the next verified build. -- Implement, check, commit, and publish small coherent batches as work progresses. Do not hold all completed work until the entire feature is finished. -- Reuse existing infrastructure, permissions, audit records, and payment/voting mechanisms wherever possible. -- Run checks appropriate to each batch. Fix failures caused by the change before publishing. Report any existing unrelated failures accurately. -- Push changes to the current development branch. Update the existing pull request until the agreed scope is complete. -- Deploy verified batches through the established website CI and deployment pipeline. A workflow dispatch being accepted, or an artifact being uploaded, does not establish that production is updated. -- Follow CI and deployment through completion, then verify the live release and affected behavior before claiming it is live. -- If a dispatch reports an error after HTTP 204, or a write times out, inspect the resulting run/remote state before retrying. Avoid duplicate writes or deployments. +## Access and server changes -## Protect existing progress +- Prefer Composio for DuneGit metadata, pull requests and CI actions. Local HTTPS Git is authorised for code, commits and pushes. +- Server SSH is restricted to the owner's designated coordinating web/scope chat for resolving blockers. Other agents/chats must not use SSH without a later explicit owner change. +- Any necessary server alteration must also be reflected in source or deployment configuration and committed, with verification, so later builds retain the fix. Do not leave undocumented hot patches. +- Never write credentials, private keys, tokens or credential-bearing URLs to source, commits, logs or ordinary artifacts. -- Inspect the working tree and remote branch heads before changing branches or publishing. Preserve unrelated edits and work in progress. -- Explicitly fetch the intended remote branch ref into its tracking ref when needed, and verify it matches the remote head. Do not assume a plain fetch refreshed an old tracking branch. -- Never restore an old release, force-push, hard-reset, replace live files from an old backup, or resolve conflicts by discarding newer work merely to make deployment pass. -- Stop and diagnose unexpected ancestry, missing files, or modify/delete conflicts. Preserve the current state; do not force a merge or push. -- Keep backups outside the source tree and do not copy credentials into ordinary build artifacts. -- Do not run broad cleanup, destructive migrations, or financial transactions unless the user has authorized the actual action. +## Product behavior -## Collaboration and product behavior +- Preserve the accepted DuneRealms design and reuse existing navigation, services and domain permissions. +- DuneForge is the existing `#forge/git-workspace` workspace; the root DuneGit register is `/git/`. +- Item cards display authoritative metadata from native Bukkit items or a verified signed HQ design. Do not invent quality, marks, lore, enchantments or stats from material names. +- Official CMS Exchange publications use the existing item-definition key and an immutable `cms.item` binding to the exact In-game Bank Treasury account. Player resales of custom items pay the player. Preserve the recovered HQ publisher, recipient-bound `/redeem` gift flow and atomic publication/payment/delivery receipts; do not replace them with placeholders or infer an official payee from an item's name or origin alone. +- Preserve real voting, banking and item-issuance boundaries. Public presentation must not expose serialized items, signatures or service credentials. +- Describe what is coded, tested, merged and deployed separately. Mark unavailable features honestly. +- The owner requires one shared header and footer across portal, CP and other website surfaces. Use one canonical source and publication path; aligning labels on separate implementations is insufficient. Verify signed-in rendering as well as emitted HTML. -- Continue authorized work without repeated permission questions or handoffs. Do not switch to Work mode. -- Give concise progress updates describing results, blockers, and the next useful step. -- Preserve existing working voting and banking behavior. Personal voting rights are absolute; organisation voting changes must not transfer personal votes. -- Place new features in the existing navigation structure when an item already exists. Avoid duplicate menus. -- Use the established CP design, readable colors, gold framing, and appropriate original Dune/Minecraft-inspired artwork. Company CP uses the Vaerkring/Spacing Guild-inspired palette. -- Clearly mark unfinished features as coming soon. Do not display invented records, offers, payments, or completed actions. - -## J.A.R.V.I.S. data-operation workflow (2026-11-18) - -- Use Git, reviewed batches and CI for changes to files, code, schemas and action implementations. -- Perform supported user/domain data changes through validated J.A.R.V.I.S. actions and instruments. Do not use ad hoc SQL/manual database editing as an operational shortcut. -- Special dev keys are server/CLI-only overrides bound to an exact action manifest, environment, authorised developer identity and short validity. Never expose their issuance, secrets or execution through website routes, dropdowns or web APIs, including Big 4 accounts. -- An ordinary code is not authority. Revalidate identity, action scope and domain conditions on execution. Keep irreversible actions explicit in the manifest. -- Record issuance ID/hash, actor, manifest hash, each result, failures and completion; never log a secret key. Enforce once-only execution and safe retries/rollback. -- Existing supported data actions require no PR/deployment per execution. New action logic still requires tests, Git and publication. -- Never call a verifier-only test a successful live operation. Report local, simulated, staged and executed states accurately. -- Seasonal changes use an explicit versioned dev batch. Preserve/reset decisions are per-season configuration, not automatic consequences of every deploy. -- Honour the approved reset exclusions: official/protected organisations and the owner's clan/company rosters; no broader reset unless explicitly requested. No Minecraft code or deployment in this web/backend batch. - -Current priority: implement and test the server-only dev-key executor, starting with the authorised clan-reset batch. Keep special dev tools outside the website package. - -## Masterkey reuse before new code - -- Before implementing a page or action, read `website/control-panel/public/jarvis-master-keys.mjs` and its existing domain adapter. Reuse an existing action rather than duplicating its flow. -- Register every new key-backed action in that catalogue in the same change, with version, typed fields, domain rules, authority and execution status. Never claim a catalogue entry is executable before its adapter is connected. -- The website generator cannot generate or modify developer keys, including for owner/Big 4 accounts. This is a fixed server boundary, not an assignable permission. An issued devkey can only be used through its separately permitted execution route. Developer issuance remains outside the website package. - -## Chat-requested keys must update web keygen - -- Whenever the user requests a key here in the development chat, find its mastertemplate and execution flow first. If absent, add the versioned template, typed fields and validated domain adapter, then update/publish the web generator as part of fulfilling that request. Reuse existing flows when present. -- This trigger is a chat request, not website-submitted arbitrary flow code. The website cannot create new execution logic from user input. -- Developer keys remain an absolute exception to web issuance: keygen must never generate or modify them, including for owner/Big 4. Devticket requests may collect a requested action and approval; developer issuance remains in the separately authorised development flow. - -## Developer keys are the last resort - -- For every requested operation, first search the masterkey catalogue and existing domain actions for a normal scoped key that achieves the same authorised result. Prefer it over a developer key. -- Do not broaden an ordinary key, bypass its permission checks, or disguise developer capabilities as a normal template to avoid this boundary. If no suitable ordinary flow exists, a separately approved developer ticket/key may be considered through the developer-only route. - -## User-requested batch tracking (24 November 2026) - -- Before starting each implementation batch, create one Development task ticket through the existing validated private support workflow. The user explicitly authorises automatic approval of these batch tickets. -- Group at least three genuine user requests in a batch; do not count individual technical edits as separate requests. War is one request, POL missions and POL decisions are the other two requests in the current batch. -- Include the scope checklist, verification plan, PR/commit and actual live-release evidence in that ticket. Update its progress and complete it only when its stated scope is actually live and verified. -- Placeholder pages must be explicitly marked as previews and include all appropriate DuneRealms artwork. Preserve working actions while the remaining consumers are built. - -## Latest owner direction: portal and control-panel redesign (24 November 2026) - -- The owner said “negeer ticketsâ€�: skip ticket creation; it must not block work. -- Current priority is the public portal preview before further CP redesign. The owner explicitly wants to keep the current site if unsatisfied: do not replace the live homepage before design acceptance. -- Use the supplied green/gold portal image as inspiration, not an immutable layout. Preserve the existing logo, seals, awards and avatars. Other layouts, menus and artwork may be redesigned, including the CPs. -- Reduce the number of control panels and unify their design, but do not cram everything into one panel. Personal services, organisation management and staff need distinct, understandable workspaces. -- The POL backend can retain its existing service contracts independently of presentation changes. The tested political-war backend batch remains on PR 563, separate from this design preview. -- Existing hostnames are sufficient for this preview. Discuss a new hostname only if implementation actually needs it. - -## Accepted full-site scope (24 November 2026) - -- Portal design accepted. Apply the approved shared style throughout the site, Exchange and control panels, then finish the backend. -- User comfort takes priority: short navigation, readable labels, accessible mobile controls and clear back paths. -- Consolidate clan/company/POL presentation in an organisation workspace; personal and staff remain separate. Preserve all domain permissions and deep links. -- Latest bans and appeals belong on a separate Community page. Keep original logos, seals, awards, avatars and the approved travel picker. - -## Backend integration after design acceptance - -- Preserve the accepted site redesign. Continue the authorised war, POL missions and POL decisions through their existing service contracts. -- Ticket creation remains skipped by the explicit owner override. +- Workspace menus (Staff, User CP and Bank) must display every menu item in the normal page flow. Never add a viewport height cap, sticky scrolling container or independent scrollbar to `#sidebar` or `#sidebar-right`. Scroll the main page; do not hide overflow to conceal unreachable links. Verify this after shared stylesheet publication. diff --git a/DuneEss/EXCHANGE.md b/DuneEss/EXCHANGE.md deleted file mode 100644 index d435d836..00000000 --- a/DuneEss/EXCHANGE.md +++ /dev/null @@ -1,30 +0,0 @@ -# CHOAM exchange — DuneEss 1.0.4 - -Install matching DuneRealms-Core.jar (1.0.12) and DuneRealms-Essentials.jar (1.0.4), with Vault and existing modules on Java 21 / Paper 1.21.8. Stop all planetary servers, back up SQL/player data, replace only these plugin JARs and configure the shared PostgreSQL database on every backend before starting. Preserve all worlds/configurations. See [database setup](../network/database/README.md). - -## Player controls - -- `/exchange` (`/choam`, `/market`): native Java/Bedrock exchange menu. -- `/exchange sell `: list 1–64 held items, up to 1,000,000 Solari per item, two decimal places. Items are escrowed with names, enchantments, Dune metadata and item data. Administrative items are rejected. -- `/exchange buy `: inspect and confirm the purchase of one item. -- `/exchange mine`: browse your listings and reclaim unsold stock. -- `/exchange cancel `: confirm cancellation of your own listing. -- `/exchange admin`: operator inspection and database check. Ownership rules still apply. - -Filters, pagination, capacity checks, stale-confirmation handling and self-purchase rejection remain supported. Missing/incompatible shared Core profiles refuse to trade; lobby inventories never enter the planetary exchange. - -## Transactions and history - -Every actual player trade runs through Core's owned profile connection. Listing escrow, buyer debit, seller credit, stock changes, the resulting authoritative player inventory checkpoint, and any completed sale history commit together. A normal SQL failure restores the in-memory inventory and rolls back all SQL. If the commit outcome is uncertain, the profile is quarantined and ordinary quit saving is suppressed until manual recovery. Excess item delivery aborts the transaction instead of dropping items into the world. - -The sales ledger `dune_exchange_sales` retains a row per completed unit purchase, including seller/buyer names and UUIDs, item/material, quantity, exact unit/total price, origin and timestamp. Cancelling or failing a trade creates no sale. Earlier sales cannot be reconstructed retroactively. Configured shared economy deposits/withdrawals now use atomic SQL arithmetic and do not fall back to stale local balances during SQL outages. - -General gameplay/container changes outside these exchange transactions still rely on autosaves and unclean-session recovery. This is not an exactly-once guarantee for every Minecraft/plugin interaction. Ender chests remain local. SQL remains synchronous with bounded timeouts; profile capacity and staging tests are documented in the database guide. - -## Account page and website - -[control-panel-inventory](../control-panel-inventory/README.md) contains the account-page armor mannequin, saved inventory and **History of sales**, plus authenticated read-only API handlers, a private market listings bridge, integration instructions and a self-contained demo preview. The CP source is not in MC, so live wiring/deployment is a handoff task. Purchases remain in-game. Existing public website demo offers remain labelled until its operator enables the supplied live bridge. - -## Validation - -Run `gradle build` in Core and DuneEss and `node --test tests/*.test.mjs` in control-panel-inventory. Core tests use mocked JDBC/Paper and exchange SQL tests use H2 PostgreSQL compatibility mode, including concurrency, rollback, sales ledger and externally owned transactions. Live PostgreSQL/Paper/Velocity/Bedrock validation is pending. diff --git a/DuneEss/build.gradle.kts b/DuneEss/build.gradle.kts deleted file mode 100644 index 914d7b4b..00000000 --- a/DuneEss/build.gradle.kts +++ /dev/null @@ -1,40 +0,0 @@ -plugins { java } -group = "com.example" -version = "1.0.12" -repositories { - mavenCentral() - maven("https://repo.papermc.io/repository/maven-public/") - maven("https://jitpack.io") -} -dependencies { - compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") - compileOnly("com.github.MilkBowl:VaultAPI:1.7") { - exclude(group = "org.bukkit", module = "bukkit") - } - implementation("org.postgresql:postgresql:42.7.4") - testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") - testImplementation("com.h2database:h2:2.3.232") - testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") - testImplementation("org.mockito:mockito-core:5.15.2") - testImplementation("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } - testRuntimeOnly("org.junit.platform:junit-platform-launcher") -} -tasks.jar { - archiveBaseName.set("DuneEss") - duplicatesStrategy = DuplicatesStrategy.EXCLUDE - from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }) -} -java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } -tasks.withType { options.encoding = "UTF-8" } -tasks.test { useJUnitPlatform() } - -repositories { maven("https://repo.opencollab.dev/main/") } -dependencies { compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") } -sourceSets.main { java.srcDir("../gui-common/src/main/java") } - -tasks.jar { archiveFileName.set("DuneRealms-Essentials.jar") } - -// Explicit test instrumentation works on Java 21 without dynamic self-attachment. -val mockitoAgent by configurations.creating -dependencies { mockitoAgent("org.mockito:mockito-core:5.15.2") { isTransitive = false } } -tasks.test { jvmArgs("-javaagent:${mockitoAgent.singleFile.absolutePath}") } diff --git a/DuneEss/settings.gradle.kts b/DuneEss/settings.gradle.kts deleted file mode 100644 index a59a2e72..00000000 --- a/DuneEss/settings.gradle.kts +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = "DuneEss" diff --git a/DuneEss/src/main/java/com/example/duneess/CommunityCodes.java b/DuneEss/src/main/java/com/example/duneess/CommunityCodes.java deleted file mode 100644 index 4f588e43..00000000 --- a/DuneEss/src/main/java/com/example/duneess/CommunityCodes.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.example.duneess; - -import com.google.gson.*; -import org.bukkit.Bukkit; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.configuration.file.YamlConfiguration; -import java.io.File; -import java.net.URI; -import java.net.http.*; -import java.time.Duration; -import java.util.*; - -/** Authenticated website bridge; rewards are always credited by the UUID/month ledger. */ -final class CommunityCodes implements CommandExecutor,TabCompleter { - private final DuneEss plugin; - private final HttpClient http=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build(); - private final Set busy=new HashSet<>(); - private final Map cooldown=new HashMap<>(); - private final String endpoint,secret; - private boolean syncing; - CommunityCodes(DuneEss plugin){ - this.plugin=plugin; - File file=new File(plugin.getDataFolder(),"website-bridge.yml");if(!file.exists())plugin.saveResource("website-bridge.yml",false); - YamlConfiguration settings=YamlConfiguration.loadConfiguration(file);endpoint=settings.getString("origin","https://cp.dunerealms.com");secret=settings.getString("secret",""); - for(String name:List.of("communitycode","linkwebsite")){PluginCommand command=Objects.requireNonNull(plugin.getCommand(name));command.setExecutor(this);command.setTabCompleter(this);} - Bukkit.getScheduler().runTaskTimer(plugin,this::syncReceipts,200L,1200L); - } - private JsonObject post(String path,JsonObject body) throws Exception { - if(secret.length()<32||!endpoint.equals("https://cp.dunerealms.com"))throw new IllegalStateException("Website bridge is not configured"); - HttpRequest request=HttpRequest.newBuilder(URI.create(endpoint+path)).timeout(Duration.ofSeconds(10)).header("Authorization","Bearer "+secret).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(body.toString())).build(); - HttpResponse response=http.send(request,HttpResponse.BodyHandlers.ofString()); - if(response.body().length()>16384)throw new IllegalStateException("Unexpected bridge response"); - JsonObject data=JsonParser.parseString(response.body()).getAsJsonObject(); - if(response.statusCode()!=200)throw new IllegalStateException(data.has("message")?data.get("message").getAsString():"Website unavailable");return data; - } - @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){ - if(!(sender instanceof Player player)){sender.sendMessage(com.example.dunegui.PublicNames.text("Players only."));return true;} - boolean linking=command.getName().equals("linkwebsite"); - if(args.length!=1){player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Generate a private link command at https://cp.dunerealms.com":"Public community codes: https://www.dunerealms.com/donate.html | Personal codes: https://cp.dunerealms.com | /communitycode CODE"));return true;} - String code=linking?args[0].toLowerCase(Locale.ROOT):args[0].toUpperCase(Locale.ROOT); - if(!(linking?code.matches("[a-f0-9]{32}"):code.matches("[A-Z0-9-]{4,48}"))){player.sendMessage(com.example.dunegui.PublicNames.text("Invalid code format."));return true;} - UUID uuid=player.getUniqueId();long now=System.currentTimeMillis();cooldown.entrySet().removeIf(entry->now-entry.getValue()>60000); - if(busy.contains(uuid)||now-cooldown.getOrDefault(uuid,0L)<3000){player.sendMessage(com.example.dunegui.PublicNames.text("Please wait a few seconds before trying again."));return true;} - cooldown.put(uuid,now);busy.add(uuid); - JsonObject body=new JsonObject();body.addProperty("uuid",uuid.toString());body.addProperty("name",player.getName());body.addProperty("code",code); - player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Verifying website link…":"Checking community reward…")); - Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{try{ - JsonObject response=post(linking?"/api/game-link/consume":"/api/community/game/prepare",body); - Bukkit.getScheduler().runTask(plugin,()->{try{ - if(linking){player.sendMessage(com.example.dunegui.PublicNames.text("Website account linked to your Minecraft UUID. Refresh the account panel."));return;} - if(response.has("delivered")&&response.get("delivered").getAsBoolean()){player.sendMessage("This Minecraft UUID has already received that month's reward.");return;} - String month=response.get("month").getAsString(),receipt=response.get("receipt").getAsString();int amount=response.get("amount").getAsInt(); - boolean granted=((DuneEconomy)plugin.economy()).grantCommunity(uuid,month,amount,receipt); - player.sendMessage(com.example.dunegui.PublicNames.text(granted?"Community reward credited: "+amount+" Dunemarks. Thank you, everyone!":"This UUID has already claimed that month's reward. No duplicate currency credited.")); - syncReceipts(); - }catch(Exception error){plugin.getLogger().warning("Community reward could not be committed: "+error.getClass().getSimpleName());player.sendMessage(com.example.dunegui.PublicNames.text("The reward could not be confirmed. Your code remains available; try again later."));}finally{busy.remove(uuid);}}); - }catch(Exception error){Bukkit.getScheduler().runTask(plugin,()->{busy.remove(uuid);player.sendMessage(com.example.dunegui.PublicNames.text("Website request failed. Check the account panel or public code page and try again later."));});}}); - return true; - } - private void syncReceipts(){ - if(syncing||secret.length()<32)return; - Map> pending;try{pending=((DuneEconomy)plugin.economy()).pendingCommunityReceipts();}catch(Exception error){return;} - if(pending.isEmpty())return;syncing=true; - Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{List> confirmed=new ArrayList<>(); - try{for(var player:pending.entrySet())for(String receipt:player.getValue()){ - JsonObject body=new JsonObject();body.addProperty("uuid",player.getKey().toString());body.addProperty("receipt",receipt); - try{post("/api/community/game/ack",body);confirmed.add(Map.entry(player.getKey(),receipt));}catch(Exception unavailable){return;} - }}finally{Bukkit.getScheduler().runTask(plugin,()->{try{for(var row:confirmed)((DuneEconomy)plugin.economy()).acknowledgeCommunity(row.getKey(),row.getValue());}catch(Exception error){plugin.getLogger().warning("Community receipts will retry on the next sync.");}finally{syncing=false;}});} - }); - } - @Override public List onTabComplete(CommandSender sender,Command command,String alias,String[] args){return List.of();} -} diff --git a/DuneEss/src/main/java/com/example/duneess/DuneCommands.java b/DuneEss/src/main/java/com/example/duneess/DuneCommands.java deleted file mode 100644 index 8db68041..00000000 --- a/DuneEss/src/main/java/com/example/duneess/DuneCommands.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.example.duneess; - -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.command.TabExecutor; - -final class DuneCommands implements TabExecutor { - private static final Map ROUTES = Map.ofEntries( - Map.entry("home", "duneess:home"), Map.entry("sethome", "duneess:sethome"), - Map.entry("homes", "duneess:homes"), Map.entry("delhome", "duneess:delhome"), - Map.entry("spawn", "duneess:spawn"), Map.entry("server", "duneess:server"), - Map.entry("tpa", "duneess:tpa"), Map.entry("tpaccept", "duneess:tpaccept"), - Map.entry("tpdeny", "duneess:tpdeny"), Map.entry("essentials", "duneess:essentials"), - Map.entry("link", "duneess:linkwebsite"), Map.entry("linkwebsite", "duneess:linkwebsite"), - Map.entry("communitycode", "duneess:communitycode"), - Map.entry("condense", "duneess:condense"), Map.entry("fix", "duneess:fix"), - Map.entry("pay", "jarvistranslator:pay"), Map.entry("invite", "jarvistranslator:invite"), - Map.entry("accept", "jarvistranslator:accept"), Map.entry("join", "jarvistranslator:join"), - Map.entry("leave", "jarvistranslator:leave"), Map.entry("redeem", "jarvistranslator:redeem"), - Map.entry("jarvis", "jarvistranslator:jarvistranslator"), - Map.entry("faction", "dunemenus:house"), Map.entry("house", "dunemenus:house"), - Map.entry("start", "dunemenus:start"), Map.entry("mentat", "dunemenus:mentat"), - Map.entry("exchange", "dunemenus:exchange"), Map.entry("spice", "dunemenus:spice"), - Map.entry("sell", "dunemenus:sellall"), Map.entry("sellall", "dunemenus:sellall"), - Map.entry("clan", "dunemenus:clan"), - Map.entry("company", "dunemenus:company"), Map.entry("office", "dunemenus:politics"), - Map.entry("scoreboard", "dunemenus:scoreboard"), Map.entry("menu", "dunemenus:dm"), - Map.entry("guildtravel", "dunemenus:guildtravel"), Map.entry("warmuster", "dunemenus:warmuster"), - Map.entry("rosterkey", "dunemenus:rosterkey"), Map.entry("lobby", "dunelobby:lobby"), - Map.entry("lobbyadmin", "dunelobby:dunelobby"), Map.entry("npc", "dunenpc:dunenpc"), - Map.entry("protect", "duneprotect:duneprotect"), Map.entry("ban", "duneban:duneban"), - Map.entry("unban", "duneban:duneunban")); - - private static final List CORE = List.of("admin", "adminitem", "summon", "choose", - "smuggle", "bounty", "npcadmin", "elytra", "kit", "politics", "trust", "water", - "gui", "guireload", "menuitem", "serverjobs", "job", "guildnpc", "givespice"); - private static final List ESSENTIALS = List.of("balance", "travel", "help"); - private static final List ESSENTIALS_ADMIN = List.of("solari", "teleport", "spicebloom"); - private static final List CLAN_ACTIONS = List.of("invite", "accept", "join", "leave"); - private static final List STAFF = List.of("admin", "adminitem", "summon", "npcadmin", - "guireload", "guildnpc", "givespice", "lobbyadmin", "npc", "protect", "ban", "unban", - "jarvis", "condense", "fix"); - - private final DuneEss plugin; - - private record Route(String target, String[] args, String label) {} - - static void register(DuneEss plugin) { - var router = new DuneCommands(plugin); - var command = Objects.requireNonNull(plugin.getCommand("dune")); - command.setExecutor(router); - command.setTabCompleter(router); - } - - private DuneCommands(DuneEss plugin) { this.plugin = plugin; } - - private static Route route(String[] args) { - String root = args[0].toLowerCase(Locale.ROOT); - if (root.equals("clan") && args.length > 1 && CLAN_ACTIONS.contains(args[1].toLowerCase(Locale.ROOT))) { - return new Route(ROUTES.get(args[1].toLowerCase(Locale.ROOT)), Arrays.copyOfRange(args, 2, args.length), "dune clan " + args[1]); - } - if (ESSENTIALS.contains(root) || (root.equals("admin") && args.length > 1 - && ESSENTIALS_ADMIN.contains(args[1].toLowerCase(Locale.ROOT)))) { - return new Route("duneess:duneess", args, "dune"); - } - if (CORE.contains(root)) return new Route("dunecore:dune", args, "dune"); - String target = ROUTES.get(root); - return target == null ? null : new Route(target, Arrays.copyOfRange(args, 1, args.length), "dune " + root); - } - - private PluginCommand target(Route route) { - if (route == null) return null; - PluginCommand target = plugin.getServer().getPluginCommand(route.target()); - return target != null && target.getPlugin().isEnabled() ? target : null; - } - - @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (args.length == 0 || (args.length == 1 && args[0].equalsIgnoreCase("help"))) { - help(sender); - return true; - } - Route route = route(args); - if (route == null) { - sender.sendMessage("Unknown Dune command. Use /dune help."); - return true; - } - PluginCommand target = target(route); - if (target == null) { - sender.sendMessage("This Dune command is unavailable on this server."); - return true; - } - target.execute(sender, route.label(), route.args()); - return true; - } - - private boolean available(CommandSender sender, String name) { - PluginCommand target = target(route(new String[]{name})); - return target != null && target.testPermissionSilent(sender); - } - - private void help(CommandSender sender) { - sender.sendMessage("DuneRealms commands · /dune "); - if (available(sender, "pay")) sender.sendMessage("/dune pay "); - if (available(sender, "invite")) sender.sendMessage("/dune clan invite · /dune clan join [tag] · /dune clan leave"); - helpLine(sender, "Homes and travel", "home", "sethome", "homes", "delhome", "spawn", "tpa", "tpaccept", "tpdeny", "travel", "lobby"); - helpLine(sender, "Clans and House", "clan", "invite", "accept", "join", "leave", "company", "faction", "mentat", "office"); - helpLine(sender, "Bank and trade", "pay", "balance", "exchange", "spice", "sellall"); - helpLine(sender, "Quests and wars", "start", "bounty", "warmuster", "rosterkey", "scoreboard", "menu"); - helpLine(sender, "Account and services", "link", "redeem", "communitycode", "guildtravel", "essentials", "server"); - helpLine(sender, "Arrakis and politics", "smuggle", "elytra", "kit", "politics", "trust", "water", "job", "serverjobs"); - if (sender.hasPermission("dune.admin")) helpLine(sender, "Staff", STAFF.toArray(String[]::new)); - } - - private void helpLine(CommandSender sender, String name, String... commands) { - var visible = Arrays.stream(commands).filter(action -> available(sender, action)).toList(); - if (!visible.isEmpty()) sender.sendMessage(name + " · " + String.join(", ", visible)); - } - - @Override public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { - if (args.length <= 1) { - String prefix = args.length == 0 ? "" : args[0].toLowerCase(Locale.ROOT); - return java.util.stream.Stream.concat(java.util.stream.Stream.of("help"), - java.util.stream.Stream.concat(ROUTES.keySet().stream(), java.util.stream.Stream.concat(CORE.stream(), ESSENTIALS.stream()))) - .distinct().filter(name -> name.startsWith(prefix)) - .filter(name -> !STAFF.contains(name) || sender.hasPermission("dune.admin")) - .filter(name -> name.equals("help") || available(sender, name)).sorted().toList(); - } - if (args.length == 2 && args[0].equalsIgnoreCase("clan")) { - String prefix = args[1].toLowerCase(Locale.ROOT); - return CLAN_ACTIONS.stream().filter(action -> action.startsWith(prefix) && available(sender, action)).toList(); - } - Route route = route(args); - PluginCommand target = target(route); - if (target == null || !target.testPermissionSilent(sender)) return List.of(); - return target.tabComplete(sender, route.label(), route.args()); - } -} diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java b/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java deleted file mode 100644 index 8e84df36..00000000 --- a/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java +++ /dev/null @@ -1,341 +0,0 @@ -package com.example.duneess; - -import net.milkbowl.vault.economy.Economy; -import net.milkbowl.vault.economy.EconomyResponse; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** DuneEss's Solaris ledger and Vault economy service. */ -@SuppressWarnings("deprecation") -final class DuneEconomy implements Economy { - private final DuneEss plugin; - private final Map balances = new HashMap<>(); - private final File file; - private final YamlConfiguration data; - private final boolean allowNegative; - private final String singular, plural; - private String jdbcUrl = "", dbUser = "", dbPassword = ""; - private boolean databaseEnabled; - private boolean sharedDatabaseRequested; - - DuneEconomy(DuneEss plugin) { - this.plugin = plugin; - this.file = new File(plugin.getDataFolder(), "balances.yml"); - this.data = YamlConfiguration.loadConfiguration(file); - this.allowNegative = plugin.getConfig().getBoolean("currency.allow-negative-balances", true); - String configuredSingular = plugin.getConfig().getString("currency.singular", "Dunemark"); - this.singular = configuredSingular.equalsIgnoreCase("Solaris") ? "Dunemark" : configuredSingular; - String configuredPlural = plugin.getConfig().getString("currency.plural", "Dunemarks"); - this.plural = configuredPlural.equalsIgnoreCase("Solaris") ? "Dunemarks" : configuredPlural; - loadDatabaseSettings(); - loadBalances(); - } - - private void loadDatabaseSettings() { - if (!plugin.getConfig().getBoolean("database.use-core-database", true)) return; - File coreConfig = new File(plugin.getDataFolder().getParentFile(), "DuneCore/config.yml"); - if (!coreConfig.isFile()) return; - YamlConfiguration core = YamlConfiguration.loadConfiguration(coreConfig); - if (!core.getBoolean("database.enabled", false)) return; - sharedDatabaseRequested = true; - jdbcUrl = core.getString("database.jdbc-url", ""); - dbUser = core.getString("database.username", ""); - dbPassword = core.getString("database.password", ""); - databaseEnabled = !jdbcUrl.isBlank(); - } - - boolean sharedDatabaseReady() { return databaseEnabled; } - - private Connection connect() throws SQLException { - try { Class.forName("org.postgresql.Driver"); } - catch (ClassNotFoundException ex) { throw new SQLException("PostgreSQL driver unavailable", ex); } - java.util.Properties settings=new java.util.Properties(); - settings.setProperty("user",dbUser);settings.setProperty("password",dbPassword); - settings.setProperty("connectTimeout","5");settings.setProperty("socketTimeout","10"); - return DriverManager.getConnection(jdbcUrl,settings); - } - - private void loadBalances() { - try { file.getParentFile().mkdirs(); } catch (Exception ignored) { } - for (String key : data.getKeys(false)) { - try { balances.put(UUID.fromString(key), money(data.getDouble(key))); } - catch (IllegalArgumentException ignored) { } - } - importLegacyFile(); - if (databaseEnabled) { - try (Connection c = connect(); Statement s = c.createStatement()) { - s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_economy_balances (uuid UUID PRIMARY KEY, balance NUMERIC(20,2) NOT NULL DEFAULT 0)"); - boolean empty; - try (ResultSet rows = s.executeQuery("SELECT NOT EXISTS (SELECT 1 FROM dune_economy_balances)")) { - empty = rows.next() && rows.getBoolean(1); - } - if (empty) { - importLegacyDatabase(c); - importLocalBalances(c); - } - try (ResultSet rows = s.executeQuery("SELECT uuid,balance FROM dune_economy_balances")) { - while (rows.next()) balances.put(rows.getObject(1, UUID.class), money(rows.getDouble(2))); - } - } catch (SQLException ex) { - plugin.getLogger().severe("Shared Solaris database unavailable; network transactions remain disabled until it recovers: " + ex.getMessage()); - } - } - saveLocal(); - } - - private void importLegacyFile() { - if (!balances.isEmpty()) return; - File old = new File(plugin.getDataFolder().getParentFile(), "DuneCore/players.yml"); - if (!old.isFile()) old = new File(plugin.getDataFolder().getParentFile(), "DuneRealms/players.yml"); - if (!old.isFile()) return; - YamlConfiguration legacy = YamlConfiguration.loadConfiguration(old); - for (String key : legacy.getKeys(false)) try { - UUID id = UUID.fromString(key); - if (legacy.contains(key + ".solaris")) balances.put(id, money(legacy.getDouble(key + ".solaris"))); - } catch (IllegalArgumentException ignored) { } - if (!balances.isEmpty()) plugin.getLogger().info("Imported " + balances.size() + " Solaris balances from the previous Dune data file."); - } - - private void importLegacyDatabase(Connection c) { - try (Statement s = c.createStatement(); ResultSet rows = s.executeQuery("SELECT uuid,solaris FROM dune_players WHERE solaris<>0")) { - try (PreparedStatement insert = c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) { - while (rows.next()) { - insert.setObject(1, rows.getObject(1, UUID.class)); - insert.setBigDecimal(2, BigDecimal.valueOf(rows.getDouble(2))); - insert.addBatch(); - } - insert.executeBatch(); - } - plugin.getLogger().info("Imported legacy Solaris balances from the shared Dune player table."); - } catch (SQLException ignored) { - // Older installations may not have enabled the shared player database. - } - } - - private void importLocalBalances(Connection c) { - if (balances.isEmpty()) return; - try (PreparedStatement insert = c.prepareStatement( - "INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) { - for (Map.Entry entry : balances.entrySet()) { - insert.setObject(1, entry.getKey()); - insert.setBigDecimal(2, BigDecimal.valueOf(entry.getValue())); - insert.addBatch(); - } - insert.executeBatch(); - plugin.getLogger().info("Migrated local Solaris balances into the shared economy database."); - } catch (SQLException ex) { - plugin.getLogger().warning("Could not migrate local Solaris balances to PostgreSQL: " + ex.getMessage()); - } - } - - private static double money(double amount) { - if (!Double.isFinite(amount)) return 0; - return BigDecimal.valueOf(amount).setScale(2, RoundingMode.HALF_UP).doubleValue(); - } - - private synchronized void saveLocal() { - for (Map.Entry entry : balances.entrySet()) data.set(entry.getKey().toString(), entry.getValue()); - try { writeCommunitySnapshot(data); } - catch (Exception ex) { plugin.getLogger().severe("Could not save Solaris balances: " + ex.getMessage()); } - } - - private synchronized double balance(UUID id) { - if (databaseEnabled) { - try (Connection c = connect(); PreparedStatement q = c.prepareStatement("SELECT balance FROM dune_economy_balances WHERE uuid=?")) { - q.setObject(1, id); - try (ResultSet row = q.executeQuery()) { - if (row.next()) { - double value = money(row.getDouble(1)); - balances.put(id, value); - return value; - } - } - } catch (SQLException ex) { plugin.getLogger().warning("Solaris balance read failed: " + ex.getMessage()); } - return 0; // Never authorize a network payment against stale local cache. - } - return balances.getOrDefault(id, 0.0); - } - - private synchronized void set(UUID id, double value) { - value = money(value); - balances.put(id, value); - if (databaseEnabled) { - try (Connection c = connect(); PreparedStatement q = c.prepareStatement( - "INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO UPDATE SET balance=EXCLUDED.balance")) { - q.setObject(1, id); q.setBigDecimal(2, BigDecimal.valueOf(value)); q.executeUpdate(); - } catch (SQLException ex) { plugin.getLogger().severe("Solaris database save failed: " + ex.getMessage()); } - } - saveLocal(); - } - - synchronized void add(UUID id, double amount) { change(id, amount); } - synchronized void subtract(UUID id, double amount) { change(id, -amount); } - - private synchronized EconomyResponse change(UUID id, double delta) { - if (!Double.isFinite(delta)) return response(0, 0, EconomyResponse.ResponseType.FAILURE, "Invalid amount."); - if (sharedDatabaseRequested && !databaseEnabled) return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable."); - if (!databaseEnabled) { - double next=money(balance(id)+delta); - if (!allowNegative && next<0) return response(Math.abs(delta),balance(id),EconomyResponse.ResponseType.FAILURE,"Insufficient funds."); - set(id,next); return response(Math.abs(delta),next,EconomyResponse.ResponseType.SUCCESS,null); - } - try (Connection c=connect()) { - c.setAutoCommit(false); - try { - try (PreparedStatement create=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,0) ON CONFLICT(uuid) DO NOTHING")) { - create.setObject(1,id);create.executeUpdate(); - } - double updated; - try (PreparedStatement q=c.prepareStatement("UPDATE dune_economy_balances SET balance=balance+? WHERE uuid=? AND (? OR balance+?>=0) RETURNING balance")) { - BigDecimal amount=BigDecimal.valueOf(money(delta)); - q.setBigDecimal(1,amount);q.setObject(2,id);q.setBoolean(3,allowNegative);q.setBigDecimal(4,amount); - try (ResultSet row=q.executeQuery()) { - if (!row.next()) {c.rollback();return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Insufficient funds.");} - updated=row.getDouble(1); - } - } - c.commit();balances.put(id,updated);saveLocal(); - return response(Math.abs(delta),updated,EconomyResponse.ResponseType.SUCCESS,null); - } catch(SQLException ex) {c.rollback();throw ex;} - } catch(SQLException ex) { - plugin.getLogger().warning("Shared Solaris transaction failed: "+ex.getSQLState()); - return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable."); - } - } - - /** One durable credit per UUID/month. A failed shared ledger never falls back to a second ledger. */ - synchronized boolean grantCommunity(UUID id,String month,int amount,String receipt) throws Exception { - if(!month.matches("20\\d\\d-(0[1-9]|1[0-2])")||amount<1||amount>10000||!receipt.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("Invalid community grant"); - if(sharedDatabaseRequested&&!databaseEnabled)throw new IOException("Shared economy is unavailable"); - String key="community-claims."+id+"."+month; - if(databaseEnabled){ - try(Connection c=connect()){ - try(Statement s=c.createStatement()){s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))");} - c.setAutoCommit(false); - try{ - int inserted; - try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_community_claims(uuid,month,receipt,amount) VALUES(?,?,?,?) ON CONFLICT(uuid,month) DO NOTHING")){s.setObject(1,id);s.setString(2,month);s.setString(3,receipt);s.setInt(4,amount);inserted=s.executeUpdate();} - if(inserted==0){try(PreparedStatement s=c.prepareStatement("SELECT receipt,amount FROM dune_community_claims WHERE uuid=? AND month=?")){s.setObject(1,id);s.setString(2,month);try(ResultSet r=s.executeQuery()){if(!r.next()||!receipt.equals(r.getString(1))||amount!=r.getInt(2))throw new IOException("Community receipt mismatch");}}c.commit();return false;} - double updated; - try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES(?,?) ON CONFLICT(uuid) DO UPDATE SET balance=dune_economy_balances.balance+EXCLUDED.balance RETURNING balance")){s.setObject(1,id);s.setBigDecimal(2,BigDecimal.valueOf(amount));try(ResultSet r=s.executeQuery()){r.next();updated=r.getDouble(1);}} - c.commit();balances.put(id,money(updated));saveLocal();return true; - }catch(Exception error){c.rollback();throw error;} - } - } - if(data.contains(key+".receipt")){if(!receipt.equals(data.getString(key+".receipt"))||amount!=data.getInt(key+".amount"))throw new IOException("Community receipt mismatch");return false;} - YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString()); - double updated=money(balances.getOrDefault(id,0.0)+amount); - next.set(id.toString(),updated);next.set(key+".receipt",receipt);next.set(key+".amount",amount);next.set(key+".acked",false); - writeCommunitySnapshot(next);balances.put(id,updated);return true; - } - private void writeCommunitySnapshot(YamlConfiguration next) throws Exception { - java.nio.file.Path target=file.toPath(),temporary=target.resolveSibling("balances.yml.community-tmp"); - java.nio.file.Files.createDirectories(target.getParent()); - byte[] bytes=next.saveToString().getBytes(java.nio.charset.StandardCharsets.UTF_8); - try(java.nio.channels.FileChannel channel=java.nio.channels.FileChannel.open(temporary,java.nio.file.StandardOpenOption.CREATE,java.nio.file.StandardOpenOption.TRUNCATE_EXISTING,java.nio.file.StandardOpenOption.WRITE)){java.nio.ByteBuffer buffer=java.nio.ByteBuffer.wrap(bytes);while(buffer.hasRemaining())channel.write(buffer);channel.force(true);} - java.nio.file.Files.move(temporary,target,java.nio.file.StandardCopyOption.ATOMIC_MOVE,java.nio.file.StandardCopyOption.REPLACE_EXISTING); - data.loadFromString(next.saveToString()); - } - synchronized Map> pendingCommunityReceipts() throws Exception { - Map> pending=new HashMap<>(); - if(sharedDatabaseRequested&&!databaseEnabled)return pending; - if(databaseEnabled){try(Connection c=connect();Statement s=c.createStatement()){ - s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))"); - try(ResultSet r=s.executeQuery("SELECT uuid,receipt FROM dune_community_claims WHERE acked=FALSE LIMIT 100")){while(r.next())pending.computeIfAbsent(r.getObject(1,UUID.class),ignored->new ArrayList<>()).add(r.getString(2));} - }return pending;} - var section=data.getConfigurationSection("community-claims");if(section==null)return pending; - for(String uuid:section.getKeys(false)){var months=section.getConfigurationSection(uuid);if(months==null)continue;for(String month:months.getKeys(false)){String key=uuid+"."+month;if(!section.getBoolean(key+".acked"))pending.computeIfAbsent(UUID.fromString(uuid),ignored->new ArrayList<>()).add(section.getString(key+".receipt"));}} - return pending; - } - synchronized void acknowledgeCommunity(UUID id,String receipt) throws Exception { - if(databaseEnabled){try(Connection c=connect();PreparedStatement s=c.prepareStatement("UPDATE dune_community_claims SET acked=TRUE WHERE uuid=? AND receipt=?")){s.setObject(1,id);s.setString(2,receipt);s.executeUpdate();}return;} - YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString());var months=next.getConfigurationSection("community-claims."+id);if(months==null)return; - for(String month:months.getKeys(false))if(receipt.equals(months.getString(month+".receipt")))months.set(month+".acked",true); - writeCommunitySnapshot(next); - } - - private EconomyResponse response(double amount, double balance, EconomyResponse.ResponseType type, String message) { - return new EconomyResponse(amount, balance, type, message); - } - private EconomyResponse deposit(OfflinePlayer player, double amount) { - if (amount < 0 || !Double.isFinite(amount)) return response(amount, getBalance(player), EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative."); - return change(player.getUniqueId(), amount); - } - private EconomyResponse withdraw(OfflinePlayer player, double amount) { - double current = getBalance(player); - if (amount < 0 || !Double.isFinite(amount)) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative."); - if (!allowNegative && current < amount) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Insufficient funds."); - return change(player.getUniqueId(), -amount); - } - - @Override public boolean isEnabled() { return plugin.isEnabled(); } - @Override public String getName() { return "DuneEss"; } - @Override public boolean hasBankSupport() { return false; } - @Override public int fractionalDigits() { return 2; } - @Override public String format(double amount) { return String.format(java.util.Locale.US, "%,.2f %s", amount, Math.abs(amount) == 1 ? singular : plural); } - @Override public String currencyNamePlural() { return plural; } - @Override public String currencyNameSingular() { return singular; } - @Override public boolean hasAccount(String name) { return hasAccount(Bukkit.getOfflinePlayer(name)); } - @Override public boolean hasAccount(OfflinePlayer player) { return balances.containsKey(player.getUniqueId()) || player.hasPlayedBefore() || player.isOnline(); } - @Override public boolean hasAccount(String name, String world) { return hasAccount(name); } - @Override public boolean hasAccount(OfflinePlayer player, String world) { return hasAccount(player); } - @Override public double getBalance(String name) { return getBalance(Bukkit.getOfflinePlayer(name)); } - @Override public double getBalance(OfflinePlayer player) { return balance(player.getUniqueId()); } - @Override public double getBalance(String name, String world) { return getBalance(name); } - @Override public double getBalance(OfflinePlayer player, String world) { return getBalance(player); } - @Override public boolean has(String name, double amount) { return has(Bukkit.getOfflinePlayer(name), amount); } - @Override public boolean has(OfflinePlayer player, double amount) { return amount >= 0 && getBalance(player) >= amount; } - @Override public boolean has(String name, String world, double amount) { return has(name, amount); } - @Override public boolean has(OfflinePlayer player, String world, double amount) { return has(player, amount); } - @Override public EconomyResponse withdrawPlayer(String name, double amount) { return withdraw(Bukkit.getOfflinePlayer(name), amount); } - @Override public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { return withdraw(player, amount); } - @Override public EconomyResponse withdrawPlayer(String name, String world, double amount) { return withdrawPlayer(name, amount); } - @Override public EconomyResponse withdrawPlayer(OfflinePlayer player, String world, double amount) { return withdraw(player, amount); } - @Override public EconomyResponse depositPlayer(String name, double amount) { return deposit(Bukkit.getOfflinePlayer(name), amount); } - @Override public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { return deposit(player, amount); } - @Override public EconomyResponse depositPlayer(String name, String world, double amount) { return depositPlayer(name, amount); } - @Override public EconomyResponse depositPlayer(OfflinePlayer player, String world, double amount) { return deposit(player, amount); } - @Override public EconomyResponse createBank(String name, String player) { return unsupported(); } - @Override public EconomyResponse createBank(String name, OfflinePlayer player) { return unsupported(); } - @Override public EconomyResponse deleteBank(String name) { return unsupported(); } - @Override public EconomyResponse bankBalance(String name) { return unsupported(); } - @Override public EconomyResponse bankHas(String name, double amount) { return unsupported(); } - @Override public EconomyResponse bankWithdraw(String name, double amount) { return unsupported(); } - @Override public EconomyResponse bankDeposit(String name, double amount) { return unsupported(); } - @Override public EconomyResponse isBankOwner(String name, String player) { return unsupported(); } - @Override public EconomyResponse isBankOwner(String name, OfflinePlayer player) { return unsupported(); } - @Override public EconomyResponse isBankMember(String name, String player) { return unsupported(); } - @Override public EconomyResponse isBankMember(String name, OfflinePlayer player) { return unsupported(); } - @Override public List getBanks() { return new ArrayList<>(); } - @Override public boolean createPlayerAccount(String name) { return createPlayerAccount(Bukkit.getOfflinePlayer(name)); } - @Override public boolean createPlayerAccount(OfflinePlayer player) { - UUID id = player.getUniqueId(); - if (databaseEnabled) { - try (Connection c=connect();PreparedStatement q=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) { - q.setObject(1,id);q.setBigDecimal(2,BigDecimal.valueOf(money(plugin.getConfig().getDouble("currency.starting-balance",0))));q.executeUpdate();return true; - } catch(SQLException ex) {return false;} - } - if (!balances.containsKey(id)) set(id, money(plugin.getConfig().getDouble("currency.starting-balance", 0))); - return true; - } - @Override public boolean createPlayerAccount(String name, String world) { return createPlayerAccount(name); } - @Override public boolean createPlayerAccount(OfflinePlayer player, String world) { return createPlayerAccount(player); } - private EconomyResponse unsupported() { return response(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "DuneEss does not provide bank accounts."); } -} diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEss.java b/DuneEss/src/main/java/com/example/duneess/DuneEss.java deleted file mode 100644 index ac743255..00000000 --- a/DuneEss/src/main/java/com/example/duneess/DuneEss.java +++ /dev/null @@ -1,599 +0,0 @@ -package com.example.duneess; - -import net.milkbowl.vault.economy.Economy; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataType; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.ServicePriority; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.lang.reflect.Method; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.util.*; - -public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCompleter, Listener { - private static final List PLANETS = List.of("arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv", "spacing_guild"); - private DuneEconomy economy; - String balanceLabel(Player player) { return economy.format(economy.getBalance(player)); } - private ExchangeMenu exchangeMenu; - private EssentialsBasics basics; - private String jdbcUrl = "", dbUser = "", dbPassword = ""; - private boolean networkEnabled; - private String localPlanet; - private NamespacedKey spiceKey; - private NamespacedKey helpPageKey, helpActionKey; - private final Map helpPageByPlayer = new HashMap<>(); - private static final String HELP_TITLE = ChatColor.DARK_RED + "Dune Field Guide"; - private static final List> HELP_PAGES = List.of( - List.of( - new HelpEntry("/duneess balance", "Check your Dunemarks wallet.", Material.GOLD_INGOT), - new HelpEntry("/duneess sell", "Sell all tagged spice in your inventory.", Material.ORANGE_DYE), - new HelpEntry("/duneess travel", "Open the Vaerkring planet selector.", Material.ENDER_PEARL), - new HelpEntry("/duneess travel arrakis", "Pay the fare and travel to Arrakis.", Material.MAP), - new HelpEntry("/dune", "Open the Dune Navigator menu.", Material.NETHER_STAR) - ), - List.of( - new HelpEntry("/dune choose fremen", "Choose Vrijduin; replace 'fremen' with another house to choose it.", Material.WHITE_BANNER), - new HelpEntry("/dune kit", "Receive your faction stillsuit and spice shovel.", Material.NETHERITE_SHOVEL), - new HelpEntry("/dune elytra", "Upgrade a worn stillsuit chestplate with an Elytra.", Material.ELYTRA), - new HelpEntry("/dune politics status", "View the Vaerkring Trust, leaders, and Landsraad appointments.", Material.WRITABLE_BOOK), - new HelpEntry("/dune water status", "View your Arrakis water-trading career.", Material.WATER_BUCKET) - ), - List.of( - new HelpEntry("/dune serverjobs", "Browse hourly Koopkring spice contracts.", Material.EMERALD), - new HelpEntry("/dune job", "Browse player-posted spice contracts.", Material.BOOK), - new HelpEntry("/dune job post 100", "Post a 100-spice contract; change the amount to suit your listing.", Material.PAPER), - new HelpEntry("/dune water sell", "Sell water collected on Arrakis.", Material.BUCKET), - new HelpEntry("/dune exchange", "Open the spice exchange menu.", Material.CHEST) - ), - List.of( - new HelpEntry("/duneess admin solari player amount", "Grant Dunemarks to an online player.", Material.GOLD_INGOT), - new HelpEntry("/duneess admin teleport arrakis", "Force yourself to Arrakis spawn.", Material.COMPASS), - new HelpEntry("/duneess admin teleport sietch", "Teleport yourself to a generated sietch.", Material.CHEST), - new HelpEntry("/duneess admin teleport spiceblow", "Teleport yourself to a generated spice blow.", Material.MAGMA_BLOCK), - new HelpEntry("/duneess admin spicebloom", "Place an untriggered bloom about 50 blocks ahead of you.", Material.GLOWSTONE), - new HelpEntry("/dune summon sandworm", "Admin: summon on Arrakis; optionally supply x y z.", Material.HUSK_SPAWN_EGG), - new HelpEntry("/dune guireload", "Reload DuneCore's configurable Navigator menu.", Material.COMPARATOR) - ) - ); - private record HelpEntry(String command, String description, Material icon) {} - - @Override public void onEnable() { - saveDefaultConfig(); - loadCoreSettings(); - spiceKey = new NamespacedKey("dunerealms", "item"); - helpPageKey = new NamespacedKey(this, "help_page"); - helpActionKey = new NamespacedKey(this, "help_action"); - economy = new DuneEconomy(this); - new CommunityCodes(this); - getServer().getServicesManager().register(Economy.class, economy, this, ServicePriority.Highest); - getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - PluginCommand command = Objects.requireNonNull(getCommand("duneess")); - command.setExecutor(this); - command.setTabCompleter(this); - getServer().getPluginManager().registerEvents(this, this); - basics=new EssentialsBasics(this); - basics.register(); - StaffItemTools.start(this); - exchangeMenu = new ExchangeMenu(this); - exchangeMenu.register(); - DuneCommands.register(this); - for (Player player : Bukkit.getOnlinePlayers()) economy.createPlayerAccount(player); - getLogger().info("DuneRealms Essentials enabled as the Dunemarks Vault provider."); - } - - @Override public void onDisable() { - getServer().getServicesManager().unregister(Economy.class, economy); - } - - public Economy economy() { return economy; } - - /** Free faction selection arrival, routed through DuneEss so Core owns no player-facing teleport command logic. */ - public void factionArrival(Player player, String planet) { - planet = planet.toLowerCase(Locale.ROOT); - if (!PLANETS.contains(planet)) return; - if (planet.equals("arrakis") && !callCoreArrakisAuthorization(player)) { - player.sendMessage(ChatColor.RED + "Arrakis travel was not authorized."); - return; - } - if (networkEnabled && !planet.equalsIgnoreCase(localPlanet)) { - String server = getConfig().getString("network.servers." + planet, ""); - if (server.isBlank()) server = YamlConfiguration.loadConfiguration( - new File(getDataFolder().getParentFile(), "DuneCore/config.yml")).getString("network.servers." + planet, ""); - if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; } - sendToServer(player, server, planet); - return; - } - World world = Bukkit.getWorld(planet); - if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; } - if (player.teleport(world.getSpawnLocation())) { - player.sendMessage(ChatColor.AQUA + "Faction arrival: " + planet); - if (planet.equals("arrakis")) callCoreArrakisArrival(player); - } - } - - private void loadCoreSettings() { - File coreFile = new File(getDataFolder().getParentFile(), "DuneCore/config.yml"); - YamlConfiguration core = YamlConfiguration.loadConfiguration(coreFile); - if (getConfig().getBoolean("database.use-core-database", true) && core.getBoolean("database.enabled", false)) { - jdbcUrl = core.getString("database.jdbc-url", ""); - dbUser = core.getString("database.username", ""); - dbPassword = core.getString("database.password", ""); - } - boolean useCore = getConfig().getBoolean("network.use-core-settings", true); - networkEnabled = useCore ? core.getBoolean("network.enabled", getConfig().getBoolean("network.enabled", false)) : getConfig().getBoolean("network.enabled", false); - localPlanet = useCore ? core.getString("network.local-planet", getConfig().getString("network.local-planet", "arrakis")) : getConfig().getString("network.local-planet", "arrakis"); - } - - String localPlanet() { return localPlanet; } - - Connection connectEconomyDatabase() throws java.sql.SQLException { - if (jdbcUrl.isBlank() || !economy.sharedDatabaseReady()) - throw new java.sql.SQLException("No shared economy database configured"); - Properties properties = new Properties(); - properties.setProperty("user", dbUser); - properties.setProperty("password", dbPassword); - properties.setProperty("connectTimeout", "5"); - properties.setProperty("socketTimeout", "5"); - return DriverManager.getConnection(jdbcUrl, properties); - } - - @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if(args.length==0 && sender instanceof Player player) { basics.menu(player); return true; } - if (args.length == 0 || args[0].equalsIgnoreCase("help")) { - int page = 1; - if (args.length > 1 && args[1].equalsIgnoreCase("menu")) { - if (sender instanceof Player player) openHelpMenu(player, 1); - else sender.sendMessage("The visual guide is available in-game: /duneess help menu"); - return true; - } - if (args.length > 1) { - if (args[1].equalsIgnoreCase("next")) page = (sender instanceof Player p ? helpPageByPlayer.getOrDefault(p.getUniqueId(), 1) : 1) + 1; - else if (args[1].equalsIgnoreCase("previous") || args[1].equalsIgnoreCase("prev")) page = (sender instanceof Player p ? helpPageByPlayer.getOrDefault(p.getUniqueId(), 1) : 1) - 1; - else try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { } - } - if (sender instanceof Player player) sendHelpPage(player, page); - else help(sender, page); - return true; - } - String root = args[0].toLowerCase(Locale.ROOT); - if (root.equals("balance")) { - Player target = args.length > 1 && sender.hasPermission("dune.admin") ? Bukkit.getPlayerExact(args[1]) : sender instanceof Player p ? p : null; - if (target == null) { sender.sendMessage("Usage: /duneess balance [online player]"); return true; } - sender.sendMessage(ChatColor.GOLD + target.getName() + " has " + economy.format(economy.getBalance(target)) + "."); - return true; - } - if (root.equals("sell")) { if (sender instanceof Player player) sellSpice(player); else sender.sendMessage("Run this command in-game."); return true; } - if (root.equals("travel")) { - if (!(sender instanceof Player player)) { sender.sendMessage("Run this command in-game."); return true; } - if (args.length == 1) { openTravelMenu(player); return true; } - travel(player, args[1]); return true; - } - if (root.equals("admin")) return admin(sender, args); - sender.sendMessage(ChatColor.YELLOW + "Use /duneess help."); - return true; - } - - private void help(CommandSender sender, int page) { - int index = Math.max(0, Math.min(HELP_PAGES.size() - 1, page - 1)); - sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+"); - sendBoxLine(sender, ChatColor.GOLD + "DUNE FIELD GUIDE" + ChatColor.GRAY + " PAGE " + (index + 1) + " OF " + HELP_PAGES.size()); - sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+"); - for (HelpEntry entry : HELP_PAGES.get(index)) { - sendBoxLine(sender, ChatColor.YELLOW + entry.command()); - for (String descriptionLine : wrap(entry.description(), 50)) - sendBoxLine(sender, ChatColor.GRAY + " " + descriptionLine); - sendBoxLine(sender, " "); - } - sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+"); - sendBoxLine(sender, ChatColor.GRAY + "Use /duneess help menu for the visual guide."); - sendBoxLine(sender, ChatColor.GRAY + "DuneEss: Dunemarks and Vaerkring travel"); - sendBoxLine(sender, ChatColor.GRAY + "DuneCore: factions and Arrakis"); - sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+"); - if (sender instanceof Player player) { - helpPageByPlayer.put(player.getUniqueId(), index + 1); - TextComponent nav = new TextComponent("§8[ " + (index == 0 ? "§8Previous Page" : "§ePrevious Page") + " §8] "); - if (index > 0) nav.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/duneess help previous")); - TextComponent next = new TextComponent("§8[ " + (index == HELP_PAGES.size() - 1 ? "§8Next Page" : "§eNext Page") + " §8]"); - if (index < HELP_PAGES.size() - 1) next.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/duneess help next")); - TextComponent pages = new TextComponent("§7 (page " + (index + 1) + "/" + HELP_PAGES.size() + ")"); - player.spigot().sendMessage(nav, next, pages); - } else { - sender.sendMessage(ChatColor.GRAY + "Page " + (index + 1) + " of " + HELP_PAGES.size() + " - /duneess help previous or next"); - } - } - - private void sendHelpPage(Player player, int page) { - int boundedPage = Math.max(1, Math.min(HELP_PAGES.size(), page)); - help(player, boundedPage); - } - - private void sendBoxLine(CommandSender sender, String text) { - String plain = ChatColor.stripColor(text); - if (plain.length() > 56) plain = plain.substring(0, 53) + "..."; - String padding = " ".repeat(Math.max(0, 56 - plain.length())); - sender.sendMessage(ChatColor.DARK_RED + "| " + text + padding + " " + ChatColor.DARK_RED + "|"); - } - - private List wrap(String text, int width) { - List lines = new ArrayList<>(); - StringBuilder line = new StringBuilder(); - for (String word : text.split("\\s+")) { - if (line.length() > 0 && line.length() + 1 + word.length() > width) { - lines.add(line.toString()); - line.setLength(0); - } - if (line.length() > 0) line.append(' '); - line.append(word); - } - if (line.length() > 0) lines.add(line.toString()); - return lines; - } - - private void openHelpMenu(Player player, int page) { - int index = Math.max(0, Math.min(HELP_PAGES.size() - 1, page - 1)); - Inventory menu = Bukkit.createInventory(null, 54, HELP_TITLE + ChatColor.DARK_GRAY + " Page " + (index + 1) + " of " + HELP_PAGES.size()); - ItemStack frame = helpItem(Material.BLACK_STAINED_GLASS_PANE, ChatColor.DARK_GRAY + " ", null); - for (int slot = 0; slot < 9; slot++) { menu.setItem(slot, frame); menu.setItem(45 + slot, frame); } - for (int row = 1; row <= 4; row++) { menu.setItem(row * 9, frame); menu.setItem(row * 9 + 8, frame); } - ItemStack heading = helpItem(Material.WRITABLE_BOOK, ChatColor.GOLD + "Dune Field Guide", - List.of(ChatColor.GRAY + "Page " + (index + 1) + " of " + HELP_PAGES.size(), ChatColor.DARK_GRAY + "Click a command to run it.")); - menu.setItem(4, heading); - int[] slots = {10, 12, 14, 16, 28, 30, 32}; - int n = 0; - for (HelpEntry entry : HELP_PAGES.get(index)) { - ItemStack item = helpItem(entry.icon(), ChatColor.YELLOW + entry.command(), - List.of(ChatColor.GRAY + entry.description(), ChatColor.GREEN + "Click to run")); - ItemMeta itemMeta = item.getItemMeta(); - if (!entry.command().endsWith(" player amount") && !entry.command().contains("[")) - itemMeta.getPersistentDataContainer().set(helpActionKey, PersistentDataType.STRING, entry.command()); - item.setItemMeta(itemMeta); - menu.setItem(slots[n++], item); - } - ItemStack previous = helpItem(index == 0 ? Material.GRAY_STAINED_GLASS_PANE : Material.BOOK, - ChatColor.YELLOW + "Previous page", List.of(ChatColor.GRAY + (index == 0 ? "You are on the first page." : "Go to page " + index))); - ItemMeta previousMeta = previous.getItemMeta(); - previousMeta.getPersistentDataContainer().set(helpPageKey, PersistentDataType.INTEGER, index); - previous.setItemMeta(previousMeta); - menu.setItem(45, previous); - menu.setItem(49, helpItem(Material.BARRIER, ChatColor.RED + "Close", List.of(ChatColor.GRAY + "Close this guide."))); - ItemStack next = helpItem(index == HELP_PAGES.size() - 1 ? Material.GRAY_STAINED_GLASS_PANE : Material.WRITABLE_BOOK, - ChatColor.YELLOW + "Next page", List.of(ChatColor.GRAY + (index == HELP_PAGES.size() - 1 ? "You are on the last page." : "Go to page " + (index + 2)))); - ItemMeta nextMeta = next.getItemMeta(); - nextMeta.getPersistentDataContainer().set(helpPageKey, PersistentDataType.INTEGER, index + 2); - next.setItemMeta(nextMeta); - menu.setItem(53, next); - java.util.Map actions=new java.util.HashMap<>(); - actions.put(45,()->openHelpMenu(player,index)); - actions.put(53,()->openHelpMenu(player,index+2)); - actions.put(49,player::closeInventory); - for(int slot:slots) { - ItemStack entry=menu.getItem(slot); - if(entry==null) continue; - String command=entry.getItemMeta().getPersistentDataContainer().get(helpActionKey,PersistentDataType.STRING); - if(command!=null) actions.put(slot,()->player.performCommand(command.substring(1))); - } - com.example.dunegui.NativeMenus.inventory(this,player,"Dune Field Guide · "+(index+1),menu,actions); - } - - private ItemStack helpItem(Material material, String name, List lore) { - ItemStack item = new ItemStack(material); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(name); - if (lore != null) meta.setLore(lore); - item.setItemMeta(meta); - return item; - } - - @EventHandler public void onHelpMenuClick(InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().startsWith(HELP_TITLE)) return; - event.setCancelled(true); - ItemStack clicked = event.getCurrentItem(); - if (clicked == null || !clicked.hasItemMeta()) return; - ItemMeta meta = clicked.getItemMeta(); - Integer page = meta.getPersistentDataContainer().get(helpPageKey, PersistentDataType.INTEGER); - if (page != null) { openHelpMenu(player, page); return; } - if (clicked.getType() == Material.BARRIER) { player.closeInventory(); return; } - String action = meta.getPersistentDataContainer().get(helpActionKey, PersistentDataType.STRING); - if (action != null) { player.closeInventory(); player.performCommand(action.substring(1)); } - } - - @EventHandler public void onHelpMenuDrag(org.bukkit.event.inventory.InventoryDragEvent event) { - if (event.getView().getTitle().startsWith(HELP_TITLE)) event.setCancelled(true); - } - - @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { - economy.createPlayerAccount(event.getPlayer()); - } - - @EventHandler(ignoreCancelled=true) - public void spiceSeller(org.bukkit.event.player.PlayerInteractEntityEvent event) { - if(!event.getRightClicked().getPersistentDataContainer().has(new NamespacedKey("dunerealms","spice-seller"),PersistentDataType.BYTE))return; - event.setCancelled(true); - if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return; - Player player=event.getPlayer(); - Inventory menu=Bukkit.createInventory(null,9,"Spice Seller"); - int quantity=16; - double price=java.math.BigDecimal.valueOf(Math.max(1,getConfig().getInt("currency.spice-price",15))) - .multiply(new java.math.BigDecimal("1.35")).multiply(java.math.BigDecimal.valueOf(quantity)).doubleValue(); - ItemStack offer=new ItemStack(Material.ORANGE_DYE,quantity); ItemMeta meta=offer.getItemMeta(); - meta.setDisplayName("Buy 16 spice · "+economy.format(price)); - meta.setLore(List.of("35% above standard spice price", "Confirm purchase"));offer.setItemMeta(meta);menu.setItem(4,offer); - Map actions=new HashMap<>(); - actions.put(4,()->{ - // Recheck proximity and capacity at confirmation; never charge for undeliverable goods. - if(!event.getRightClicked().isValid() || !player.getWorld().equals(event.getRightClicked().getWorld()) - || player.getLocation().distanceSquared(event.getRightClicked().getLocation())>64)return; - ItemStack spice=new ItemStack(Material.ORANGE_DYE,quantity);ItemMeta sm=spice.getItemMeta(); - sm.setDisplayName(ChatColor.GOLD+"Melange Spice");sm.getPersistentDataContainer().set(spiceKey,PersistentDataType.STRING,"spice");spice.setItemMeta(sm); - if(player.getInventory().firstEmpty()<0){player.sendMessage("Make an empty inventory slot first.");return;} - if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Dunemarks, or economy unavailable.");return;} - player.getInventory().addItem(spice);player.sendMessage(ChatColor.GOLD+"Bought 16 spice for "+economy.format(price)+"."); - }); - com.example.dunegui.NativeMenus.inventory(this,player,"Spice Seller · +35%",menu,actions); - } - - private void sellSpice(Player player) { - int amount = 0; - for (ItemStack item : player.getInventory().getStorageContents()) { - if (isSpice(item)) { amount += item.getAmount(); item.setAmount(0); } - } - if (amount == 0) { player.sendMessage(ChatColor.RED + "You have no tagged spice to sell."); return; } - int price = Math.max(1, getConfig().getInt("currency.spice-price", 15)); - int gross = Math.multiplyExact(amount, price); - int net = callCoreSaleAdjustment(player, gross); - economy.depositPlayer(player, net); - player.sendMessage(ChatColor.GOLD + "Sold " + amount + " spice for " + economy.format(net) + "."); - } - - private boolean isSpice(ItemStack item) { - return item != null && item.hasItemMeta() - && "spice".equals(item.getItemMeta().getPersistentDataContainer().get(spiceKey, PersistentDataType.STRING)); - } - - private int callCoreSaleAdjustment(Player player, int gross) { - Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore"); - if (core == null || !core.isEnabled()) return gross; - try { - Method method = core.getClass().getMethod("processSpiceSale", Player.class, int.class); - Object value = method.invoke(core, player, gross); - if (value instanceof Number n) return Math.max(0, n.intValue()); - } catch (ReflectiveOperationException ex) { getLogger().warning("Could not apply DuneCore spice trade rules: " + ex.getMessage()); } - return gross; - } - - private void openTravelMenu(Player player) { - Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Vaerkring Travel"); - for (int i = 0; i < PLANETS.size(); i++) { - String planet = PLANETS.get(i); - ItemStack item = new ItemStack(Material.ENDER_PEARL); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(ChatColor.GOLD + com.example.dunegui.PlanetSigils.label(planet) + " — " + getConfig().getInt("currency.travel-price", 100) + " Dunemarks"); - meta.getPersistentDataContainer().set(new NamespacedKey(this, "planet"), PersistentDataType.STRING, planet); - item.setItemMeta(meta); - inventory.setItem(i, com.example.dunegui.PlanetSigils.apply(item,planet)); - } - java.util.Map actions=new java.util.HashMap<>(); - for(int i=0;itravel(player,planet)); } - com.example.dunegui.NativeMenus.inventory(this,player,"Vaerkring Travel",inventory,actions); - } - - @EventHandler public void onTravelMenuClick(InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Vaerkring Travel")) return; - event.setCancelled(true); - ItemStack item = event.getCurrentItem(); - if (item == null || !item.hasItemMeta()) return; - String planet = item.getItemMeta().getPersistentDataContainer().get(new NamespacedKey(this, "planet"), PersistentDataType.STRING); - if (planet == null) return; - player.closeInventory(); - travel(player, planet); - } - - private void travel(Player player, String planet) { - planet = planet.toLowerCase(Locale.ROOT); - if (!PLANETS.contains(planet)) { player.sendMessage(ChatColor.RED + "Unknown planet."); return; } - if (planet.equals("arrakis") && !callCoreArrakisAuthorization(player)) { player.sendMessage(ChatColor.RED + "Arrakis travel was not authorized."); return; } - if (networkEnabled && !planet.equalsIgnoreCase(localPlanet)) { - String server = getConfig().getString("network.servers." + planet, ""); - if (server.isBlank()) { - YamlConfiguration core = YamlConfiguration.loadConfiguration(new File(getDataFolder().getParentFile(), "DuneCore/config.yml")); - server = core.getString("network.servers." + planet, ""); - } - if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; } - int fare = travelFare(player, planet); - if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; } - if (fare > 0) economy.withdrawPlayer(player, fare); - if (!sendToServer(player, server, planet) && fare > 0) economy.depositPlayer(player, fare); - return; - } - World world = Bukkit.getWorld(planet); - if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; } - int fare = travelFare(player, planet); - if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; } - if (fare > 0) economy.withdrawPlayer(player, fare); - if (!player.teleport(world.getSpawnLocation())) { - if (fare > 0) economy.depositPlayer(player, fare); - player.sendMessage(ChatColor.RED + "Vaerkring travel failed. Your fare was returned."); - } else { - player.sendMessage(ChatColor.AQUA + "Vaerkring arrival: " + planet); - if (planet.equals("arrakis")) callCoreArrakisArrival(player); - } - } - - private boolean sendToServer(Player player, String server, String planet) { - try { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStream data = new DataOutputStream(bytes); - data.writeUTF("Connect"); data.writeUTF(server); - player.sendPluginMessage(this, "BungeeCord", bytes.toByteArray()); - player.sendMessage(ChatColor.AQUA + "Vaerkring transfer requested: " + planet); - return true; - } catch (Exception ex) { - player.sendMessage(ChatColor.RED + "Guild transfer failed. Your fare was returned."); - return false; - } - } - - private boolean callCoreArrakisAuthorization(Player player) { - Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore"); - if (core == null || !core.isEnabled()) return true; - try { - Method method = core.getClass().getMethod("authorizeArrakisTravel", Player.class); - return Boolean.TRUE.equals(method.invoke(core, player)); - } catch (ReflectiveOperationException ex) { getLogger().warning("Could not authorize Arrakis travel with DuneCore: " + ex.getMessage()); return false; } - } - - private void callCoreArrakisArrival(Player player) { - Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore"); - if (core == null || !core.isEnabled()) return; - try { core.getClass().getMethod("enforceArrakisArrival", Player.class).invoke(core, player); } - catch (ReflectiveOperationException ex) { getLogger().warning("Could not enforce Arrakis arrival rules: " + ex.getMessage()); } - } - - private int travelFare(Player player, String planet) { - if (planet.equals("arrakis")) { - Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore"); - if (core != null && core.isEnabled()) try { - Method method = core.getClass().getMethod("hasFreeArrakisTravel", Player.class); - if (Boolean.TRUE.equals(method.invoke(core, player))) return 0; - } catch (ReflectiveOperationException ex) { getLogger().warning("Could not check Arrakis travel rights: " + ex.getMessage()); } - } - return Math.max(0, getConfig().getInt("currency.travel-price", 100)); - } - - private boolean admin(CommandSender sender, String[] args) { - if (!sender.hasPermission("dune.admin")) { sender.sendMessage(ChatColor.RED + "Admin only."); return true; } - if (args.length < 2) { sender.sendMessage("Usage: /duneess admin ..."); return true; } - if (args[1].equalsIgnoreCase("solari")) { - if (args.length != 4) { sender.sendMessage("Usage: /duneess admin solari "); return true; } - Player target = Bukkit.getPlayerExact(args[2]); - if (target == null) { sender.sendMessage(ChatColor.RED + "That player must be online."); return true; } - try { - double amount = Double.parseDouble(args[3]); - if (amount <= 0 || !Double.isFinite(amount)) throw new NumberFormatException(); - economy.depositPlayer(target, amount); - sender.sendMessage(ChatColor.GREEN + "Added " + economy.format(amount) + " to " + target.getName() + "."); - target.sendMessage(ChatColor.GOLD + "An admin added " + economy.format(amount) + " to your balance."); - } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Dunemarks amount."); } - return true; - } - if (args[1].equalsIgnoreCase("spicebloom")) { - Player bloomTarget = args.length > 2 ? Bukkit.getPlayerExact(args[2]) : sender instanceof Player p ? p : null; - if (bloomTarget == null) { sender.sendMessage("Usage: /duneess admin spicebloom [online player]"); return true; } - World arrakisWorld = Bukkit.getWorld("arrakis"); - if (arrakisWorld == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; } - spawnSpiceBloom(sender, bloomTarget, arrakisWorld); - return true; - } - if (!args[1].equalsIgnoreCase("teleport")) { sender.sendMessage("Usage: /duneess admin teleport [player]"); return true; } - if (args.length < 3) { sender.sendMessage("Usage: /duneess admin teleport [player]"); return true; } - Player target = args.length > 3 ? Bukkit.getPlayerExact(args[3]) : sender instanceof Player p ? p : null; - if (target == null) { sender.sendMessage(ChatColor.RED + "Specify an online player from console."); return true; } - World arrakis = Bukkit.getWorld("arrakis"); - if (arrakis == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; } - switch (args[2].toLowerCase(Locale.ROOT)) { - case "arrakis" -> finishTeleport(sender, target, arrakis.getSpawnLocation(), "Arrakis spawn"); - case "sietch" -> teleportToSietch(sender, target, arrakis); - case "spiceblow" -> teleportToSpiceBlow(sender, target, arrakis); - default -> sender.sendMessage("Usage: /duneess admin teleport [player]"); - } - return true; - } - - private void finishTeleport(CommandSender sender, Player target, Location location, String label) { - if (target.teleport(location)) { target.sendMessage(ChatColor.AQUA + "An admin sent you to " + label + "."); sender.sendMessage(ChatColor.GREEN + "Teleported " + target.getName() + " to " + label + "."); } - else sender.sendMessage(ChatColor.RED + "Teleport failed."); - } - - private void teleportToSietch(CommandSender sender, Player target, World world) { - Location origin = target.getWorld().equals(world) ? target.getLocation() : world.getSpawnLocation(); - for (long[] c : candidates(origin, 0x534945544348L)) { - int x=(int)c[0], z=(int)c[1]; - world.getChunkAt(x >> 4, z >> 4).load(true); - int chestX=x, chestZ=z-10, estimate=world.getHighestBlockYAt(x+12,z+12); - for (int y=Math.max(world.getMinHeight()+1,estimate-80); y<=Math.min(world.getMaxHeight()-1,estimate+5); y++) { - Block b=world.getBlockAt(chestX,y,chestZ); - if (b.getType()==Material.CHEST && b.getState() instanceof org.bukkit.block.Chest chest && "Personal Sietch Cache".equals(chest.getCustomName())) { - finishTeleport(sender,target,new Location(world,x+.5,y+14,z+.5),"a sietch"); return; - } - } - } - sender.sendMessage(ChatColor.RED+"No generated sietch was found nearby. Explore new Arrakis terrain, then retry."); - } - - private void teleportToSpiceBlow(CommandSender sender, Player target, World world) { - for (long[] c : candidates(target.getWorld().equals(world)?target.getLocation():world.getSpawnLocation(),0x5350494345424c4fL)) { - int x=(int)c[0],z=(int)c[1]; world.getChunkAt(x>>4,z>>4).load(true); - int top=world.getHighestBlockYAt(x,z); Material marker=world.getBlockAt(x,top,z).getType(); - if(marker==Material.MAGMA_BLOCK||marker==Material.GLOWSTONE) { - int sx=x+4,sz=z+4; finishTeleport(sender,target,new Location(world,sx+.5,world.getHighestBlockYAt(sx,sz)+1,sz+.5),"a spice blow"); return; - } - } - sender.sendMessage(ChatColor.RED+"No spice blow was found nearby. Explore new Arrakis terrain, then retry."); - } - - private List candidates(Location origin,long salt) { - int spacing=2000; long gx0=Math.floorDiv(origin.getBlockX(),spacing),gz0=Math.floorDiv(origin.getBlockZ(),spacing); - List points=new ArrayList<>(); - for(long gx=gx0-2;gx<=gx0+2;gx++)for(long gz=gz0-2;gz<=gz0+2;gz++){ - long h1=mix64(gx*0x9E3779B97F4A7C15L^gz*0xC2B2AE3D27D4EB4FL^salt); - long h2=mix64(gz*0x165667B19E3779F9L^gx*0x85EBCA77C2B2AE63L^~salt); - long x=gx*spacing+8+Math.floorMod(h1,spacing-16),z=gz*spacing+8+Math.floorMod(h2,spacing-16); - long dx=x-origin.getBlockX(),dz=z-origin.getBlockZ();points.add(new long[]{x,z,dx*dx+dz*dz}); - } - points.sort(Comparator.comparingLong(point->point[2]));return points; - } - private static long mix64(long value){value=(value^(value>>>30))*0xBF58476D1CE4E5B9L;value=(value^(value>>>27))*0x94D049BB133111EBL;return value^(value>>>31);} - - private void spawnSpiceBloom(CommandSender sender, Player target, World world) { - if(!target.getWorld().equals(world)){sender.sendMessage(ChatColor.RED+"The target must be on Arrakis.");return;} - double base=Math.toRadians(90.0-target.getLocation().getYaw()); Block center=null; - for(int offset=-12;offset<=12;offset++){ - double angle=base+Math.toRadians(offset*15.0);int x=target.getLocation().getBlockX()+(int)Math.round(Math.cos(angle)*50),z=target.getLocation().getBlockZ()+(int)Math.round(Math.sin(angle)*50),y=world.getHighestBlockYAt(x,z);boolean ok=true; - for(int dx=-1;dx<=1&&ok;dx++)for(int dz=-1;dz<=1;dz++){Block b=world.getBlockAt(x+dx,y,z+dz);if((b.getType()!=Material.SAND&&b.getType()!=Material.RED_SAND)||!world.getBlockAt(x+dx,y+1,z+dz).isPassable()){ok=false;break;}} - if(ok&&world.getBlockAt(x,y+2,z).isPassable()){center=world.getBlockAt(x,y,z);break;} - } - if(center==null){sender.sendMessage(ChatColor.RED+"No clear sand patch was found 50 blocks ahead.");return;} - int x=center.getX(),y=center.getY(),z=center.getZ();for(int dx=-1;dx<=1;dx++)for(int dz=-1;dz<=1;dz++)world.getBlockAt(x+dx,y,z+dz).setType(Material.MAGMA_BLOCK,false);world.getBlockAt(x,y+1,z).setType(Material.MAGMA_BLOCK,false); - org.bukkit.plugin.Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore"); - if (core != null && core.isEnabled()) try { - Location bloom = new Location(world, x, y + 1, z); - core.getClass().getMethod("announceArrakisEvent", String.class, Location.class, String.class) - .invoke(core, "spicebloom", bloom, "bloom:" + world.getUID() + ":" + x + ":" + (y + 1) + ":" + z); - } catch (ReflectiveOperationException ex) { getLogger().warning("Spice bloom announcement failed: " + ex.getMessage()); } - sender.sendMessage(ChatColor.GREEN+"Placed a spice bloom near "+x+", "+z+".");target.sendMessage(ChatColor.GOLD+"A spice bloom appeared about 50 blocks ahead."); - } - - @Override public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { - if(args.length==1)return complete(List.of("help","balance","sell","travel","admin"),args[0]); - if(args[0].equalsIgnoreCase("help")&&args.length==2)return complete(List.of("1","2","3","4","next","previous","menu"),args[1]); - if(args[0].equalsIgnoreCase("travel")&&args.length==2)return complete(PLANETS,args[1]); - if(args[0].equalsIgnoreCase("admin")&&sender.hasPermission("dune.admin")){ - if(args.length==2)return complete(List.of("solari","teleport","spicebloom"),args[1]); - if(args[1].equalsIgnoreCase("teleport")&&args.length==3)return complete(List.of("arrakis","sietch","spiceblow"),args[2]); - if(args[1].equalsIgnoreCase("spicebloom")&&args.length==3)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[2]); - if((args[1].equalsIgnoreCase("teleport")||args[1].equalsIgnoreCase("solari"))&&args.length==4)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[3]); - } - if(args[0].equalsIgnoreCase("balance")&&args.length==2&&sender.hasPermission("dune.admin"))return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[1]); - return List.of(); - } - private List complete(Collection options,String prefix){return options.stream().filter(s->s.toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT))).sorted(String.CASE_INSENSITIVE_ORDER).toList();} -} diff --git a/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java b/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java deleted file mode 100644 index 598e9165..00000000 --- a/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.example.duneess; - -import com.example.dunegui.NativeMenus; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.command.*; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.*; -import org.bukkit.event.player.PlayerQuitEvent; -import java.io.*; -import java.nio.file.*; -import java.util.*; - -/** Deliberately small essentials command surface; vanilla owns bed/anchor respawns. */ -final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener { - private final DuneEss plugin; - private final File file; - private YamlConfiguration homes; - private PersonalHomeTravel homeTravel; - private final Map requests=new HashMap<>(); - private record Request(UUID sender,long expires) {} - EssentialsBasics(DuneEss plugin) { - this.plugin=plugin; - file=new File(plugin.getDataFolder(),"homes.yml"); - homes=YamlConfiguration.loadConfiguration(file); - } - void register() { - homeTravel=new PersonalHomeTravel(plugin); - for(String name:List.of("home","rescue","sethome","delhome","homes","tpa","tpaccept","tpdeny","spawn","server","essentials")) { - PluginCommand command=Objects.requireNonNull(plugin.getCommand(name)); - command.setExecutor(this); command.setTabCompleter(this); - } - Bukkit.getPluginManager().registerEvents(this,plugin); - } - static String homeName(String[] args) { - String name=args.length==0?"home":args[0].toLowerCase(Locale.ROOT); - if(args.length>1 || !name.matches("[a-z0-9_-]{1,24}")) throw new IllegalArgumentException("Use a home name with 1–24 letters, numbers, underscores or hyphens."); - return name; - } - private record HomeAddress(String name,boolean explicitWorld) {} - private static HomeAddress address(Player player,String[] args){ - if(args.length!=2)return new HomeAddress(homeName(args),false); - if(!player.getWorld().getName().equalsIgnoreCase(args[0])){ - throw new IllegalArgumentException("Use the Spacing Guild Navigator to reach "+args[0]+" first."); - } - return new HomeAddress(homeName(new String[]{args[1]}),true); - } - private String worldKey(Player player,String name){ - return "worldHomes."+player.getUniqueId()+"."+player.getWorld().getUID()+"."+name; - } - private Location location(Player player,String name){ - Location current=homes.getLocation(worldKey(player,name)); - return current!=null?current:homes.getLocation(key(player,name)); - } - private String key(Player p,String name) { return p.getUniqueId()+"."+name; } - private Set names(Player p) { - var section=homes.getConfigurationSection(p.getUniqueId().toString()); - var world=homes.getConfigurationSection("worldHomes."+p.getUniqueId()+"."+p.getWorld().getUID()); - Set result=new TreeSet<>(); - if(section!=null)result.addAll(section.getKeys(false)); - if(world!=null)result.addAll(world.getKeys(false)); - return result; - } - private void save() throws IOException { - Path target=file.toPath(), temp=target.resolveSibling("homes.yml.tmp"); - Files.createDirectories(target.getParent()); - Files.writeString(temp,homes.saveToString()); - try { Files.move(temp,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING); } - catch(AtomicMoveNotSupportedException ex) { Files.move(temp,target,StandardCopyOption.REPLACE_EXISTING); } - } - private void teleport(Player p,Location location) { - // Local essentials never bypass interplanetary permits, fares, or arrival rules. - if(location==null || location.getWorld()==null) { p.sendMessage("That destination is unavailable on this server."); return; } - if(!p.getWorld().equals(location.getWorld())) { p.sendMessage("Use /server to travel between worlds, then /home at your destination."); return; } - if(!location.getWorld().getWorldBorder().isInside(location) || location.getY()=location.getWorld().getMaxHeight()) { - p.sendMessage("That destination is outside the world's playable bounds."); return; - } - p.teleportAsync(location).thenAccept(success->{ if(!success) p.sendMessage("Teleportation failed. Try again."); }); - } - void menu(Player p) { - List choices=new ArrayList<>(); - choices.add(new NativeMenus.Choice("Set home","Save your current position as home.",()->p.performCommand("sethome"))); - choices.add(new NativeMenus.Choice("Homes","Choose a saved home on this backend.",()->homeMenu(p))); - choices.add(new NativeMenus.Choice("Spawn","Return to this world's spawn.",()->p.performCommand("spawn"))); - choices.add(new NativeMenus.Choice("Guild servers","Travel using existing Solaris fares and permissions.",()->p.performCommand("duneess travel"))); - choices.add(new NativeMenus.Choice("Solaris","Show your balance.",()->p.performCommand("duneess balance"))); - choices.add(new NativeMenus.Choice("Koopkring Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange"))); - choices.add(new NativeMenus.Choice("Help","Open the Dune Field Guide.",()->p.performCommand("duneess help menu"))); - NativeMenus.show(plugin,p,"DuneRealms Essentials","Solaris: "+plugin.economy().format(plugin.economy().getBalance(p)),choices); - } - private void homeMenu(Player p) { - List choices=names(p).stream().sorted().map(name->new NativeMenus.Choice(name,"Teleport to this saved home.",()->p.performCommand("home "+name))).toList(); - if(choices.isEmpty()) p.sendMessage("You have no homes. Use /sethome [name]."); - else NativeMenus.show(plugin,p,"Your homes",choices); - } - @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) { - if(!(sender instanceof Player p)) { sender.sendMessage("Use this command in-game."); return true; } - String action=command.getName(); - if(!p.hasPermission("duneess.basics")) { p.sendMessage("You do not have permission to use essentials."); return true; } - try { - switch(action) { - case "essentials" -> menu(p); - case "homes" -> homeMenu(p); - case "sethome" -> { - HomeAddress address=address(p,args);String name=address.name(),path=address.explicitWorld()?worldKey(p,name):key(p,name); - if(!names(p).contains(name) && names(p).size()>=Math.max(1,plugin.getConfig().getInt("essentials.max-homes",3))) throw new IllegalArgumentException("Your home limit has been reached."); - homes.set(path,p.getLocation()); save(); p.sendMessage("Home saved: "+name); - } - case "rescue" -> {if(args.length!=0)throw new IllegalArgumentException("Use /rescue for emergency travel.");homeTravel.rescue(p,location(p,"home"));} - case "home" -> { - HomeAddress address=address(p,args); - Location destination=location(p,address.name()); - if(address.explicitWorld()||homes.contains(worldKey(p,address.name())))homeTravel.worldHome(p,destination); - else homeTravel.begin(p,destination); - } - case "delhome" -> { - HomeAddress address=address(p,args);String name=address.name(),scoped=worldKey(p,name),path=address.explicitWorld()||homes.contains(scoped)?scoped:key(p,name); - if(!homes.contains(path)) throw new IllegalArgumentException("That home does not exist."); - homes.set(path,null); save(); p.sendMessage("Home removed: "+name); - } - case "spawn" -> teleport(p,p.getWorld().getSpawnLocation()); - case "server" -> plugin.onCommand(p,Objects.requireNonNull(plugin.getCommand("duneess")),"duneess",args.length==0?new String[]{"travel"}:new String[]{"travel",args[0]}); - case "tpa" -> { - if(args.length!=1) throw new IllegalArgumentException("Usage: /tpa "); - Player target=Bukkit.getPlayerExact(args[0]); - if(target==null || target.equals(p) || !p.canSee(target)) throw new IllegalArgumentException("Choose another online player on this server."); - if(!target.getWorld().equals(p.getWorld())) throw new IllegalArgumentException("Use Vaerkring travel to reach that player's world first."); - requests.put(target.getUniqueId(),new Request(p.getUniqueId(),System.nanoTime()+60_000_000_000L)); - target.sendMessage(p.getName()+" requests to teleport to you. /tpaccept or /tpdeny (60 seconds)."); - p.sendMessage("Teleport request sent."); - } - case "tpaccept","tpdeny" -> { - Request request=requests.remove(p.getUniqueId()); - if(request==null || request.expires() { return false; } - } - } catch(IllegalArgumentException ex) { p.sendMessage(ex.getMessage()); } - catch(IOException ex) { - homes=YamlConfiguration.loadConfiguration(file); - plugin.getLogger().warning("Could not persist homes: "+ex.getMessage()); - p.sendMessage("Could not save your homes. No change was committed."); - } - return true; - } - @Override public List onTabComplete(CommandSender sender,Command command,String alias,String[] args) { - if(!(sender instanceof Player p))return List.of(); - if(args.length==2&&Set.of("home","delhome").contains(command.getName())&&p.getWorld().getName().equalsIgnoreCase(args[0]))return names(p).stream().filter(n->n.startsWith(args[1].toLowerCase(Locale.ROOT))).toList(); - if(args.length!=1)return List.of(); - Collection values=switch(command.getName()) { - case "home","delhome" -> {var choices=new TreeSet<>(names(p));choices.add(p.getWorld().getName());yield choices;} - case "sethome" -> List.of(p.getWorld().getName()); - case "tpa" -> Bukkit.getOnlinePlayers().stream().filter(p::canSee).map(Player::getName).toList(); - case "server" -> List.of("arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv","spacing_guild"); - default -> List.of(); - }; - return values.stream().filter(v->v.toLowerCase(Locale.ROOT).startsWith(args[0].toLowerCase(Locale.ROOT))).toList(); - } - @EventHandler public void quit(PlayerQuitEvent event) { - UUID id=event.getPlayer().getUniqueId(); - requests.remove(id); requests.values().removeIf(request->request.sender().equals(id)); - } -} diff --git a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java b/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java deleted file mode 100644 index 8c64d9bc..00000000 --- a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java +++ /dev/null @@ -1,320 +0,0 @@ -package com.example.duneess; - -import org.bukkit.*; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.event.*; -import org.bukkit.event.inventory.*; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.inventory.*; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataType; -import org.bukkit.plugin.Plugin; -import java.math.BigDecimal; -import java.sql.SQLException; -import java.util.*; - -/** Native menus share the existing SQL-backed trading operations. */ -@SuppressWarnings("deprecation") -final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { - private static final List CATEGORIES=List.of("ores","spice","building","equipment","farming","misc"); - private static final List PLANETS=List.of("all","arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv"); - private static final List ICONS=List.of(Material.IRON_PICKAXE,Material.ORANGE_DYE,Material.BRICKS,Material.IRON_SWORD,Material.WHEAT,Material.CHEST); - private final DuneEss plugin; - private final ExchangeStore store; - private final Map planets=new HashMap<>(); - private boolean ready; - static final class Screen implements InventoryHolder { - final UUID owner; - final Map actions=new HashMap<>(); - Inventory inventory; - String title; - Screen(UUID owner) { this.owner=owner; } - @Override public Inventory getInventory() { return inventory; } - } - ExchangeMenu(DuneEss plugin) { - this.plugin=plugin; - this.store=new ExchangeStore(plugin::connectEconomyDatabase); - } - void register() { - PluginCommand command=Objects.requireNonNull(plugin.getCommand("exchange")); - command.setExecutor(this); command.setTabCompleter(this); - Bukkit.getPluginManager().registerEvents(this,plugin); - try { store.initialize(); ready=true; } - catch(SQLException ex) { plugin.getLogger().warning("Koopkring is offline until the shared PostgreSQL economy is connected."); } - } - private boolean connected(Player p) { - // Retry after a transient startup outage; never trade against a fallback local wallet. - if(!ready) try { store.initialize(); ready=true; } catch(SQLException ignored) { } - if(!ready) p.sendMessage(ChatColor.YELLOW+"Koopkring is not connected. Ask an operator to configure DuneCore PostgreSQL and restart DuneEss. No items or Dunemarks were taken."); - return ready; - } - private String faction(Player p) { - Plugin core=Bukkit.getPluginManager().getPlugin("DuneCore"); - if(core!=null) try { - String house=String.valueOf(core.getClass().getMethod("factionOf",Player.class).invoke(core,p)); - if(List.of("Fremen","Atreides","Harkonnen","Corrino","Ordos").contains(house)) return house; - } catch(ReflectiveOperationException ignored) { } - return "Vaerkring"; - } - private ChatColor tint(Player p) { - return switch(faction(p)) { - case "Atreides" -> ChatColor.AQUA; - case "Harkonnen" -> ChatColor.RED; - case "Corrino" -> ChatColor.GOLD; - case "Fremen" -> ChatColor.YELLOW; - case "Ordos" -> ChatColor.GREEN; - default -> ChatColor.LIGHT_PURPLE; - }; - } - private ItemStack icon(Material material,String name,String... lore) { - ItemStack item=new ItemStack(material); ItemMeta meta=item.getItemMeta(); - meta.setDisplayName(name); meta.setLore(Arrays.asList(lore)); item.setItemMeta(meta); return item; - } - private Screen screen(Player p,String title) { - Screen s=new Screen(p.getUniqueId()); - s.title="Koopkring | "+title; - s.inventory=Bukkit.createInventory(s,54,tint(p)+"Koopkring | "+title); - Material glass=switch(faction(p)) { - case "Atreides" -> Material.CYAN_STAINED_GLASS_PANE; - case "Harkonnen" -> Material.RED_STAINED_GLASS_PANE; - case "Corrino" -> Material.YELLOW_STAINED_GLASS_PANE; - case "Ordos" -> Material.GREEN_STAINED_GLASS_PANE; - case "Fremen" -> Material.ORANGE_STAINED_GLASS_PANE; - default -> Material.PURPLE_STAINED_GLASS_PANE; - }; - for(int i=0;i<54;i++) if(i<9||i>=45||i%9==0||i%9==8) - s.inventory.setItem(i,icon(glass," ")); - s.inventory.setItem(47,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Dunemarks",List.of(ChatColor.GRAY+"Wallet: "+plugin.balanceLabel(p),ChatColor.GRAY+"Display icon only; balances stay in the ledger."))); - button(s,49,Material.BARRIER,"Back to Exchange",()->home(p)); return s; - } - private void button(Screen s,int slot,Material material,String title,Runnable action,String... lore) { - s.inventory.setItem(slot,icon(material,ChatColor.GOLD+title,lore)); s.actions.put(slot,action); - } - private void home(Player p) { - Screen s=screen(p,faction(p)); - for(int i=0;ibrowse(p,category,0,false,false)); - } - s.inventory.setItem(29,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Buy / All Items",List.of(ChatColor.GRAY+"Pay with Dunemarks from your wallet."))); - s.actions.put(29,()->browse(p,"all",0,false,false)); - button(s,31,Material.CHEST,"Sell Held Item",()->{ - p.closeInventory(); p.sendMessage(ChatColor.YELLOW+"Hold the item to list, then /exchange sell . Example: /exchange sell 16 25"); - },"Tagged Dune items and their attributes are preserved.","Price is for ONE item."); - button(s,33,Material.BOOK,"My Listings",()->browse(p,"all",0,true,false),"Cancel and reclaim your unsold items."); - button(s,40,Material.COMPASS,"Planet: "+planets.getOrDefault(p.getUniqueId(),"all"),()->planetMenu(p)); - button(s,38,Material.PAPER,"Trading Guide",()->{ - p.sendMessage(ChatColor.YELLOW+"/exchange sell · /exchange buy · /exchange cancel · /exchange mine"); - p.sendMessage(ChatColor.GRAY+"Purchases buy one item. Listings reserve the offered items. Website demo offers cannot be purchased."); - }); - if(p.hasPermission("dune.admin")) button(s,42,Material.COMMAND_BLOCK,"Exchange Administration",()->admin(p)); - button(s,49,Material.BARRIER,"Close",p::closeInventory); - com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); - } - private void planetMenu(Player p) { - Screen s=screen(p,"Planet Filter"); - for(int i=0;i{planets.put(p.getUniqueId(),planet); browse(p,"all",0,false,false);}); - } - com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); - } - private void admin(Player p) { - if(!p.hasPermission("dune.admin")) return; - Screen s=screen(p,"Administration"); - button(s,20,Material.BOOK,"All Listings",()->browse(p,"all",0,false,true),"All planets. Read-only inspection; normal ownership rules apply."); - button(s,24,Material.REDSTONE,"Check Database",()->{ - if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared Koopkring database connected."); - }); - com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); - } - private ItemStack decode(ExchangeStore.Listing offer) { - ItemStack item; - if(offer.payload()!=null&&!offer.payload().isBlank()) item=ItemStack.deserializeBytes(Base64.getDecoder().decode(offer.payload())); - else { - Material material=Material.matchMaterial(offer.material()); - if(material==null||material.isAir()||!material.isItem()) throw new IllegalArgumentException("This item is unsupported on this server; contact an operator."); - item=new ItemStack(material); - } - item.setAmount(1); return item; - } - private void browse(Player p,String category,int page,boolean mine,boolean admin) { - if(admin&&!p.hasPermission("dune.admin")) return; - if(!connected(p)) return; - execute(p,()->{ - int current=Math.max(0,page); - String planet=mine||admin?"all":planets.getOrDefault(p.getUniqueId(),"all"); - List rows=store.browse(category,planet,mine?p.getUniqueId():null,current); - Screen s=screen(p,(mine?"My Listings":admin?"All Listings":category)+" · "+(current+1)); - int slot=10; - for(ExchangeStore.Listing row:rows.subList(0,Math.min(28,rows.size()))) { - while(slot%9==0||slot%9==8) slot++; - ItemStack item; - try { item=decode(row); } catch(RuntimeException ex) { item=new ItemStack(Material.PAPER); } - ItemMeta meta=item.getItemMeta(); - meta.setDisplayName(ChatColor.GOLD+"#"+row.id()+" "+(row.displayName()==null?row.material():row.displayName())); - meta.setLore(List.of("Quantity: "+row.quantity(),"Each: "+row.price()+" Dunemarks","Seller: "+row.sellerName(),"Planet: "+row.origin(), - row.seller().equals(p.getUniqueId())?"Click to reclaim unsold items":"Click to review purchase")); - item.setItemMeta(meta); s.inventory.setItem(slot,item); - s.actions.put(slot,()->confirm(p,row.id(),row.seller().equals(p.getUniqueId()))); slot++; - } - if(rows.isEmpty()) s.inventory.setItem(22,icon(Material.PAPER,"No matching listings","Try another planet or list a held item.")); - if(current>0) button(s,45,Material.ARROW,"Previous",()->browse(p,category,current-1,mine,admin)); - if(rows.size()>28) button(s,53,Material.ARROW,"Next",()->browse(p,category,current+1,mine,admin)); - com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); - }); - } - private void confirm(Player p,long id,boolean reclaim) { - execute(p,()->{ - ExchangeStore.Listing row=store.find(id); - if(reclaim&&!row.seller().equals(p.getUniqueId())) throw new IllegalArgumentException("You can reclaim only your own listings."); - Screen s=screen(p,reclaim?"Reclaim Listing":"Confirm Purchase"); - s.inventory.setItem(22,icon(decode(row).getType(),"#"+id+" "+(row.displayName()==null?row.material():row.displayName()), - "Seller: "+row.sellerName(),reclaim?"Return "+row.quantity()+" unsold items":"Buy ONE for "+row.price()+" Dunemarks")); - button(s,30,Material.LIME_CONCRETE,reclaim?"Confirm Reclaim":"Confirm Purchase",()->{ - p.closeInventory(); if(reclaim) cancel(p,id); else buy(p,id); - }); - button(s,32,Material.RED_CONCRETE,"Never Mind",()->home(p)); com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); - }); - } - private boolean fits(Player p,ItemStack item,int amount) { - int remaining=amount; - for(ItemStack slot:p.getInventory().getStorageContents()) { - if(slot==null||slot.getType().isAir()) remaining-=item.getMaxStackSize(); - else if(slot.isSimilar(item)) remaining-=Math.max(0,item.getMaxStackSize()-slot.getAmount()); - if(remaining<=0) return true; - } - return false; - } - private void deliver(Player p,ItemStack item,int amount) { - item.setAmount(amount); - Map excess=p.getInventory().addItem(item); - // Capacity is checked immediately before the transaction on this same server thread. - if (!excess.isEmpty()) throw new IllegalArgumentException("Inventory changed; the trade was rolled back. Make room and retry."); - } - private void sell(Player p,int amount,BigDecimal price) throws SQLException { - ExchangeStore.validate(amount,price); - ItemStack held=p.getInventory().getItemInMainHand(); - if(held.getType().isAir()||amount>held.getAmount()) throw new IllegalArgumentException("Hold at least that many items in your main hand."); - // Never let operator tools become tradeable through the public exchange. - if(held.hasItemMeta()) for(NamespacedKey key:held.getItemMeta().getPersistentDataContainer().getKeys()) - if(key.getKey().contains("admin")) throw new IllegalArgumentException("Administrative tools cannot be listed."); - ItemStack unit=held.clone(); unit.setAmount(1); - String name=unit.hasItemMeta()&&unit.getItemMeta().hasDisplayName()?ChatColor.stripColor(unit.getItemMeta().getDisplayName()):unit.getType().name(); - if(name.length()>120) name=name.substring(0,120); - final String displayName=name; - atomic(p, scoped -> { - scoped.list(p.getUniqueId(),p.getName(),origin(p),category(unit),unit.getType().name(),amount,price, - Base64.getEncoder().encodeToString(unit.serializeAsBytes()),displayName); - held.setAmount(held.getAmount()-amount); - }); - p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+name+" at "+price+" Dunemarks each."); - } - private String origin(Player p) { - String world=p.getWorld().getName().toLowerCase(Locale.ROOT).replace('-','_'); - for(String planet:PLANETS) if(!planet.equals("all")&&world.contains(planet)) return planet; - return plugin.localPlanet(); - } - static String category(ItemStack item) { - if(item.hasItemMeta()) { - String kind=item.getItemMeta().getPersistentDataContainer().get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING); - if(kind!=null&&kind.toLowerCase(Locale.ROOT).contains("spice")) return "spice"; - } - String n=item.getType().name(); - if(n.contains("ORE")||n.contains("INGOT")||n.contains("DEBRIS")||n.contains("DIAMOND")||n.contains("EMERALD")||n.contains("COAL")||n.contains("REDSTONE")||n.contains("RAW_")||n.contains("LAPIS")||n.contains("QUARTZ")) return "ores"; - if(n.contains("SWORD")||n.contains("PICKAXE")||n.endsWith("AXE")||n.contains("HELMET")||n.contains("CHESTPLATE")||n.contains("LEGGINGS")||n.contains("BOOTS")||n.contains("ELYTRA")||n.contains("BOW")||n.contains("SHOVEL")||n.contains("HOE")||n.equals("SHIELD")||n.equals("TRIDENT")||n.equals("FISHING_ROD")||n.equals("ENCHANTED_BOOK")) return "equipment"; - if(item.getType().isEdible()||n.contains("WHEAT")||n.contains("SEED")||n.contains("SAPLING")) return "farming"; - return item.getType().isBlock()?"building":"misc"; - } - private void buy(Player p,long id) { - if(!connected(p)) return; - execute(p,()->{ - ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before); - if(!fits(p,item,1)) throw new IllegalArgumentException("Make room in your inventory first."); - atomic(p, scoped -> { - scoped.buy(p.getUniqueId(),p.getName(),id); - deliver(p,item,1); - }); - p.sendMessage(ChatColor.GREEN+"Purchased one item for "+before.price()+" Dunemarks."); - }); - } - private void cancel(Player p,long id) { - if(!connected(p)) return; - execute(p,()->{ - ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before); - if(!fits(p,item,before.quantity())) throw new IllegalArgumentException("Make room for all "+before.quantity()+" items first."); - atomic(p, scoped -> { - ExchangeStore.Listing cancelled=scoped.cancel(p.getUniqueId(),id); - deliver(p,item,cancelled.quantity()); - }); - p.sendMessage(ChatColor.GREEN+"Listing cancelled. Unsold items returned."); - }); - } - private interface Trade { void run(ExchangeStore scoped) throws SQLException; } - private void atomic(Player p, Trade trade) throws SQLException { - Plugin core=Bukkit.getPluginManager().getPlugin("DuneCore"); - if (core==null) throw new SQLException("DuneCore network profiles are required"); - try { - java.util.function.Consumer work = connection -> { - try { trade.run(ExchangeStore.bound(connection)); } - catch (SQLException ex) { throw new java.util.concurrent.CompletionException(ex); } - }; - core.getClass().getMethod("transactNetworkInventory",Player.class,java.util.function.Consumer.class).invoke(core,p,work); - } catch (ReflectiveOperationException ex) { - Throwable cause=ex instanceof java.lang.reflect.InvocationTargetException ? ex.getCause() : ex; - if (cause instanceof java.util.concurrent.CompletionException && cause.getCause()!=null) cause=cause.getCause(); - if (cause instanceof IllegalArgumentException invalid) throw invalid; - if (cause instanceof SQLException sql) throw sql; - throw new SQLException("Network inventory transaction unavailable; install matching Core and Essentials",cause); - } - } - private interface Operation { void run() throws SQLException; } - private void execute(Player p,Operation action) { - try { action.run(); } - catch(IllegalArgumentException ex) { p.sendMessage(ChatColor.YELLOW+ex.getMessage()); } - catch(SQLException ex) { - ready=false; plugin.getLogger().warning("Koopkring SQL operation failed: "+ex.getSQLState()); - p.sendMessage(ChatColor.RED+"The market database is unavailable. Please try again later."); - } - } - @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) { - if(!(sender instanceof Player p)) { sender.sendMessage("Open the Koopkring exchange in-game with /exchange."); return true; } - if(args.length==0) { home(p); return true; } - String action=args[0].toLowerCase(Locale.ROOT); - if(action.equals("admin")) { if(p.hasPermission("dune.admin")) admin(p); else p.sendMessage(ChatColor.RED+"Operators only."); return true; } - if(action.equals("help")) { home(p); return true; } - if(!connected(p)) return true; - execute(p,()->{ - try { - switch(action) { - case "sell" -> { if(args.length!=3) throw new IllegalArgumentException("/exchange sell "); sell(p,Integer.parseInt(args[1]),new BigDecimal(args[2])); } - case "buy","cancel" -> { if(args.length!=2) throw new IllegalArgumentException("/exchange "+action+" "); long id=Long.parseLong(args[1]); if(id<1) throw new IllegalArgumentException("Listing IDs are positive numbers."); confirm(p,id,action.equals("cancel")); } - case "mine" -> browse(p,"all",0,true,false); - default -> p.sendMessage(ChatColor.YELLOW+"Use /exchange, /exchange sell , /exchange buy , /exchange cancel , or /exchange mine."); - } - } catch(NumberFormatException ex) { throw new IllegalArgumentException("Enter a valid amount, price and listing ID."); } - }); - return true; - } - @Override public List onTabComplete(CommandSender sender,Command command,String alias,String[] args) { - if(args.length!=1) return List.of(); - return List.of("help","sell","buy","cancel","mine","admin").stream() - .filter(s->!s.equals("admin")||sender.hasPermission("dune.admin")) - .filter(s->s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList(); - } - @EventHandler public void click(InventoryClickEvent e) { - if(!(e.getView().getTopInventory().getHolder() instanceof Screen screen)) return; - e.setCancelled(true); - if(!(e.getWhoClicked() instanceof Player p)||!screen.owner.equals(p.getUniqueId()) - ||e.getClickedInventory()!=e.getView().getTopInventory()||e.getClick()==ClickType.DOUBLE_CLICK) return; - Runnable action=screen.actions.get(e.getRawSlot()); - if(action!=null) Bukkit.getScheduler().runTask(plugin,()->{ - if(p.isOnline()&&p.getOpenInventory().getTopInventory()==screen.inventory) action.run(); - }); - } - @EventHandler public void drag(InventoryDragEvent e) { - if(e.getView().getTopInventory().getHolder() instanceof Screen) e.setCancelled(true); - } - @EventHandler public void quit(PlayerQuitEvent e) { planets.remove(e.getPlayer().getUniqueId()); } -} diff --git a/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java b/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java deleted file mode 100644 index e9ec7dcf..00000000 --- a/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.example.duneess; - -import java.math.BigDecimal; -import java.sql.*; -import java.util.*; - -/** SQL escrow and wallet changes share one transaction. Bukkit inventory work stays on its server thread. */ -final class ExchangeStore { - interface Connections { Connection open() throws SQLException; } - record Listing(long id, UUID seller, String sellerName, String origin, String category, - String material, int quantity, BigDecimal price, String payload, String displayName) {} - private final Connections connections; - ExchangeStore(Connections connections) { this.connections = connections; } - /** Reuse the Core profile transaction; only Core may commit, roll back or close it. */ - static ExchangeStore bound(Connection connection) { - Connection scoped = (Connection) java.lang.reflect.Proxy.newProxyInstance( - ExchangeStore.class.getClassLoader(), new Class[]{Connection.class}, (proxy, method, args) -> { - if (Set.of("close", "commit", "rollback", "setAutoCommit").contains(method.getName())) return null; - try { return method.invoke(connection, args); } - catch (java.lang.reflect.InvocationTargetException ex) { throw ex.getCause(); } - }); - return new ExchangeStore(() -> scoped); - } - void initialize() throws SQLException { - try (Connection c = connections.open(); Statement s = c.createStatement()) { - s.setQueryTimeout(5); - s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_listings (id BIGSERIAL PRIMARY KEY, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, origin VARCHAR(48) NOT NULL, category VARCHAR(24) NOT NULL, material VARCHAR(80) NOT NULL, quantity INT NOT NULL CHECK(quantity>0), price NUMERIC(20,2) NOT NULL CHECK(price>0))"); - s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS payload TEXT"); - s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS display_name VARCHAR(120)"); - s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_sales (id BIGSERIAL PRIMARY KEY, listing_id BIGINT NOT NULL, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, buyer UUID NOT NULL, buyer_name VARCHAR(32) NOT NULL, material VARCHAR(80) NOT NULL, display_name VARCHAR(120), quantity INTEGER NOT NULL CHECK(quantity>0), unit_price NUMERIC(20,2) NOT NULL CHECK(unit_price>0), total_price NUMERIC(20,2) NOT NULL CHECK(total_price>0), origin VARCHAR(48) NOT NULL, sold_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP)"); - s.executeUpdate("CREATE INDEX IF NOT EXISTS dune_exchange_sales_seller_id ON dune_exchange_sales(seller,id DESC)"); - } - } - private PreparedStatement prepare(Connection c, String sql) throws SQLException { - PreparedStatement q = c.prepareStatement(sql); q.setQueryTimeout(5); return q; - } - static void validate(int amount, BigDecimal price) { - if (amount < 1 || amount > 64 || price == null || price.signum() <= 0 || price.scale() > 2 - || price.compareTo(new BigDecimal("1000000")) > 0) - throw new IllegalArgumentException("Use 1–64 items and a price from 0.01 to 1,000,000 Solaris (two decimals maximum)."); - } - void list(UUID seller, String name, String origin, String category, String material, - int amount, BigDecimal price, String payload, String displayName) throws SQLException { - validate(amount, price); - try (Connection c = connections.open(); PreparedStatement q = prepare(c, - "INSERT INTO dune_exchange_listings(seller,seller_name,origin,category,material,quantity,price,payload,display_name) VALUES(?,?,?,?,?,?,?,?,?)")) { - q.setObject(1,seller); q.setString(2,name); q.setString(3,origin); q.setString(4,category); - q.setString(5,material); q.setInt(6,amount); q.setBigDecimal(7,price); q.setString(8,payload); q.setString(9,displayName); - q.executeUpdate(); - } - } - List browse(String category, String planet, UUID owner, int page) throws SQLException { - String sql = "SELECT * FROM dune_exchange_listings WHERE origin<>'jarvis-hq'"; - if (!category.equals("all")) sql += " AND category=?"; - if (!planet.equals("all")) sql += " AND origin=?"; - if (owner != null) sql += " AND seller=?"; - sql += " ORDER BY id DESC LIMIT 29 OFFSET ?"; - try (Connection c = connections.open(); PreparedStatement q = prepare(c,sql)) { - int k=1; - if (!category.equals("all")) q.setString(k++,category); - if (!planet.equals("all")) q.setString(k++,planet); - if (owner!=null) q.setObject(k++,owner); - q.setInt(k,Math.max(0,page)*28); - try (ResultSet r=q.executeQuery()) { - List rows=new ArrayList<>(); while(r.next()) rows.add(read(r)); return rows; - } - } - } - Listing find(long id) throws SQLException { - try(Connection c=connections.open(); PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? AND origin<>'jarvis-hq'")) { - q.setLong(1,id); try(ResultSet r=q.executeQuery()) { - if(!r.next()) throw new IllegalArgumentException("That listing has already been sold or cancelled."); - return read(r); - } - } - } - private Listing read(ResultSet r) throws SQLException { - return new Listing(r.getLong("id"),r.getObject("seller",UUID.class),r.getString("seller_name"), - r.getString("origin"),r.getString("category"),r.getString("material"),r.getInt("quantity"), - r.getBigDecimal("price"),r.getString("payload"),r.getString("display_name")); - } - /** On SQL failure, no wallet or listing changes survive. Never set quantity to zero under CHECK(quantity>0). */ - Listing buy(UUID buyer, long id) throws SQLException { return buy(buyer, "Unknown", id); } - Listing buy(UUID buyer, String buyerName, long id) throws SQLException { - try(Connection c=connections.open()) { - c.setAutoCommit(false); - try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? AND origin<>'jarvis-hq' FOR UPDATE")) { - q.setLong(1,id); - try(ResultSet r=q.executeQuery()) { - if(!r.next()) throw new IllegalArgumentException("Listing unavailable."); - Listing offer=read(r); - if(offer.seller().equals(buyer)) throw new IllegalArgumentException("Use My Listings to reclaim your own offer."); - try(PreparedStatement debit=prepare(c,"UPDATE dune_economy_balances SET balance=balance-? WHERE uuid=? AND balance>=?"); - PreparedStatement credit=prepare(c,"UPDATE dune_economy_balances SET balance=balance+? WHERE uuid=?"); - PreparedStatement stock=prepare(c,offer.quantity()==1?"DELETE FROM dune_exchange_listings WHERE id=?":"UPDATE dune_exchange_listings SET quantity=quantity-1 WHERE id=?")) { - debit.setBigDecimal(1,offer.price()); debit.setObject(2,buyer); debit.setBigDecimal(3,offer.price()); - if(debit.executeUpdate()!=1) throw new IllegalArgumentException("Insufficient Solaris or shared wallet unavailable."); - credit.setBigDecimal(1,offer.price()); credit.setObject(2,offer.seller()); - if(credit.executeUpdate()!=1) throw new IllegalArgumentException("Seller wallet unavailable; no payment taken."); - stock.setLong(1,id); if(stock.executeUpdate()!=1) throw new SQLException("Listing changed."); - try (PreparedStatement sale = prepare(c, "INSERT INTO dune_exchange_sales(listing_id,seller,seller_name,buyer,buyer_name,material,display_name,quantity,unit_price,total_price,origin) VALUES(?,?,?,?,?,?,?,1,?,?,?)")) { - sale.setLong(1, id); sale.setObject(2, offer.seller()); sale.setString(3, offer.sellerName()); - sale.setObject(4, buyer); sale.setString(5, buyerName); - sale.setString(6, offer.material()); sale.setString(7, offer.displayName()); - sale.setBigDecimal(8, offer.price()); sale.setBigDecimal(9, offer.price()); sale.setString(10, offer.origin()); - sale.executeUpdate(); - } - c.commit(); return offer; - } - } - } catch(SQLException|RuntimeException ex) { c.rollback(); throw ex; } - } - } - Listing cancel(UUID owner, long id) throws SQLException { - try(Connection c=connections.open()) { - c.setAutoCommit(false); - try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? AND seller=? FOR UPDATE")) { - q.setLong(1,id); q.setObject(2,owner); - try(ResultSet r=q.executeQuery()) { - if(!r.next()) throw new IllegalArgumentException("This listing is unavailable or belongs to another player."); - Listing offer=read(r); - try(PreparedStatement d=prepare(c,"DELETE FROM dune_exchange_listings WHERE id=?")) { - d.setLong(1,id); d.executeUpdate(); c.commit(); return offer; - } - } - } catch(SQLException|RuntimeException ex) { c.rollback(); throw ex; } - } - } -} diff --git a/DuneEss/src/main/java/com/example/duneess/PersonalHomeTravel.java b/DuneEss/src/main/java/com/example/duneess/PersonalHomeTravel.java deleted file mode 100644 index 96ae9935..00000000 --- a/DuneEss/src/main/java/com/example/duneess/PersonalHomeTravel.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.example.duneess; - -import com.google.gson.*; -import org.bukkit.*; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.*; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.plugin.java.JavaPlugin; -import java.nio.file.*; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.*; - -/** Same-world home travel. The existing connector owns central banking; this journal owns delivery. */ -final class PersonalHomeTravel implements Listener { - private final JavaPlugin plugin;private final Path file;private YamlConfiguration journal; - private final Map waiting=new HashMap<>();private final Set busy=new HashSet<>(); - PersonalHomeTravel(JavaPlugin plugin){ - this.plugin=plugin;file=plugin.getDataFolder().toPath().resolve("home-journeys.yml");journal=YamlConfiguration.loadConfiguration(file.toFile()); - Bukkit.getPluginManager().registerEvents(this,plugin); - Bukkit.getScheduler().runTaskTimer(plugin,this::recover,40,100); - } - static boolean valid(Location location){return location!=null&&location.getWorld()!=null&&Double.isFinite(location.getX())&&Double.isFinite(location.getY())&&Double.isFinite(location.getZ())&&location.getWorld().getWorldBorder().isInside(location)&&location.getY()>=location.getWorld().getMinHeight()&&location.getY()>4,at.getBlockZ()>>4))return false; - var feet=at.getBlock(); - var head=feet.getRelative(org.bukkit.block.BlockFace.UP); - var floor=feet.getRelative(org.bukkit.block.BlockFace.DOWN); - return feet.getType().isAir()&&head.getType().isAir()&&floor.getType().isSolid()&& - !Set.of(Material.MAGMA_BLOCK,Material.CACTUS,Material.CAMPFIRE,Material.SOUL_CAMPFIRE).contains(floor.getType()); - } - private void begin(Player p,Location destination,String mode){ - boolean rescue=mode.equals("rescue"); - if(!valid(destination)){p.sendMessage("That saved home is unavailable or outside the world's playable bounds.");return;} - if(!p.getWorld().equals(destination.getWorld())){p.sendMessage("Travel to that world through the Guild first, then use /home.");return;} - String id=p.getUniqueId().toString();if(waiting.containsKey(p.getUniqueId())||journal.contains(id)){p.sendMessage("Your home journey is already being completed.");return;} - var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){p.sendMessage("Central home travel is unavailable. No payment was made.");return;} - UUID token=UUID.randomUUID(),world=p.getWorld().getUID();waiting.put(p.getUniqueId(),token);Location target=destination.clone(); - if(!rescue)p.sendMessage(mode.equals("world")?"World home travel in 5 seconds · Spacing Guild tariff · 24-hour cooldown.":"Home travel in 5 seconds · 25 DM · 15 minute cooldown."); - Runnable reserve=()->{ - if(!token.equals(waiting.remove(p.getUniqueId()))||!p.isOnline())return; - if(!world.equals(p.getWorld().getUID())||p.isDead()||!valid(target)){p.sendMessage("Home travel cancelled. No payment was made.");return;} - journal.set(id+".requestId",token.toString());journal.set(id+".destination",target);journal.set(id+".stage","reserve");journal.set(id+".mode",mode); - try{journal.set(id+".destinationHash",HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest((target.getWorld().getUID()+":"+target.getX()+":"+target.getY()+":"+target.getZ()+":"+target.getYaw()+":"+target.getPitch()).getBytes(StandardCharsets.UTF_8))));}catch(Exception e){throw new IllegalStateException(e);} - if(persist())attempt(id); - }; - if(rescue)reserve.run();else Bukkit.getScheduler().runTaskLater(plugin,reserve,100); - } - private void recover(){for(String id:new HashSet<>(journal.getKeys(false)))attempt(id);} - private void stage(String id,String value){journal.set(id+".stage",value);persist();} - private void attempt(String id){ - if(!busy.add(id))return; - String mode=journal.getString(id+".mode",""); - boolean rescue=mode.equals("rescue"); - String stage=journal.getString(id+".stage");Player player=Bukkit.getPlayer(UUID.fromString(id)); - // Keep a pre-payment instruction after a lost reply; retry it with exactly the same reference. - var input=new JsonObject();input.addProperty("action",stage);input.addProperty("requestId",journal.getString(id+".requestId"));input.addProperty("destinationHash",journal.getString(id+".destinationHash"));if(!mode.isEmpty())input.addProperty("mode",mode); - var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){busy.remove(id);return;} - Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{ - JsonObject result=null;try{result=JsonParser.parseString((String)connector.getClass().getMethod("requestHome",UUID.class,String.class).invoke(connector,UUID.fromString(id),input.toString())).getAsJsonObject();}catch(Exception ignored){} - JsonObject response=result;Bukkit.getScheduler().runTask(plugin,()->{ - boolean teleporting=false; - try{ - if(response==null)return; // Unknown outcome stays durable and retries, never creates another payment. - if(response.has("rejectedStatus")){ - int status=response.get("rejectedStatus").getAsInt(); - // Only a definitive reserve refusal has no accepted liability. Settlement failures retain the journal. - if(stage.equals("reserve")&&response.has("unreserved")&&response.get("unreserved").getAsBoolean()){ - if(player!=null&&player.isOnline())player.sendMessage(response.has("message")?response.get("message").getAsString():"Home travel was refused.");journal.set(id,null);persist(); - }return; - } - String state=response.get("state").getAsString(); - if(!state.equals("pending")){journal.set(id,null);persist();return;} - if(!stage.equals("reserve"))return; - Player current=Bukkit.getPlayer(UUID.fromString(id));Location target=journal.getLocation(id+".destination"); - if(current==null||!current.isOnline()||current.isDead()||!valid(target)||rescue&&!safe(target)||!current.getWorld().equals(target.getWorld())){stage(id,"cancel");return;} - // Keep the busy latch until the actual native result. Crash recovery re-delivers the same destination. - current.teleportAsync(target).whenComplete((success,failure)->Bukkit.getScheduler().runTask(plugin,()->{ - boolean arrived=Boolean.TRUE.equals(success)&&failure==null; - stage(id,arrived?"arrive":"cancel");busy.remove(id); - if(arrived&&rescue&¤t.isOnline()&&!current.isDead()){ - var health=current.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH); - if(health!=null)current.setHealth(health.getValue()); - current.setFireTicks(0);current.setFallDistance(0); - } - if(current.isOnline())current.sendMessage(arrived&&mode.equals("world")?"World home reached · "+String.format(Locale.ROOT,"%.2f DM",response.get("fareMinor").getAsLong()/100.0)+" · 24-hour cooldown.":arrived?(rescue?"Emergency rescue complete · 1,000 DM · 24-hour cooldown.":"Home reached · 25 DM · 15 minute cooldown."):"Teleport failed. Your reservation will be released.");attempt(id); - })); - teleporting=true; - return; - }finally{ - if(!teleporting)busy.remove(id); - } - }); - }); - } - @EventHandler public void quit(PlayerQuitEvent event){waiting.remove(event.getPlayer().getUniqueId());} -} diff --git a/DuneEss/src/main/java/com/example/duneess/StaffItemTools.java b/DuneEss/src/main/java/com/example/duneess/StaffItemTools.java deleted file mode 100644 index 2714adb1..00000000 --- a/DuneEss/src/main/java/com/example/duneess/StaffItemTools.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.example.duneess; - -import java.util.*; -import java.util.function.Consumer; -import java.sql.Connection; -import java.lang.reflect.InvocationTargetException; -import org.bukkit.*; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.inventory.*; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.persistence.PersistentDataType; - -/** Staff conveniences using current native recipes and the shared inventory checkpoint. */ -public final class StaffItemTools implements CommandExecutor { - private final JavaPlugin plugin; - public static void start(JavaPlugin plugin){var tools=new StaffItemTools(plugin);for(String name:List.of("condense","fix"))Objects.requireNonNull(plugin.getCommand(name)).setExecutor(tools);} - private StaffItemTools(JavaPlugin plugin){this.plugin=plugin;} - private record Compression(ItemStack result,int cost){} - private static List ingredients(Recipe recipe){ - if(recipe instanceof ShapedRecipe r){String[] rows=r.getShape();if(rows.length!=2&&rows.length!=3||Arrays.stream(rows).anyMatch(row->row.length()!=rows.length||row.contains(" ")))return List.of();var list=new ArrayList();for(String row:rows)for(char c:row.toCharArray())list.add(r.getChoiceMap().get(c));return list;} - if(recipe instanceof ShapelessRecipe r)return r.getChoiceList();return List.of(); - } - private static boolean matches(RecipeChoice choice,ItemStack stack){return choice!=null&&choice.test(stack);} - private Compression compression(ItemStack item)throws Exception{ - var data=item.getItemMeta().getPersistentDataContainer();String custom=data.get(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING),legacy=data.get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING); - var jarvis=Bukkit.getPluginManager().getPlugin("JarvisTranslator"); - if("spice".equals(legacy)||"spice".equals(custom)||"smuggled_spice".equals(custom)){var result=(ItemStack)jarvis.getClass().getMethod("compressedSpice",ItemStack.class).invoke(jarvis,item);return result==null?null:new Compression(result,9);} - if(custom!=null||legacy!=null||data.has(new NamespacedKey("dunerealms","preview_only")))return null; - var all=new ArrayList();Bukkit.recipeIterator().forEachRemaining(all::add); - for(int cost:new int[]{9,4})for(var recipe:all){ - if(!(recipe instanceof Keyed keyed)||!keyed.getKey().getNamespace().equals("minecraft"))continue; - var inputs=ingredients(recipe);var result=recipe.getResult(); - if(inputs.size()!=cost||result.getAmount()!=1||result.getType()==item.getType()||inputs.stream().anyMatch(c->!matches(c,item)))continue; - // Only reversible storage recipes: never silently turn wood into workbenches. - boolean reverse=all.stream().anyMatch(r->{var parts=ingredients(r);return parts.size()==1&&matches(parts.getFirst(),result)&&r.getResult().getType()==item.getType()&&r.getResult().getAmount()==cost;}); - if(reverse){var output=result.clone();if(jarvis!=null)jarvis.getClass().getMethod("markCreatedItem",ItemStack.class).invoke(jarvis,output);return new Compression(output,cost);} - } - return null; - } - private int condense(Player p)throws Exception{ - var inventory=p.getInventory();var contents=inventory.getStorageContents();var seen=new ArrayList();int blocks=0; - for(var sample:contents){if(sample==null||sample.isEmpty()||seen.stream().anyMatch(i->i.isSimilar(sample)))continue;seen.add(sample.clone());var rule=compression(sample);if(rule==null)continue; - int count=Arrays.stream(contents).filter(i->i!=null&&i.isSimilar(sample)).mapToInt(ItemStack::getAmount).sum(),made=count/rule.cost();if(made==0)continue; - var temporary=Bukkit.createInventory(null,36);temporary.setContents(Arrays.stream(contents).map(i->i==null?null:i.clone()).toArray(ItemStack[]::new));int remaining=made*rule.cost(); - for(int slot=0;slot<36&&remaining>0;slot++){var item=temporary.getItem(slot);if(item==null||!item.isSimilar(sample))continue;int take=Math.min(item.getAmount(),remaining);item.setAmount(item.getAmount()-take);temporary.setItem(slot,item.isEmpty()?null:item);remaining-=take;} - var output=rule.result().clone();output.setAmount(made);if(!temporary.addItem(output).isEmpty())continue; - contents=temporary.getContents();blocks+=made; - } - inventory.setStorageContents(contents);return blocks; - } - private static int repair(Player p){int count=0;for(int slot=0;slot0){damage.setDamage(0);item.setItemMeta(meta);p.getInventory().setItem(slot,item);count++;}}return count;} - @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){ - if(!(sender instanceof Player p))return true;if(!p.hasPermission("dune.admin")){p.sendMessage("This command is for staff.");return true;}if(args.length!=0){p.sendMessage("/"+command.getName());return true;} - try{var core=Bukkit.getPluginManager().getPlugin("DuneCore");if(core==null||!core.isEnabled())throw new IllegalStateException("Shared inventory unavailable. Nothing changed.");int[] count={0};Consumer action=connection->{try{count[0]=command.getName().equals("fix")?repair(p):condense(p);}catch(Exception e){throw new java.util.concurrent.CompletionException(e);}};core.getClass().getMethod("transactNetworkInventory",Player.class,Consumer.class).invoke(core,p,action);p.sendMessage(command.getName().equals("fix")?"Repaired "+count[0]+" items.":"Created "+count[0]+" condensed items.");} - catch(Exception e){Throwable cause=e instanceof InvocationTargetException?e.getCause():e;plugin.getLogger().warning("Staff inventory operation failed: "+cause.getClass().getSimpleName());p.sendMessage("Inventory operation could not be confirmed. Reopen your inventory before retrying.");} - return true; - } -} diff --git a/DuneEss/src/main/resources/config.yml b/DuneEss/src/main/resources/config.yml deleted file mode 100644 index 38695e3c..00000000 --- a/DuneEss/src/main/resources/config.yml +++ /dev/null @@ -1,24 +0,0 @@ -currency: - singular: Dunemark - plural: Dunemarks - spice-price: 15 - travel-price: 100 - starting-balance: 0 - allow-negative-balances: true - -# DuneEss automatically reuses DuneCore's existing PostgreSQL settings when enabled. -# Set use-core-database to false to use local balances.yml storage instead. -database: - use-core-database: true - -network: - use-core-settings: true - enabled: true - local-planet: arrakis - servers: {} - -worlds: [arrakis, giedi_prime, kaitain, caladan, sigma_draconis_iv] - -# Homes are local to each backend. Vanilla bed/anchor respawns remain authoritative. -essentials: - max-homes: 3 diff --git a/DuneEss/src/main/resources/plugin.yml b/DuneEss/src/main/resources/plugin.yml deleted file mode 100644 index 3aaad2ca..00000000 --- a/DuneEss/src/main/resources/plugin.yml +++ /dev/null @@ -1,72 +0,0 @@ -name: DuneEss -version: 1.0.12 -main: com.example.duneess.DuneEss -api-version: '1.21.8' -depend: [Vault] -softdepend: [floodgate, ViaVersion, DuneCore, DuneTerrain] -prefix: DuneRealms Essentials -description: DuneRealms Essentials - Dunemarks economy, Vault provider, spice sales, and Arrakduin travel -commands: - dune: - description: DuneRealms commands - usage: /dune help - condense: - description: Compress matching resources into storage blocks - permission: dune.admin - fix: - description: Repair every damaged item in your inventory and equipment - permission: dune.admin - communitycode: - description: Claim one community currency reward per UUID and monthly goal - usage: /communitycode - linkwebsite: - description: Verify your Minecraft UUID for a website account - usage: /linkwebsite - exchange: - description: CHOAM interplanetary player marketplace - usage: /exchange - aliases: [choam, market] - duneess: - description: Solaris, travel, and Arrakis administration - usage: /duneess help - aliases: [dess] - essentials: - description: Open DuneRealms Essentials - permission: duneess.basics - rescue: - description: Emergency teleport and heal for 1,000 DM - usage: /rescue - home: - description: Teleport to a saved home on your current world - usage: /home [world] [name] - permission: duneess.basics - sethome: - description: Save a named home on your current world - usage: /sethome [world] [name] - permission: duneess.basics - delhome: - description: Remove a named home - permission: duneess.basics - homes: - description: Choose a saved home - permission: duneess.basics - tpa: - description: Request player teleportation - permission: duneess.basics - tpaccept: - description: Accept a teleport request - permission: duneess.basics - tpdeny: - description: Decline a teleport request - permission: duneess.basics - spawn: - description: Return to world spawn - permission: duneess.basics - server: - description: Open Guild server travel - permission: duneess.basics -permissions: - duneess.basics: - default: true - dune.admin: - default: op diff --git a/DuneEss/src/main/resources/website-bridge.yml b/DuneEss/src/main/resources/website-bridge.yml deleted file mode 100644 index 35404fc4..00000000 --- a/DuneEss/src/main/resources/website-bridge.yml +++ /dev/null @@ -1,3 +0,0 @@ -origin: https://cp.dunerealms.com -# Operator secret shared with the account panel. Never publish or put it in command arguments. -secret: '' diff --git a/DuneEss/src/test/java/com/example/duneess/CommunityLedgerTest.java b/DuneEss/src/test/java/com/example/duneess/CommunityLedgerTest.java deleted file mode 100644 index 7fb2514b..00000000 --- a/DuneEss/src/test/java/com/example/duneess/CommunityLedgerTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.example.duneess; - -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import java.nio.file.*; -import java.util.*; -import java.util.logging.Logger; -import static org.mockito.Mockito.*; -import static org.junit.jupiter.api.Assertions.*; - -class CommunityLedgerTest { - @TempDir Path directory; - DuneEss plugin(){DuneEss plugin=mock(DuneEss.class);when(plugin.getDataFolder()).thenReturn(directory.resolve("DuneEss").toFile());when(plugin.getConfig()).thenReturn(new YamlConfiguration());when(plugin.getLogger()).thenReturn(Logger.getAnonymousLogger());return plugin;} - @Test void creditsOnceAcrossRestartAndRetainsReceiptUntilAcknowledged() throws Exception { - DuneEss plugin=plugin();UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid);String receipt="a".repeat(64); - DuneEconomy first=new DuneEconomy(plugin);assertTrue(first.grantCommunity(uuid,"2026-10",50,receipt));assertEquals(50,first.getBalance(player)); - first.add(uuid,10);assertEquals(60,first.getBalance(player)); - DuneEconomy restarted=new DuneEconomy(plugin);assertFalse(restarted.grantCommunity(uuid,"2026-10",50,receipt));assertEquals(60,restarted.getBalance(player));assertEquals(List.of(receipt),restarted.pendingCommunityReceipts().get(uuid)); - assertThrows(Exception.class,()->restarted.grantCommunity(uuid,"2026-10",50,"b".repeat(64))); - restarted.acknowledgeCommunity(uuid,receipt);assertTrue(new DuneEconomy(plugin).pendingCommunityReceipts().isEmpty()); - assertTrue(restarted.grantCommunity(uuid,"2026-11",50,"c".repeat(64)));assertEquals(110,restarted.getBalance(player)); - } - @Test void failedDurableWriteDoesNotCreditOrConsumeTheReward() throws Exception { - DuneEss plugin=plugin();DuneEconomy ledger=new DuneEconomy(plugin);UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid); - Path blocker=directory.resolve("DuneEss/balances.yml.community-tmp");Files.createDirectory(blocker); - assertThrows(Exception.class,()->ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64)));assertEquals(0,ledger.getBalance(player));assertTrue(ledger.pendingCommunityReceipts().isEmpty()); - Files.delete(blocker);assertTrue(ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64)));assertEquals(50,ledger.getBalance(player)); - } - @Test void incompleteSharedConfigurationCannotCreateASecondLocalWallet() throws Exception { - Files.createDirectories(directory.resolve("DuneCore"));YamlConfiguration core=new YamlConfiguration();core.set("database.enabled",true);core.set("database.jdbc-url","");core.save(directory.resolve("DuneCore/config.yml").toFile()); - DuneEconomy ledger=new DuneEconomy(plugin());UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid); - assertFalse(ledger.depositPlayer(player,50).transactionSuccess());assertEquals(0,ledger.getBalance(player)); - assertThrows(Exception.class,()->ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64))); - } -} diff --git a/DuneEss/src/test/java/com/example/duneess/DuneCommandsTest.java b/DuneEss/src/test/java/com/example/duneess/DuneCommandsTest.java deleted file mode 100644 index f015c5e0..00000000 --- a/DuneEss/src/test/java/com/example/duneess/DuneCommandsTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.example.duneess; - -import org.bukkit.Server; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.plugin.Plugin; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - -import static org.mockito.Mockito.*; - -class DuneCommandsTest { - @Test void forwardsNamespacedCommandsWithOriginalSenderAndArguments() { - var plugin = mock(DuneEss.class); - var server = mock(Server.class); - var root = mock(PluginCommand.class); - var sender = mock(CommandSender.class); - var enabledPlugin = mock(Plugin.class); - when(plugin.getServer()).thenReturn(server); - when(plugin.getCommand("dune")).thenReturn(root); - when(enabledPlugin.isEnabled()).thenReturn(true); - var invite = destination(server, enabledPlugin, "jarvistranslator:invite"); - var pay = destination(server, enabledPlugin, "jarvistranslator:pay"); - var home = destination(server, enabledPlugin, "duneess:home"); - var house = destination(server, enabledPlugin, "dunemenus:house"); - var menu = destination(server, enabledPlugin, "dunemenus:dm"); - var core = destination(server, enabledPlugin, "dunecore:dune"); - - DuneCommands.register(plugin); - var executor = ArgumentCaptor.forClass(CommandExecutor.class); - verify(root).setExecutor(executor.capture()); - var router = executor.getValue(); - router.onCommand(sender, root, "dune", new String[]{"clan", "invite", "Yooshi"}); - router.onCommand(sender, root, "dune", new String[]{"pay", "Yooshi", "12.50", "for", "storage"}); - router.onCommand(sender, root, "dune", new String[]{"home", "sietch"}); - router.onCommand(sender, root, "dune", new String[]{"faction"}); - router.onCommand(sender, root, "dune", new String[]{"menu", "travel"}); - router.onCommand(sender, root, "dune", new String[]{"summon", "sandworm"}); - - verify(invite).execute(sender, "dune clan invite", new String[]{"Yooshi"}); - verify(pay).execute(sender, "dune pay", new String[]{"Yooshi", "12.50", "for", "storage"}); - verify(home).execute(sender, "dune home", new String[]{"sietch"}); - verify(house).execute(sender, "dune faction", new String[0]); - verify(menu).execute(sender, "dune menu", new String[]{"travel"}); - verify(core).execute(sender, "dune", new String[]{"summon", "sandworm"}); - verify(server, never()).getPluginCommand("invite"); - } - - private PluginCommand destination(Server server, Plugin plugin, String name) { - var command = mock(PluginCommand.class); - when(command.getPlugin()).thenReturn(plugin); - when(server.getPluginCommand(name)).thenReturn(command); - return command; - } -} diff --git a/DuneEss/src/test/java/com/example/duneess/DunemarkDenominationsTest.java b/DuneEss/src/test/java/com/example/duneess/DunemarkDenominationsTest.java deleted file mode 100644 index 9e3acfbc..00000000 --- a/DuneEss/src/test/java/com/example/duneess/DunemarkDenominationsTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.example.duneess; -import com.example.dunegui.DunemarkItems; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; -class DunemarkDenominationsTest { - @Test void walletArtSelectsOnlySupportedDenominationsWithoutRoundingUp(){ - assertEquals(1,DunemarkItems.denomination(0)); assertEquals(1,DunemarkItems.denomination(4.99)); - assertEquals(5,DunemarkItems.denomination(5)); assertEquals(5,DunemarkItems.denomination(99.99)); - assertEquals(100,DunemarkItems.denomination(100));assertEquals(1000,DunemarkItems.denomination(4999.99)); - assertEquals(5000,DunemarkItems.denomination(5000)); - } -} diff --git a/DuneEss/src/test/java/com/example/duneess/EssentialsBasicsTest.java b/DuneEss/src/test/java/com/example/duneess/EssentialsBasicsTest.java deleted file mode 100644 index b6b60cad..00000000 --- a/DuneEss/src/test/java/com/example/duneess/EssentialsBasicsTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.example.duneess; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; -class EssentialsBasicsTest { - @Test void normalizesNamesAndHasAStableDefault() { - assertEquals("home",EssentialsBasics.homeName(new String[]{})); - assertEquals("sietch_2",EssentialsBasics.homeName(new String[]{"Sietch_2"})); - } - @Test void rejectsYamlPathsAndInvalidArguments() { - for(String name:new String[]{"../other","player.home","","a b","x".repeat(25)}) - assertThrows(IllegalArgumentException.class,()->EssentialsBasics.homeName(new String[]{name})); - assertThrows(IllegalArgumentException.class,()->EssentialsBasics.homeName(new String[]{"one","two"})); - } - - @org.junit.jupiter.api.io.TempDir java.nio.file.Path directory; - @Test void teleportRequestsRequireConsentAndCannotBeAcceptedTwice() { - DuneEss plugin=org.mockito.Mockito.mock(DuneEss.class); - org.mockito.Mockito.when(plugin.getDataFolder()).thenReturn(directory.toFile()); - EssentialsBasics basics=new EssentialsBasics(plugin); - var source=org.mockito.Mockito.mock(org.bukkit.entity.Player.class); - var target=org.mockito.Mockito.mock(org.bukkit.entity.Player.class); - var world=org.mockito.Mockito.mock(org.bukkit.World.class); - var border=org.mockito.Mockito.mock(org.bukkit.WorldBorder.class); - var request=org.mockito.Mockito.mock(org.bukkit.command.Command.class); - var accept=org.mockito.Mockito.mock(org.bukkit.command.Command.class); - java.util.UUID senderId=java.util.UUID.randomUUID(), targetId=java.util.UUID.randomUUID(); - org.mockito.Mockito.when(source.getUniqueId()).thenReturn(senderId); - org.mockito.Mockito.when(target.getUniqueId()).thenReturn(targetId); - org.mockito.Mockito.when(source.getName()).thenReturn("Sender"); - org.mockito.Mockito.when(source.hasPermission("duneess.basics")).thenReturn(true); - org.mockito.Mockito.when(target.hasPermission("duneess.basics")).thenReturn(true); - org.mockito.Mockito.when(source.canSee(target)).thenReturn(true); - org.mockito.Mockito.when(source.getWorld()).thenReturn(world); - org.mockito.Mockito.when(target.getWorld()).thenReturn(world); - org.mockito.Mockito.when(source.isOnline()).thenReturn(true); - org.mockito.Mockito.when(world.getWorldBorder()).thenReturn(border); - org.mockito.Mockito.when(border.isInside(org.mockito.ArgumentMatchers.any())).thenReturn(true); - org.mockito.Mockito.when(world.getMinHeight()).thenReturn(-64); - org.mockito.Mockito.when(world.getMaxHeight()).thenReturn(320); - var destination=new org.bukkit.Location(world,10,80,10); - org.mockito.Mockito.when(target.getLocation()).thenReturn(destination); - org.mockito.Mockito.when(source.teleportAsync(destination)).thenReturn(java.util.concurrent.CompletableFuture.completedFuture(true)); - org.mockito.Mockito.when(request.getName()).thenReturn("tpa"); - org.mockito.Mockito.when(accept.getName()).thenReturn("tpaccept"); - try(var bukkit=org.mockito.Mockito.mockStatic(org.bukkit.Bukkit.class)) { - bukkit.when(()->org.bukkit.Bukkit.getPlayerExact("Target")).thenReturn(target); - bukkit.when(()->org.bukkit.Bukkit.getPlayer(senderId)).thenReturn(source); - basics.onCommand(source,request,"tpa",new String[]{"Target"}); - org.mockito.Mockito.verify(source,org.mockito.Mockito.never()).teleportAsync(org.mockito.ArgumentMatchers.any(org.bukkit.Location.class)); - basics.onCommand(target,accept,"tpaccept",new String[]{}); - basics.onCommand(target,accept,"tpaccept",new String[]{}); - org.mockito.Mockito.verify(source,org.mockito.Mockito.times(1)).teleportAsync(destination); - } - } -} diff --git a/DuneEss/src/test/java/com/example/duneess/ExchangeMenuTest.java b/DuneEss/src/test/java/com/example/duneess/ExchangeMenuTest.java deleted file mode 100644 index e99788bf..00000000 --- a/DuneEss/src/test/java/com/example/duneess/ExchangeMenuTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.example.duneess; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.*; -import org.bukkit.inventory.*; -import org.bukkit.scheduler.BukkitScheduler; -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - -class ExchangeMenuTest { - @Test void ordinaryInventoriesAreNeverHijackedByTitle() { - ExchangeMenu menu=new ExchangeMenu(mock(DuneEss.class)); - InventoryClickEvent click=mock(InventoryClickEvent.class); - InventoryView view=mock(InventoryView.class);Inventory inventory=mock(Inventory.class); - when(click.getView()).thenReturn(view);when(view.getTopInventory()).thenReturn(inventory); - menu.click(click);verify(click,never()).setCancelled(anyBoolean()); - } - @Test void bottomInventoryTransfersAndDragsAreCancelledWithoutRunningAnAction() { - ExchangeMenu menu=new ExchangeMenu(mock(DuneEss.class));UUID owner=UUID.randomUUID(); - ExchangeMenu.Screen screen=new ExchangeMenu.Screen(owner); - Inventory top=mock(Inventory.class),bottom=mock(Inventory.class);InventoryView view=mock(InventoryView.class); - screen.inventory=top;when(top.getHolder()).thenReturn(screen);when(view.getTopInventory()).thenReturn(top); - Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(owner); - InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getView()).thenReturn(view); - when(click.getWhoClicked()).thenReturn(player);when(click.getClickedInventory()).thenReturn(bottom); - AtomicInteger actions=new AtomicInteger();screen.actions.put(10,actions::incrementAndGet); - menu.click(click);verify(click).setCancelled(true);assertEquals(0,actions.get()); - InventoryDragEvent drag=mock(InventoryDragEvent.class);when(drag.getView()).thenReturn(view); - menu.drag(drag);verify(drag).setCancelled(true); - } - @Test void queuedSecondConfirmationCannotExecuteAfterFirstClosesScreen() { - DuneEss plugin=mock(DuneEss.class);ExchangeMenu menu=new ExchangeMenu(plugin); - UUID owner=UUID.randomUUID();ExchangeMenu.Screen screen=new ExchangeMenu.Screen(owner); - Inventory top=mock(Inventory.class),closed=mock(Inventory.class);screen.inventory=top; - InventoryView view=mock(InventoryView.class);when(view.getTopInventory()).thenReturn(top); - when(top.getHolder()).thenReturn(screen); - Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(owner);when(player.isOnline()).thenReturn(true); - when(player.getOpenInventory()).thenReturn(view); - InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getView()).thenReturn(view); - when(click.getWhoClicked()).thenReturn(player);when(click.getClickedInventory()).thenReturn(top); - when(click.getClick()).thenReturn(ClickType.LEFT);when(click.getRawSlot()).thenReturn(30); - AtomicInteger actions=new AtomicInteger();screen.actions.put(30,()->{actions.incrementAndGet();when(view.getTopInventory()).thenReturn(closed);}); - BukkitScheduler scheduler=mock(BukkitScheduler.class);List queued=new ArrayList<>(); - try(MockedStatic bukkit=mockStatic(Bukkit.class)) { - bukkit.when(Bukkit::getScheduler).thenReturn(scheduler); - when(scheduler.runTask(eq(plugin),any(Runnable.class))).thenAnswer(invocation->{queued.add(invocation.getArgument(1));return null;}); - menu.click(click);menu.click(click);queued.forEach(Runnable::run); - } - assertEquals(1,actions.get()); - } - @Test void administratorCommandRechecksPermission() { - ExchangeMenu menu=new ExchangeMenu(mock(DuneEss.class));Player player=mock(Player.class); - assertTrue(menu.onCommand(player,null,"exchange",new String[]{"admin"})); - verify(player).sendMessage(contains("Operators only")); - } -} diff --git a/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java b/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java deleted file mode 100644 index 399f87e2..00000000 --- a/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.example.duneess; - -import org.junit.jupiter.api.*; -import java.math.BigDecimal; -import java.sql.*; -import java.util.*; -import java.util.concurrent.*; -import static org.junit.jupiter.api.Assertions.*; - -class ExchangeStoreTest { - private String url; - private ExchangeStore store; - private final UUID seller=UUID.randomUUID(),buyer=UUID.randomUUID(); - @BeforeEach void setup() throws Exception { - url="jdbc:h2:mem:"+UUID.randomUUID()+";MODE=PostgreSQL;DB_CLOSE_DELAY=-1"; - store=new ExchangeStore(()->DriverManager.getConnection(url)); - try(Connection c=DriverManager.getConnection(url);Statement s=c.createStatement()) { - s.execute("CREATE TABLE dune_economy_balances(uuid UUID PRIMARY KEY,balance NUMERIC(20,2) NOT NULL)"); - } - wallet(seller,"0"); wallet(buyer,"100"); store.initialize(); store.initialize(); - } - private void wallet(UUID id,String amount) throws SQLException { - try(Connection c=DriverManager.getConnection(url);PreparedStatement q=c.prepareStatement("INSERT INTO dune_economy_balances VALUES(?,?)")) { - q.setObject(1,id);q.setBigDecimal(2,new BigDecimal(amount));q.executeUpdate(); - } - } - private BigDecimal balance(UUID id) throws SQLException { - try(Connection c=DriverManager.getConnection(url);PreparedStatement q=c.prepareStatement("SELECT balance FROM dune_economy_balances WHERE uuid=?")) { - q.setObject(1,id);try(ResultSet r=q.executeQuery()){assertTrue(r.next());return r.getBigDecimal(1);} - } - } - private long listing(int amount,String price) throws SQLException { - store.list(seller,"Seller","arrakis","spice","ORANGE_DYE",amount,new BigDecimal(price),"preserved-payload","Melange"); - return store.browse("all","all",null,0).getFirst().id(); - } - @Test void finalItemIsDeletedAndBothWalletsChangeExactlyOnce() throws Exception { - long id=listing(1,"12.50"); - assertEquals("preserved-payload",store.buy(buyer,id).payload()); - assertEquals(new BigDecimal("87.50"),balance(buyer)); - assertEquals(new BigDecimal("12.50"),balance(seller)); - assertTrue(store.browse("all","all",null,0).isEmpty()); - assertThrows(IllegalArgumentException.class,()->store.buy(buyer,id)); - assertEquals(new BigDecimal("87.50"),balance(buyer)); - } - @Test void partiallyFilledStockRemainsAndCancellationReturnsOnlyUnsoldQuantity() throws Exception { - long id=listing(3,"10");store.buy(buyer,id); - assertEquals(2,store.find(id).quantity()); - assertEquals(2,store.cancel(seller,id).quantity()); - assertTrue(store.browse("all","all",null,0).isEmpty()); - assertEquals(new BigDecimal("10.00"),balance(seller)); - } - @Test void insufficientFundsAndSelfPurchaseCannotChangeStock() throws Exception { - long id=listing(2,"101"); - assertThrows(IllegalArgumentException.class,()->store.buy(buyer,id)); - assertThrows(IllegalArgumentException.class,()->store.buy(seller,id)); - assertEquals(2,store.find(id).quantity());assertEquals(new BigDecimal("100.00"),balance(buyer)); - } - @Test void wrongOwnerCannotCancelOrReclaim() throws Exception { - long id=listing(2,"1"); - assertThrows(IllegalArgumentException.class,()->store.cancel(buyer,id)); - assertEquals(2,store.find(id).quantity()); - } - @Test void failedSellerCreditRollsBackBuyerDebit() throws Exception { - long id=listing(1,"10"); - try(Connection c=DriverManager.getConnection(url);PreparedStatement q=c.prepareStatement("DELETE FROM dune_economy_balances WHERE uuid=?")) { - q.setObject(1,seller);q.executeUpdate(); - } - assertThrows(IllegalArgumentException.class,()->store.buy(buyer,id)); - assertEquals(new BigDecimal("100.00"),balance(buyer));assertEquals(1,store.find(id).quantity()); - } - @Test void filtersAndPaginationIncludeAllCategoriesWithoutEmptyCategoryPredicate() throws Exception { - listing(1,"1"); - store.list(seller,"Seller","caladan","building","OAK_LOG",64,new BigDecimal("2"),null,null); - assertEquals(2,store.browse("all","all",null,0).size()); - assertEquals(1,store.browse("spice","arrakis",null,0).size()); - assertTrue(store.browse("spice","caladan",null,0).isEmpty()); - assertTrue(store.browse("all","all",buyer,0).isEmpty()); - for(int i=0;i<30;i++) listing(1,"1"); - assertEquals(29,store.browse("all","all",seller,0).size()); - assertEquals(4,store.browse("all","all",seller,1).size()); - } - @Test void concurrentBuyersCannotBothBuyTheLastItem() throws Exception { - UUID other=UUID.randomUUID(); wallet(other,"100");long id=listing(1,"25"); - try(ExecutorService pool=Executors.newFixedThreadPool(2)) { - CountDownLatch start=new CountDownLatch(1); - List> results=new ArrayList<>(); - for(UUID player:List.of(buyer,other)) results.add(pool.submit(()->{ - start.await();try{store.buy(player,id);return true;}catch(IllegalArgumentException ex){return false;} - })); - start.countDown();int successes=0;for(Future result:results)if(result.get(5,TimeUnit.SECONDS)) successes++; - assertEquals(1,successes);assertEquals(new BigDecimal("25.00"),balance(seller)); - assertEquals(new BigDecimal("175.00"),balance(buyer).add(balance(other))); - } - } - @Test void invalidAmountsAndPricesAreRejectedBeforeWriting() { - for(String price:List.of("0","-1","1000001","0.001")) - assertThrows(IllegalArgumentException.class,()->listing(1,price)); - assertThrows(IllegalArgumentException.class,()->listing(0,"1")); - assertThrows(IllegalArgumentException.class,()->listing(65,"1")); - } - @Test void committedSaleRecordsBuyerItemAndExactPaymentButFailuresDoNot() throws Exception { - long id=listing(2,"12.50");store.buy(buyer,"BuyerName",id); - try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT * FROM dune_exchange_sales")) { - assertTrue(r.next());assertEquals(seller,r.getObject("seller",UUID.class)); - assertEquals(buyer,r.getObject("buyer",UUID.class));assertEquals("BuyerName",r.getString("buyer_name")); - assertEquals(1,r.getInt("quantity"));assertEquals(new BigDecimal("12.50"),r.getBigDecimal("total_price"));assertFalse(r.next()); - } - assertThrows(IllegalArgumentException.class,()->store.buy(seller,id));store.cancel(seller,id); - try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT COUNT(*) FROM dune_exchange_sales")) { - assertTrue(r.next());assertEquals(1,r.getInt(1)); - } - } - @Test void externallyOwnedTransactionRollsBackStockWalletsAndHistoryTogether() throws Exception { - long id=listing(1,"25"); - try(Connection c=DriverManager.getConnection(url)) { - c.setAutoCommit(false);ExchangeStore.bound(c).buy(buyer,"Buyer",id); - assertFalse(c.isClosed());c.rollback(); - } - assertEquals(1,store.find(id).quantity());assertEquals(new BigDecimal("100.00"),balance(buyer)); - assertEquals(new BigDecimal("0.00"),balance(seller)); - try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT COUNT(*) FROM dune_exchange_sales")) { - assertTrue(r.next());assertEquals(0,r.getInt(1)); - } - } -} diff --git a/DuneEss/src/test/java/com/example/duneess/PersonalHomeTravelTest.java b/DuneEss/src/test/java/com/example/duneess/PersonalHomeTravelTest.java deleted file mode 100644 index d95033c6..00000000 --- a/DuneEss/src/test/java/com/example/duneess/PersonalHomeTravelTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.example.duneess; -import org.bukkit.*;import org.bukkit.entity.Player;import org.bukkit.plugin.java.JavaPlugin;import org.bukkit.plugin.PluginManager;import org.bukkit.scheduler.BukkitScheduler; -import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import org.mockito.MockedStatic; -import java.nio.file.*;import java.util.*;import java.util.concurrent.CompletableFuture; -import com.google.gson.*; -import static org.mockito.Mockito.*;import static org.mockito.ArgumentMatchers.*;import static org.junit.jupiter.api.Assertions.*; - -class PersonalHomeTravelTest { - @TempDir Path directory; - public static class Connector extends JavaPlugin{public String requestHome(UUID id,String body)throws Exception{return null;}} - @Test void waitsFiveSecondsAndKeepsOneDeliveryUntilActualTeleportAndBankReceipt()throws Exception{ - try(var f=new Fixture(directory)){ - var travel=new PersonalHomeTravel(f.plugin);travel.begin(f.player,f.location); - assertEquals(100L,f.delay);verify(f.connector,never()).requestHome(any(),any());assertFalse(Files.exists(directory.resolve("home-journeys.yml"))); - f.delayed.remove().run();assertTrue(Files.exists(directory.resolve("home-journeys.yml")));f.asynchronous.remove().run();f.main.remove().run(); - verify(f.player).teleportAsync(f.location);f.periodic.getFirst().run();assertEquals(0,f.asynchronous.size()); - f.teleport.complete(true);f.main.remove().run();f.asynchronous.remove().run();f.main.remove().run(); - assertEquals(List.of("reserve","arrive"),f.calls.stream().map(q->q.get("action").getAsString()).toList()); - assertEquals(f.calls.get(0).get("requestId"),f.calls.get(1).get("requestId")); - assertFalse(org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(directory.resolve("home-journeys.yml").toFile()).contains(f.id.toString())); - } - } - @Test void lostReplyRecoversSameReferenceAndOfflinePlayerCancelsWithoutTeleport()throws Exception{ - try(var f=new Fixture(directory)){ - var travel=new PersonalHomeTravel(f.plugin);doThrow(new java.io.IOException("lost reply")).doAnswer(f::respond).when(f.connector).requestHome(any(),any()); - travel.begin(f.player,f.location);f.delayed.remove().run();f.asynchronous.remove().run();f.main.remove().run(); - var saved=org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(directory.resolve("home-journeys.yml").toFile()).getString(f.id+".requestId"); - when(f.player.isOnline()).thenReturn(false);f.periodic.getFirst().run();f.asynchronous.remove().run();f.main.remove().run(); - f.periodic.getFirst().run();f.asynchronous.remove().run();f.main.remove().run(); - verify(f.player,never()).teleportAsync(any(Location.class));assertEquals(List.of("reserve","cancel"),f.calls.stream().map(q->q.get("action").getAsString()).toList());assertEquals(saved,f.calls.getFirst().get("requestId").getAsString()); - } - } - @Test void differentWorldAndUnavailableHomesNeverReachBank()throws Exception{ - try(var f=new Fixture(directory)){ - var travel=new PersonalHomeTravel(f.plugin);var other=mock(World.class);var border=f.world.getWorldBorder();when(other.getWorldBorder()).thenReturn(border);when(other.getMinHeight()).thenReturn(-64);when(other.getMaxHeight()).thenReturn(320); - travel.begin(f.player,null);travel.begin(f.player,new Location(other,0,70,0));assertTrue(f.delayed.isEmpty());verify(f.connector,never()).requestHome(any(),any()); - } - } - class Fixture implements AutoCloseable{ - final JavaPlugin plugin=mock(JavaPlugin.class);final Connector connector=mock(Connector.class);final Player player=mock(Player.class);final UUID id=UUID.randomUUID(); - final World world=mock(World.class);final Location location=new Location(world,1,70,2);final CompletableFuture teleport=new CompletableFuture<>(); - final Queue delayed=new ArrayDeque<>(),asynchronous=new ArrayDeque<>(),main=new ArrayDeque<>();final List periodic=new ArrayList<>();final List calls=new ArrayList<>();long delay; - final MockedStatic bukkit=mockStatic(Bukkit.class); - Fixture(Path directory)throws Exception{ - when(plugin.getDataFolder()).thenReturn(directory.toFile());when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger()); - when(world.getUID()).thenReturn(UUID.randomUUID());when(world.getName()).thenReturn("test_world");when(world.getMinHeight()).thenReturn(-64);when(world.getMaxHeight()).thenReturn(320);var border=mock(WorldBorder.class);when(world.getWorldBorder()).thenReturn(border);when(border.isInside(any())).thenReturn(true); - when(player.getUniqueId()).thenReturn(id);when(player.getWorld()).thenReturn(world);when(player.isOnline()).thenReturn(true);when(player.teleportAsync(any(Location.class))).thenReturn(teleport); - var manager=mock(PluginManager.class);when(manager.getPlugin("JarvisTranslator")).thenReturn(connector);when(connector.isEnabled()).thenReturn(true);doAnswer(this::respond).when(connector).requestHome(any(),any()); - var scheduler=mock(BukkitScheduler.class);when(scheduler.runTaskTimer(eq(plugin),any(Runnable.class),anyLong(),anyLong())).thenAnswer(a->{periodic.add(a.getArgument(1));return null;}); - when(scheduler.runTaskLater(eq(plugin),any(Runnable.class),anyLong())).thenAnswer(a->{delay=a.getArgument(2);delayed.add(a.getArgument(1));return null;}); - when(scheduler.runTaskAsynchronously(eq(plugin),any(Runnable.class))).thenAnswer(a->{asynchronous.add(a.getArgument(1));return null;});when(scheduler.runTask(eq(plugin),any(Runnable.class))).thenAnswer(a->{main.add(a.getArgument(1));return null;}); - bukkit.when(Bukkit::getPluginManager).thenReturn(manager);bukkit.when(Bukkit::getScheduler).thenReturn(scheduler);bukkit.when(()->Bukkit.getPlayer(id)).thenReturn(player);bukkit.when(()->Bukkit.getWorld("test_world")).thenReturn(world); - } - Object respond(org.mockito.invocation.InvocationOnMock a){var q=JsonParser.parseString(a.getArgument(1,String.class)).getAsJsonObject();calls.add(q);return "{\"ok\":true,\"state\":\""+(q.get("action").getAsString().equals("reserve")?"pending":q.get("action").getAsString().equals("arrive")?"arrived":"cancelled")+"\"}";} - public void close(){bukkit.close();} - } -} diff --git a/DuneEss/src/test/java/com/example/duneess/PlanetNamesTest.java b/DuneEss/src/test/java/com/example/duneess/PlanetNamesTest.java deleted file mode 100644 index ae60b604..00000000 --- a/DuneEss/src/test/java/com/example/duneess/PlanetNamesTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.example.duneess; -import com.example.dunegui.PlanetSigils; -import com.example.dunegui.PublicNames; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; -class PlanetNamesTest { - @Test void newDisplayNamesRetainSavedIdentifiersAndFullCapitalization(){ - assertEquals("Arrakduin",PlanetSigils.label("arrakis"));assertEquals("Kaladam",PlanetSigils.label("caladan")); - assertEquals("Giedermark",PlanetSigils.label("giedi_prime"));assertEquals("Kaiterhof",PlanetSigils.label("kaitain")); - assertEquals("Sigmadraken IV",PlanetSigils.label("sigma_draconis_iv")); - assertEquals("arrakis_world_id",PublicNames.text("arrakis_world_id")); - assertEquals("/duneess travel arrakis",PublicNames.text("/duneess travel arrakis")); - assertEquals("Arrakduin and Kaladam",PublicNames.text("Serevan and Pelareth")); - } -} diff --git a/DuneEss/src/test/java/com/example/dunegui/MenuSessionTest.java b/DuneEss/src/test/java/com/example/dunegui/MenuSessionTest.java deleted file mode 100644 index 9948a5ac..00000000 --- a/DuneEss/src/test/java/com/example/dunegui/MenuSessionTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.example.dunegui; -import org.junit.jupiter.api.Test; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; -class MenuSessionTest { - @Test void rejectsAnotherPlayerWithoutConsumingTheOwnerAction() { - UUID owner=UUID.randomUUID(); MenuSession session=new MenuSession(owner); - assertFalse(session.claim(UUID.randomUUID())); assertTrue(session.claim(owner)); assertFalse(session.claim(owner)); - } - @Test void openingANewMenuInvalidatesThePreviousConfirmation() { - UUID owner=UUID.randomUUID(); MenuSession old=new MenuSession(owner), next=new MenuSession(owner); - assertFalse(old.claim(owner)); assertTrue(next.claim(owner)); - } - @Test void expiringOldMenuDoesNotInvalidateTheNewMenu() { - UUID owner=UUID.randomUUID(); MenuSession old=new MenuSession(owner), next=new MenuSession(owner); - old.expire(); assertTrue(next.claim(owner)); - } - @Test void expiredMenuCannotTrade() { - UUID owner=UUID.randomUUID(); MenuSession session=new MenuSession(owner); session.expire(); assertFalse(session.claim(owner)); - } -} diff --git a/DuneFullscreenPaper/README.md b/DuneFullscreenPaper/README.md deleted file mode 100644 index 2a3361f2..00000000 --- a/DuneFullscreenPaper/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Optional Paper fullscreen roleplay provider - -DuneGit builds this provider as a separate development artifact. It requires Paper 26.2 build 135 and Java 25. Build `DuneRealmsGUI` first, then run `gradle -p DuneFullscreenPaper test jar` with Java 25 and Gradle 9.2.1. - -The Java Decisions dashboard uses this provider only for UUIDs listed under `development.fullscreen-decisions-viewers` in the DunerealmsGUI config. Quest dashboards, turn-ins and next-mission screens use `development.fullscreen-quest-viewers`. Branded organisation modules use `development.fullscreen-organisation-viewers`, Exchange browse, listing and kit shelves, plus loose-item and kit checkout, use `development.fullscreen-exchange-viewers`, and House or Mentat screens use `development.fullscreen-house-viewers`. Keep these allowlists empty on live servers. Existing menus handle unavailable providers, invalid card slots, documents outside the 54-card inventory limit, and quest text that exceeds the native layout. - -Larger documents retain their server-provided slots and show four entries per page in Decisions, quests and organisation modules, and six in Exchange and House views. The mounted view can still expose vanilla overlays such as the experience bar, crosshair, chat and system notifications. diff --git a/DuneFullscreenPaper/build.gradle.kts b/DuneFullscreenPaper/build.gradle.kts deleted file mode 100644 index 0b1b29c9..00000000 --- a/DuneFullscreenPaper/build.gradle.kts +++ /dev/null @@ -1,22 +0,0 @@ -plugins { - java - id("io.papermc.paperweight.userdev") version "2.0.0-beta.23" -} - -dependencies { - paperweight.paperDevBundle("26.2.build.135-stable") - compileOnly(files("../DuneMenus/build/libs/DuneMenus.jar")) - testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") - testRuntimeOnly("org.junit.platform:junit-platform-launcher") -} - -repositories { mavenCentral() } -// Teardown tests exercise the provider's lifecycle without bootstrapping a Paper server. -configurations.testRuntimeClasspath { - exclude(group = "io.papermc.paper", module = "dev-bundle") -} -tasks.test { useJUnitPlatform() } - -java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) } -tasks.withType().configureEach { options.encoding = "UTF-8" } -tasks.jar { archiveFileName.set("DuneFullscreenPaper.jar") } diff --git a/DuneFullscreenPaper/settings.gradle.kts b/DuneFullscreenPaper/settings.gradle.kts deleted file mode 100644 index baca26c0..00000000 --- a/DuneFullscreenPaper/settings.gradle.kts +++ /dev/null @@ -1,7 +0,0 @@ -pluginManagement { - repositories { - gradlePluginPortal() - maven("https://repo.papermc.io/repository/maven-public/") - } -} -rootProject.name = "DuneFullscreenPaper" diff --git a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/FullscreenProvider.java b/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/FullscreenProvider.java deleted file mode 100644 index f65c56ac..00000000 --- a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/FullscreenProvider.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.dunerealms.fullscreen; - -import com.dunerealms.services.DecisionsViewTransport; -import io.papermc.paper.ServerBuildInfo; -import org.bukkit.Bukkit; -import org.bukkit.plugin.ServicePriority; -import org.bukkit.plugin.java.JavaPlugin; - -public final class FullscreenProvider extends JavaPlugin { - private PaperDecisionsScene scenes; - - @Override - public void onEnable() { - var build = ServerBuildInfo.buildInfo(); - if (!build.minecraftVersionId().equals("26.2") || build.buildNumber().orElse(-1) != 135 || - !build.isBrandCompatible(ServerBuildInfo.BRAND_PAPER_ID)) { - getLogger().info("Fullscreen Decisions requires Paper 26.2 build 135."); - return; - } - try { - scenes = new PaperDecisionsScene(this); - Bukkit.getPluginManager().registerEvents(scenes, this); - Bukkit.getServicesManager().register(DecisionsViewTransport.class, scenes, this, ServicePriority.Normal); - com.dunerealms.menus.FullscreenProvider menus = (viewer, screen, select, close) -> { - var cards = new java.util.ArrayList(); - for (var card : screen.cards()) { - cards.add(new DecisionsViewTransport.Card(card.slot(), card.title(), card.lore(), true, card.material())); - } - int infoSlot = 54; - for (String line : screen.info()) { - cards.add(new DecisionsViewTransport.Card(infoSlot++, line, java.util.List.of(), false)); - } - return scenes.open(viewer, new DecisionsViewTransport.Document(screen.title(), screen.subtitle(), cards), select, close); - }; - Bukkit.getServicesManager().register(com.dunerealms.menus.FullscreenProvider.class, menus, this, ServicePriority.Normal); - } catch (LinkageError unavailable) { - getLogger().warning("Fullscreen Decisions runtime is unavailable: " + unavailable.getClass().getSimpleName()); - } - } - - @Override - public void onDisable() { - Bukkit.getServicesManager().unregisterAll(this); - if (scenes != null) scenes.close(); - } -} diff --git a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/PaperDecisionsScene.java b/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/PaperDecisionsScene.java deleted file mode 100644 index 115c6b5e..00000000 --- a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/PaperDecisionsScene.java +++ /dev/null @@ -1,1137 +0,0 @@ -package com.dunerealms.fullscreen; - -import com.dunerealms.services.DecisionsViewTransport; -import java.util.function.IntConsumer; - -import java.awt.Color; -import java.awt.Font; -import java.awt.BasicStroke; -import java.awt.image.BufferedImage; -import java.util.*; -import io.netty.buffer.Unpooled; -import io.netty.channel.*; -import net.minecraft.core.*; -import net.minecraft.core.component.DataComponents; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.game.*; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.decoration.*; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.saveddata.maps.*; -import net.minecraft.world.scores.DisplaySlot; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.craftbukkit.scoreboard.CraftScoreboard; -import org.bukkit.entity.Player; -import org.bukkit.event.*; -import org.bukkit.event.player.*; -import org.bukkit.map.MapPalette; -import org.bukkit.plugin.java.JavaPlugin; - -final class PaperDecisionsScene implements DecisionsViewTransport, Listener, AutoCloseable { - private static final String INPUT = "dune_fullscreen_decisions"; - private static final int COLS = 11, ROWS = 9; - private static final int STANDARD_PAGE = 4, THREE_COLUMN_PAGE = 6; - private static final int LAST_ROW = 5, LAST_CARD_HEIGHT = 64; - private static final int JOURNAL_WIDTH = 384; - private static final int JOURNAL_TEXT_WIDTH = 304; - private static final Font JOURNAL_TITLE = new Font(Font.SERIF, Font.BOLD, 24); - private static final Font JOURNAL_TEXT = new Font(Font.SANS_SERIF, Font.PLAIN, 16); - private static final Font CARD_TITLE = new Font(Font.SANS_SERIF, Font.BOLD, 17); - private static final Font CARD_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 13); - private static final int FULL_CARD_LORE_LINES = 5; - private static final Font FULL_CARD_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 12); - private static final Font CHECKOUT_TERMS = new Font(Font.SANS_SERIF, Font.BOLD, 15); - private static final Font COMPACT_CARD_TITLE = new Font(Font.SANS_SERIF, Font.BOLD, 13); - private static final Font COMPACT_CARD_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 11); - private static final Font SIDEBAR_TERMS = new Font(Font.SANS_SERIF, Font.PLAIN, 11); - private static final int SIDEBAR_TERMS_WIDTH = 108, SIDEBAR_TERMS_LINES = 16; - private static final Font ARCHIVE_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 12); - private static final int ARCHIVE_COLUMN_LINES = 7; - private static final int ARCHIVE_COLUMN_WIDTH = 177; - private static final int PREVIOUS = -1, NEXT = -2, EMPTY = -3; - private static final int CHECKOUT_BACK = 45, CHECKOUT_PRIMARY = 49, CHECKOUT_CONTROLS = 2; - private final Map scenes = new HashMap<>(); - private final JavaPlugin plugin; - // This range is private to each connection and reused on reopen to bound the client map cache. - private static final int FIRST_SCENE_MAP = 2_000_000_000; - - PaperDecisionsScene(JavaPlugin plugin) { - this.plugin = plugin; - } - - private record Tile(MapId map, BufferedImage normal, BufferedImage focused) {} - private record Page(int index, Style style, List cards) {} - private record Roleplay(String heading, String contact, Card portrait, Card world, Card summary) {} - - private static final class Scene { - final Player viewer; - final Location original; - final boolean gravity; - final Document document; - final Roleplay roleplay; - final IntConsumer select; - final Runnable dismiss; - final List entities = new ArrayList<>(); - final Map> buttons = new HashMap<>(); - Integer focus; - volatile Page page; - int mountId; - boolean presentationMasked; - volatile boolean closed; - boolean positioning; - - Scene(Player viewer, Document document, Roleplay roleplay, IntConsumer select, Runnable dismiss) { - this.viewer = viewer; - this.document = document; - this.roleplay = roleplay; - this.select = select; - this.dismiss = dismiss; - original = viewer.getLocation(); - gravity = viewer.hasGravity(); - page = page(this.document, 0); - } - } - - @Override public void close() { - List.copyOf(scenes.values()).forEach(scene -> finish(scene, true, true)); - } - - @Override public boolean open(Player viewer, Document document, IntConsumer select, Runnable dismiss) { - if (!(viewer instanceof CraftPlayer player) || !viewer.isOnline() || viewer.isDead() || - viewer.isInsideVehicle() || scenes.containsKey(viewer.getUniqueId()) || - !canPresent(document)) return false; - var pipeline = player.getHandle().connection.connection.channel.pipeline(); - if (pipeline.get("packet_handler") == null || pipeline.get(INPUT) != null) return false; - - Roleplay roleplay = roleplay(document); - Document visibleDocument = presentable(document, roleplay); - if (roleplay != null && !fitsRoleplay(visibleDocument, roleplay)) return false; - if (visibleDocument.style() != Style.AUTO && !fitsStyled(visibleDocument)) return false; - Scene scene = new Scene(viewer, visibleDocument, roleplay, select, dismiss); - var origin = scene.original; - var viewpoint = new Location(origin.getWorld(), origin.getBlockX() + .5, origin.getBlockY() + 6, - origin.getBlockZ() + .5, 0, 0); - if (!viewpoint.getBlock().isPassable() || !viewpoint.clone().add(0, 1, 0).getBlock().isPassable()) return false; - scenes.put(viewer.getUniqueId(), scene); - try { - viewer.setGravity(false); - scene.positioning = true; - if (!viewer.teleport(viewpoint) || !viewer.getLocation().equals(viewpoint)) { - finish(scene, false, false); - return false; - } - scene.positioning = false; - show(scene); - Bukkit.getScheduler().runTaskLater(plugin, () -> finish(scene, true, true), 2400); - return true; - } catch (RuntimeException | LinkageError error) { - plugin.getLogger().warning("Fullscreen Decisions could not open: " + error.getClass().getSimpleName()); - finish(scene, true, false); - return false; - } - } - private void show(Scene scene) { - var handle = ((CraftPlayer) scene.viewer).getHandle(); - var level = handle.level(); - var origin = scene.original; - paint(scene, true); - for (int row = 0; row < ROWS; row++) { - for (int col = 0; col < COLS; col++) { - var pos = new BlockPos(origin.getBlockX() + 5 - col, origin.getBlockY() + 11 - row, origin.getBlockZ() + 2); - var frame = new GlowItemFrame(level, pos, Direction.NORTH); - frame.setInvisible(true); - var map = new MapId(FIRST_SCENE_MAP + row * COLS + col); - var item = new net.minecraft.world.item.ItemStack(Items.FILLED_MAP); - item.set(DataComponents.MAP_ID, map); - frame.setItem(item, false, false); - add(scene, frame, Direction.NORTH.get3DDataValue()); - } - } - - var mount = new ArmorStand(level, handle.getX(), handle.getY() - 1.4, handle.getZ()); - var camera = new ArmorStand(level, handle.getX(), handle.getY(), handle.getZ()); - for (var stand : List.of(mount, camera)) { - stand.setInvisible(true); - stand.setNoGravity(true); - add(scene, stand, 0); - } - scene.mountId = mount.getId(); - handle.connection.send(passengers(scene.mountId, handle.getId())); - handle.connection.send(new ClientboundSetCameraPacket(camera)); - scene.presentationMasked = true; - maskHands(handle, true); - sidebar(scene.viewer, true); - handle.connection.send(new ClientboundSetActionBarTextPacket(net.minecraft.network.chat.Component.empty())); - var channel = handle.connection.connection.channel; - var ids = scene.entities.stream().map(Entity::getId).collect(java.util.stream.Collectors.toUnmodifiableSet()); - channel.pipeline().addBefore("packet_handler", INPUT, new ChannelInboundHandlerAdapter() { - private Integer focus; - private Page previous; - @Override public void channelRead(ChannelHandlerContext context, Object input) throws Exception { - if (!scene.closed) { - Page page = scene.page; - if (page != previous) { - previous = page; - focus = null; - } - if (input instanceof ServerboundMovePlayerPacket move && move.hasRotation()) { - Integer target = target(page, move.getYRot(0), move.getXRot(0)); - if (!Objects.equals(target, focus)) { - focus = target; - Bukkit.getScheduler().runTask(plugin, () -> { if (scene.page == page) focus(scene, target); }); - } - } - if (input instanceof ServerboundInteractPacket use && ids.contains(use.entityId())) { - Integer target = focus; - if (use.hand() == net.minecraft.world.InteractionHand.MAIN_HAND) - Bukkit.getScheduler().runTask(plugin, () -> { if (scene.page == page) select(scene, target); }); - return; - } - } - super.channelRead(context, input); - } - }); - } - - private static void sidebar(Player viewer, boolean masked) { - var scoreboard = ((CraftScoreboard) viewer.getScoreboard()).getHandle(); - var connection = ((CraftPlayer) viewer).getHandle().connection; - for (DisplaySlot slot : DisplaySlot.values()) { - if (slot != DisplaySlot.SIDEBAR && !slot.name().startsWith("TEAM_")) continue; - var objective = scoreboard.getDisplayObjective(slot); - if (objective != null) connection.send(new ClientboundSetDisplayObjectivePacket(slot, masked ? null : objective)); - } - } - - private static boolean canPresent(Document document) { - var cards = document.cards(); - return !cards.isEmpty() && cards.size() <= 54 && - cards.stream().allMatch(card -> card.slot() >= 0) && - cards.stream().map(Card::slot).distinct().count() == cards.size(); - } - - private static Page page(Document document, int index) { - if (document.style() == Style.EXCHANGE_CHECKOUT) return checkoutPage(document, index); - if (usesReadingPane(document.style())) return archivePage(document, index); - if (document.style() == Style.JOURNAL) return journalPage(document, index); - var cards = document.cards(); - int capacity = capacity(document.style()); - if (cards.size() <= capacity) return new Page(0, document.style(), cards); - int start = index * capacity; - int end = Math.min(start + capacity, cards.size()); - var visible = new ArrayList<>(cards.subList(start, end)); - while (visible.size() < capacity) visible.add(new Card(EMPTY, "", List.of(), false)); - String pageNumber = "Page " + (index + 1) + " / " + ((cards.size() + capacity - 1) / capacity); - visible.add(new Card(PREVIOUS, "Previous", List.of(pageNumber), index > 0)); - visible.add(new Card(NEXT, "Next", List.of(pageNumber), end < cards.size())); - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static Page journalPage(Document document, int index) { - var back = document.cards().stream() - .filter(card -> card.actionable() && card.title().equals("Back")).findFirst().orElse(null); - var entries = document.cards().stream().filter(card -> card != back).toList(); - int start = index * 2; - int end = Math.min(start + 2, entries.size()); - int count = Math.max(1, (entries.size() + 1) / 2); - var blank = new Card(EMPTY, "", List.of(), false); - var visible = new ArrayList<>(entries.subList(start, end)); - while (visible.size() < 2) visible.add(blank); - var label = List.of("Page " + (index + 1) + " / " + count); - visible.add(new Card(PREVIOUS, "Previous", label, index > 0)); - visible.add(back == null ? blank : back); - visible.add(new Card(NEXT, "Next", label, end < entries.size())); - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static Page archivePage(Document document, int index) { - var entries = document.cards().stream().filter(card -> isReadingEntry(document.style(), card)).toList(); - var actions = document.cards().stream().filter(card -> !isReadingEntry(document.style(), card)).toList(); - var entry = entries.get(index); - var visible = new ArrayList(); - var blank = new Card(EMPTY, "", List.of(), false); - visible.add(entry); // The reading pane is drawn separately from the interactive tiles. - visible.add(blank); - if (document.style() == Style.WORKSHOP) - visible.add(entry.actionable() ? new Card(entry.slot(), entry.title(), List.of(), true, entry.material()) : blank); - visible.addAll(actions); - while (visible.size() < STANDARD_PAGE) visible.add(blank); - if (entries.size() > 1) { - String number = "Page " + (index + 1) + " / " + entries.size(); - visible.add(new Card(PREVIOUS, "Previous", List.of(number), index > 0)); - visible.add(new Card(NEXT, "Next", List.of(number), index + 1 < entries.size())); - } - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static Page checkoutPage(Document document, int index) { - var controls = document.cards().stream() - .filter(card -> card.slot() != CHECKOUT_BACK && card.slot() != CHECKOUT_PRIMARY) - .sorted(Comparator.comparingInt(card -> exchangeControlOrder(document.title(), card.slot()))).toList(); - int start = index * CHECKOUT_CONTROLS; - int end = Math.min(start + CHECKOUT_CONTROLS, controls.size()); - var visible = new ArrayList<>(controls.subList(start, end)); - while (visible.size() < CHECKOUT_CONTROLS) visible.add(new Card(EMPTY, "", List.of(), false)); - for (int slot : new int[]{CHECKOUT_BACK,CHECKOUT_PRIMARY}) { - visible.add(document.cards().stream().filter(card -> card.slot() == slot).findFirst().orElseThrow()); - } - if (controls.size() > CHECKOUT_CONTROLS) { - String number = "Page " + (index + 1) + " / " + ((controls.size() + CHECKOUT_CONTROLS - 1) / CHECKOUT_CONTROLS); - visible.add(new Card(PREVIOUS, "Previous", List.of(number), index > 0)); - visible.add(new Card(NEXT, "Next", List.of(number), end < controls.size())); - } - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static int exchangeControlOrder(String title, int slot) { - return switch (title) { - case "Exchange · Add item" -> switch (slot) { - case 13 -> 0; - case 40 -> 1; - case 30 -> 2; - case 32 -> 3; - default -> 4; - }; - case "Exchange · Price" -> switch (slot) { - case 13 -> 0; - case 53 -> 1; - case 27 -> 2; - case 32 -> 3; - default -> 4; - }; - default -> switch (slot) { - case 30 -> 0; - case 32 -> 1; - case 31 -> 2; - default -> 3; - }; - }; - } - - private void paint(Scene scene, boolean initial) { - BufferedImage art = artwork(scene); - scene.buttons.clear(); - scene.focus = null; - for (int row = 0; row < ROWS; row++) { - for (int col = 0; col < COLS; col++) { - if (!initial && (row < 3 || row > 5 || col < 4 || col > 6 || (col == 5 && capacity(scene.page.style) == STANDARD_PAGE && !usesReadingPane(scene.page.style) && scene.page.style != Style.JOURNAL))) continue; - var map = new MapId(FIRST_SCENE_MAP + row * COLS + col); - var image = art.getSubimage(col * 128, row * 128, 128, 128); - var card = cardAt(scene.page, row, col); - boolean journalRow = scene.page.style == Style.JOURNAL && row < LAST_ROW; - var tile = new Tile(map, image, card == null || !card.actionable() ? image : - journalRow ? focusedJournalRow(image, col) : focused(image, row == LAST_ROW ? LAST_CARD_HEIGHT : 122)); - if (card != null && card.actionable()) - scene.buttons.computeIfAbsent(card.slot(), ignored -> new ArrayList<>()).add(tile); - pixels(scene, tile, false); - } - } - } - - private static void maskHands(net.minecraft.server.level.ServerPlayer player, boolean masked) { - var data = player.getEntityData().packAll(); - if (data != null) { - for (var value : data) { - if (value.id() != 0 || !(value.value() instanceof Byte flags)) continue; - var display = new net.minecraft.network.syncher.SynchedEntityData.DataValue<>( - value.id(), net.minecraft.network.syncher.EntityDataSerializers.BYTE, - masked ? (byte) (flags | 0x20) : flags); - player.connection.send(new ClientboundSetEntityDataPacket(player.getId(), List.of(display))); - break; - } - } - int offhand = net.minecraft.world.entity.player.Inventory.SLOT_OFFHAND; - for (int slot = 0; slot < 9; slot++) sendHandSlot(player, slot, masked); - sendHandSlot(player, offhand, masked); - } - - private static void sendHandSlot(net.minecraft.server.level.ServerPlayer player, int slot, boolean masked) { - var item = masked ? net.minecraft.world.item.ItemStack.EMPTY : player.getInventory().getItem(slot).copy(); - player.connection.send(new ClientboundSetPlayerInventoryPacket(slot, item)); - } - - private void add(Scene scene, Entity entity, int extra) { - var connection = ((CraftPlayer) scene.viewer).getHandle().connection; - scene.entities.add(entity); - if (entity instanceof ItemFrame) { - connection.send(new ClientboundAddEntityPacket(entity, extra, entity.blockPosition())); - } else { - connection.send(new ClientboundAddEntityPacket(entity.getId(), entity.getUUID(), entity.getX(), entity.getY(), - entity.getZ(), entity.getXRot(), entity.getYRot(), entity.getType(), extra, - net.minecraft.world.phys.Vec3.ZERO, entity.getYHeadRot())); - } - var data = entity.getEntityData().getNonDefaultValues(); - if (data != null) connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); - } - - private ClientboundSetPassengersPacket passengers(int mount, int... riders) { - var buffer = new FriendlyByteBuf(Unpooled.buffer()); - try { - buffer.writeVarInt(mount); - buffer.writeVarIntArray(riders); - return ClientboundSetPassengersPacket.STREAM_CODEC.decode(buffer); - } finally { - buffer.release(); - } - } - - private void pixels(Scene scene, Tile tile, boolean focused) { - byte[] image = MapPalette.imageToBytes(focused ? tile.focused : tile.normal); - var patch = new MapItemSavedData.MapPatch(0, 0, 128, 128, image); - ((CraftPlayer) scene.viewer).getHandle().connection.send( - new ClientboundMapItemDataPacket(tile.map, (byte) 0, true, List.of(), patch)); - } - - private static int capacity(Style style) { - return style == Style.EXCHANGE || style == Style.HOUSE ? THREE_COLUMN_PAGE : STANDARD_PAGE; - } - - private static Card cardAt(Page page, int row, int col) { - if (row < 3 || row > LAST_ROW || col < 4 || col > 6) return null; - if (page.style == Style.JOURNAL) return page.cards.get(row == LAST_ROW ? col - 2 : row - 3); - if (usesReadingPane(page.style) && row == 3) return null; - if (col == 5 && (capacity(page.style) == STANDARD_PAGE || row == LAST_ROW)) return null; - int cap = capacity(page.style); - int index = row == LAST_ROW ? cap + (col == 4 ? 0 : 1) : - (row - 3) * (cap / 2) + (cap == THREE_COLUMN_PAGE ? col - 4 : (col - 4) / 2); - return index < page.cards.size() ? page.cards.get(index) : null; - } - - private static Integer target(Page page, float yaw, float pitch) { - if (!Float.isFinite(yaw) || !Float.isFinite(pitch) || Math.abs(yaw) > 45 || Math.abs(pitch) > 40) return null; - double x = -Math.tan(Math.toRadians(yaw)) * 2.46; - double y = Math.tan(Math.toRadians(pitch)) * 2.46; - if (Math.abs(x) > 1.5 || y > 1.02) return null; - Card card = cardAt(page, 4 + (int) Math.round(y), 5 - (int) Math.round(x)); - return card != null && card.actionable() ? card.slot() : null; - } - - private void focus(Scene scene, Integer slot) { - if (scene.closed || Objects.equals(scene.focus, slot)) return; - scene.focus = slot; - scene.buttons.forEach((action, tiles) -> tiles.forEach(tile -> pixels(scene, tile, action.equals(slot)))); - } - - private void select(Scene scene, Integer slot) { - if (scene.closed || slot == null || !scene.buttons.containsKey(slot)) return; - if (slot == PREVIOUS || slot == NEXT) { - scene.page = page(scene.document, scene.page.index + (slot == NEXT ? 1 : -1)); - paint(scene, false); - return; - } - finish(scene, true, true, () -> scene.select.accept(slot)); - } - - @EventHandler public void swap(PlayerSwapHandItemsEvent event) { - var scene = scenes.get(event.getPlayer().getUniqueId()); - if (scene == null) return; - event.setCancelled(true); - finish(scene, true, true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void teleport(PlayerTeleportEvent event) { - interrupt(event.getPlayer()); - } - - @EventHandler public void changedWorld(PlayerChangedWorldEvent event) { - interrupt(event.getPlayer()); - } - - @EventHandler public void death(org.bukkit.event.entity.PlayerDeathEvent event) { - interrupt(event.getEntity()); - } - - @EventHandler public void quit(PlayerQuitEvent event) { - var scene = scenes.get(event.getPlayer().getUniqueId()); - if (scene != null) finish(scene, true, true); - } - - private void interrupt(Player viewer) { - var scene = scenes.get(viewer.getUniqueId()); - if (scene != null && !scene.positioning) finish(scene, false, true); - } - - private void finish(Scene scene, boolean restoreLocation, boolean dismiss) { - finish(scene, restoreLocation, dismiss, null); - } - - private void finish(Scene scene, boolean restoreLocation, boolean dismiss, Runnable selection) { - if (scene.closed) return; - scene.closed = true; - Player viewer = scene.viewer; - scenes.remove(viewer.getUniqueId(), scene); - var handle = ((CraftPlayer) viewer).getHandle(); - var connection = handle.connection; - boolean removePresentation = viewer.isOnline() && !scene.entities.isEmpty(); - Runnable terminal = dismiss ? scene.dismiss : () -> {}; - SceneTeardown.run( - () -> !restoreLocation || (viewer.isOnline() && - Objects.equals(viewer.getWorld(), scene.original.getWorld()) && - SceneTeardown.restore(positionOf(scene.original), () -> viewer.teleport(scene.original), - () -> positionOf(viewer.getLocation()))), - selection, - terminal, - () -> { - if (viewer.isOnline()) viewer.sendMessage(selection == null - ? "The fullscreen view closed, but your original position could not be restored." - : "The fullscreen view could not close normally. Your action was not run."); - }, - error -> plugin.getLogger().warning("Fullscreen teardown failed: " + error), - () -> { - var pipeline = connection.connection.channel.pipeline(); - if (pipeline.get(INPUT) != null) pipeline.remove(INPUT); - }, - () -> { if (removePresentation && scene.presentationMasked) maskHands(handle, false); }, - () -> { if (removePresentation && scene.presentationMasked) sidebar(viewer, false); }, - () -> { if (removePresentation) connection.send(new ClientboundSetCameraPacket(handle)); }, - () -> { if (removePresentation && scene.mountId != 0) connection.send(passengers(scene.mountId)); }, - () -> { - if (removePresentation) - connection.send(new ClientboundRemoveEntitiesPacket(scene.entities.stream().mapToInt(Entity::getId).toArray())); - }, - () -> viewer.setGravity(scene.gravity)); - } - - private static SceneTeardown.Position positionOf(Location location) { - return new SceneTeardown.Position(location.getWorld().getUID(), location.getX(), location.getY(), location.getZ()); - } - - private BufferedImage artwork(Scene scene) { - var image = new BufferedImage(COLS * 128, ROWS * 128, BufferedImage.TYPE_INT_RGB); - var draw = image.createGraphics(); - try { - Palette palette = palette(scene); - draw.setColor(palette.background); - draw.fillRect(0, 0, image.getWidth(), image.getHeight()); - draw.setColor(palette.accent); - if (scene.document.style() == Style.JOURNAL) { - drawJournal(draw, scene.document, scene.page, palette); - return image; - } - draw.setStroke(new BasicStroke(7)); - draw.drawRect(445, 335, 518, 374); - - String heading = scene.roleplay != null ? scene.roleplay.heading : - scene.document.style() == Style.AUTO ? scene.document.title() : styledTitle(scene.document); - setHeadingFont(draw, scene.document.style(), heading); - int headlineWidth = draw.getFontMetrics().stringWidth(heading); - draw.drawString(heading, (image.getWidth() - headlineWidth) / 2, 372); - if (scene.roleplay != null) drawRoleplay(draw, scene); - else if (usesReadingPane(scene.document.style())) drawArchive(draw, scene, palette); - else if (scene.document.style() != Style.AUTO) drawStyledIdentity(draw, scene, palette); - for (int row = 3; row <= LAST_ROW; row++) for (int col = 4; col <= 6; col++) { - Card card = cardAt(scene.page, row, col); - if (card == null || card.slot() == EMPTY) continue; - int x = col * 128; - int y = row * 128; - draw.setColor(card.actionable() ? palette.tile : new Color(55, 63, 66)); - boolean bottom = row == LAST_ROW; - draw.fillRect(x, y + 3, 128, bottom ? LAST_CARD_HEIGHT : 122); - if (card.slot() >= 0 && drawStyledCard(draw, scene.document, card, palette, x, y)) continue; - draw.setColor(Color.WHITE); - draw.setFont(CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + 24, 114, bottom ? 2 : 3); - String lore = displayLore(scene.roleplay, card); - if (!lore.isBlank()) { - draw.setFont(CARD_LORE); - writeWrapped(draw, lore, x + 7, y + (card.slot() < 0 ? 45 : bottom ? 64 : 78), 114, bottom ? 2 : 3); - } - } - } finally { - draw.dispose(); - } - return image; - } - - private static boolean fitsJournal(java.awt.Graphics2D draw, Document document) { - draw.setFont(JOURNAL_TITLE); - if (!wrap(draw, document.title(), 323, 1).complete()) return false; - for (Card card : document.cards()) { - var title = journalRowTitle(draw, card); - if (!title.complete()) return false; - draw.setFont(JOURNAL_TEXT); - if (!wrapLore(draw, card.lore(), JOURNAL_TEXT_WIDTH, 5 - title.lines().size()).complete()) return false; - } - return true; - } - - private static Wrapped journalRowTitle(java.awt.Graphics2D draw, Card card) { - draw.setFont(JOURNAL_TITLE); - var title = wrap(draw, card.title(), JOURNAL_TEXT_WIDTH, 2); - if (title.complete()) return title; - draw.setFont(JOURNAL_TITLE.deriveFont(19f)); - return wrap(draw, card.title(), JOURNAL_TEXT_WIDTH, 2); - } - - private void drawJournal(java.awt.Graphics2D draw, Document document, Page page, Palette palette) { - var ink = new Color(34, 43, 39); - var binding = new Color(25, 58, 51); - var brass = new Color(199, 152, 72); - draw.setColor(new Color(12, 28, 27)); - draw.fillRoundRect(478, 330, 452, 386, 16, 16); - draw.setColor(brass); - draw.drawRoundRect(485, 337, 438, 372, 12, 12); - draw.setColor(binding); - draw.fillRoundRect(490, 342, 428, 362, 10, 10); - draw.setColor(brass); - draw.fillRect(510, 379, JOURNAL_WIDTH + 4, 2); - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 506, 349, 62, 24); - draw.setColor(palette.accent); - draw.setFont(JOURNAL_TITLE); - draw.drawString(document.title(), 578, 370); - - for (int row = 3; row < LAST_ROW; row++) { - Card card = cardAt(page, row, 5); - if (card == null || card.slot() == EMPTY) continue; - int y = row * 128; - draw.setColor(new Color(15, 36, 32)); - draw.fillRoundRect(514, y + 8, JOURNAL_WIDTH - 2, 116, 12, 12); - draw.setColor(card.actionable() ? palette.tile : new Color(188, 177, 149)); - draw.fillRoundRect(512, y + 4, JOURNAL_WIDTH, 116, 12, 12); - draw.setColor(brass); - draw.drawRoundRect(515, y + 7, JOURNAL_WIDTH - 7, 109, 9, 9); - draw.drawLine(530, y + 14, 530, y + 110); - draw.setColor(ink); - var title = journalRowTitle(draw, card).lines(); - int titleHeight = draw.getFontMetrics().getHeight(); - int textY = y + 31; - for (String line : title) { - draw.drawString(line, 543, textY); - textY += titleHeight; - } - if (card.actionable()) { - draw.setColor(binding); - draw.fillOval(856, y + 45, 28, 28); - draw.setColor(palette.accent); - draw.setStroke(new BasicStroke(2)); - draw.drawLine(864, y + 59, 876, y + 59); - draw.drawLine(871, y + 54, 876, y + 59); - draw.drawLine(871, y + 64, 876, y + 59); - draw.setStroke(new BasicStroke(1)); - } - draw.setColor(ink); - draw.setFont(JOURNAL_TEXT); - int baseline = textY - 8; - for (String line : wrapLore(draw, card.lore(), JOURNAL_TEXT_WIDTH, 5 - title.size()).lines()) { - draw.drawString(line, 543, baseline); - baseline += draw.getFontMetrics().getHeight(); - } - } - - for (int col = 4; col <= 6; col++) { - Card navigation = cardAt(page, LAST_ROW, col); - if (!navigation.actionable()) continue; - int x = col * 128; - draw.setColor(new Color(37, 78, 64)); - draw.fillRoundRect(x + 4, 648, 120, 48, 8, 8); - draw.setColor(brass); - draw.drawRoundRect(x + 4, 648, 119, 47, 8, 8); - draw.setColor(palette.accent); - draw.setFont(CARD_TITLE); - String label = navigation.title(); - draw.drawString(label, x + (128 - draw.getFontMetrics().stringWidth(label)) / 2, col == 5 ? 669 : 678); - } - String label = cardAt(page, LAST_ROW, 4).lore().getFirst(); - draw.setColor(palette.accent); - draw.setFont(JOURNAL_TEXT.deriveFont(13f)); - draw.drawString(label, 704 - draw.getFontMetrics().stringWidth(label) / 2, - cardAt(page, LAST_ROW, 5).actionable() ? 687 : 678); - } - - private static BufferedImage focusedJournalRow(BufferedImage normal, int column) { - var image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); - var draw = image.createGraphics(); - try { - draw.drawImage(normal, 0, 0, null); - draw.setColor(new Color(249, 218, 155)); - draw.fillRect(0, 4, 128, 3); - draw.fillRect(0, 121, 128, 3); - if (column == 4) draw.fillRect(0, 4, 3, 120); - if (column == 6) draw.fillRect(125, 4, 3, 120); - } finally { - draw.dispose(); - } - return image; - } - - private record Palette(Color background, Color tile, Color accent) {} - - private static Palette palette(Scene scene) { - return switch (scene.document.style()) { - case WAR_MUSTER -> new Palette(new Color(38, 24, 28), new Color(78, 44, 53), new Color(245, 204, 177)); - case WORKSHOP -> new Palette(new Color(29, 37, 42), new Color(54, 73, 84), new Color(235, 219, 177)); - case DECISION_DETAIL -> new Palette(new Color(21, 33, 41), new Color(47, 69, 81), new Color(236, 203, 129)); - case ORGANISATION -> new Palette(new Color(16, 31, 37), new Color(29, 75, 79), new Color(142, 228, 211)); - case EXCHANGE, EXCHANGE_CHECKOUT -> new Palette(new Color(42, 28, 18), new Color(91, 62, 36), new Color(245, 208, 139)); - case CODEX, ITEM_ARCHIVE -> new Palette(new Color(40, 33, 24), new Color(90, 63, 37), new Color(246, 221, 158)); - case GUILD -> new Palette(new Color(14, 28, 47), new Color(28, 58, 83), new Color(188, 224, 249)); - case SPICE -> new Palette(new Color(54, 25, 16), new Color(105, 54, 33), new Color(255, 214, 133)); - case JOURNAL -> new Palette(new Color(18, 33, 30), new Color(239, 221, 177), new Color(255, 226, 159)); - case HOUSE -> new Palette(new Color(34, 26, 39), new Color(72, 52, 79), new Color(244, 211, 152)); - case AUTO -> scene.roleplay == null - ? new Palette(new Color(25, 40, 46), new Color(52, 93, 107), new Color(237, 199, 105)) - : new Palette(new Color(9, 33, 24), new Color(38, 80, 61), new Color(237, 199, 105)); - }; - } - - private static boolean fitsStyled(Document document) { - var graphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics(); - try { - if (document.style() == Style.JOURNAL) return fitsJournal(graphics, document); - setHeadingFont(graphics, document.style(), styledTitle(document)); - if (!wrap(graphics, styledTitle(document), 500, 1).complete) return false; - if (document.style() == Style.EXCHANGE_CHECKOUT) { - if (document.description().isBlank() || !hasCheckoutAction(document, CHECKOUT_BACK) || - !hasCheckoutAction(document, CHECKOUT_PRIMARY)) return false; - graphics.setFont(CHECKOUT_TERMS); - var terms = checkoutTerms(graphics, document.description()); - if (terms.isEmpty() || terms.size() > 9) return false; - } - if (document.style() == Style.GUILD || document.style() == Style.WAR_MUSTER) { - graphics.setFont(SIDEBAR_TERMS); - var terms = sidebarTerms(graphics, document); - if (terms.lines().isEmpty() || !terms.complete()) return false; - } - if (usesReadingPane(document.style())) { - long navigationCount = document.cards().stream().filter(card -> !isReadingEntry(document.style(), card)).count(); - int maximumNavigation = document.style() == Style.WORKSHOP ? 1 : 2; - if (navigationCount > maximumNavigation || navigationCount == document.cards().size()) return false; - if (document.style() == Style.ITEM_ARCHIVE && navigationCount == 0) return false; - } - graphics.setFont(CARD_TITLE); - if (document.identity() != null && !wrap(graphics, document.identity().mentat(), 112, 2).complete) return false; - for (Card card : document.cards()) { - boolean seal = document.style() == Style.HOUSE && nativeArt(card.material()) != null; - graphics.setFont(CARD_TITLE); - if (usesReadingPane(document.style()) && isReadingEntry(document.style(), card)) { - if (!wrap(graphics, card.title(), 368, 1).complete) return false; - graphics.setFont(ARCHIVE_LORE); - if (!archiveLore(graphics, card).complete) return false; - if (document.style() == Style.WORKSHOP && card.actionable() && - !fitsFullCardTitle(graphics, document.style(), card)) return false; - continue; - } - if (usesFullCardLore(document.style()) || saleControls(document, card)) { - if (!fitsFullCardTitle(graphics, document.style(), card)) return false; - graphics.setFont(compactCardLore(document.style()) ? COMPACT_CARD_LORE : FULL_CARD_LORE); - if (!fullCardLore(graphics, document.style(), card).complete) return false; - continue; - } - if (!wrap(graphics, card.title(), 114, seal ? 2 : 3).complete) return false; - graphics.setFont(CARD_LORE); - if (!wrap(graphics, styledLore(document.style(), card), 114, seal ? 2 : 3).complete) return false; - } - return true; - } finally { - graphics.dispose(); - } - } - - private static void setHeadingFont(java.awt.Graphics2D draw, Style style, String title) { - int size = switch (style) { - case ITEM_ARCHIVE, GUILD, ORGANISATION, WORKSHOP, DECISION_DETAIL, WAR_MUSTER -> 28; - default -> 38; - }; - draw.setFont(new Font(Font.SANS_SERIF, Font.BOLD, size)); - if (style != Style.ORGANISATION) return; - while (size > 20 && draw.getFontMetrics().stringWidth(title) > 500) { - size--; - draw.setFont(draw.getFont().deriveFont((float) size)); - } - } - - private static boolean usesFullCardLore(Style style) { - return switch (style) { - case CODEX, ITEM_ARCHIVE, GUILD, SPICE, ORGANISATION, WORKSHOP, DECISION_DETAIL, WAR_MUSTER -> true; - default -> false; - }; - } - - private static boolean fitsFullCardTitle(java.awt.Graphics2D draw, Style style, Card card) { - boolean compact = compactCardTitle(style); - draw.setFont(compact ? COMPACT_CARD_TITLE : CARD_TITLE); - return wrap(draw, card.title(), 114, compact ? 3 : 2).complete(); - } - - private static boolean compactCardTitle(Style style) { - return style == Style.CODEX || style == Style.GUILD || style == Style.EXCHANGE_CHECKOUT || compactCardLore(style); - } - - private static boolean compactCardLore(Style style) { - return style == Style.SPICE || style == Style.ORGANISATION || style == Style.WORKSHOP || style == Style.DECISION_DETAIL || style == Style.WAR_MUSTER; - } - - private static boolean usesReadingPane(Style style) { - return style == Style.ITEM_ARCHIVE || style == Style.WORKSHOP; - } - - private static boolean isReadingEntry(Style style, Card card) { - if (style == Style.ITEM_ARCHIVE) return !card.actionable(); - return !card.actionable() || (!card.title().equals("Back") && !card.title().equals("Close")); - } - - private static Wrapped sidebarTerms(java.awt.Graphics2D draw, Document document) { - return wrapLore(draw, document.description().lines().toList(), SIDEBAR_TERMS_WIDTH, SIDEBAR_TERMS_LINES); - } - - private static Wrapped archiveLore(java.awt.Graphics2D draw, Card card) { - var entries = card.lore().stream().filter(line -> !line.matches("─+")).toList(); - return wrapLore(draw, entries, ARCHIVE_COLUMN_WIDTH, 2 * ARCHIVE_COLUMN_LINES); - } - - private void drawArchive(java.awt.Graphics2D draw, Scene scene, Palette palette) { - var card = scene.page.cards.getFirst(); - draw.setColor(palette.tile); - draw.fillRect(512, 386, 384, 123); - draw.setColor(Color.WHITE); - draw.setFont(CARD_TITLE); - draw.drawString(card.title(), 520, 404); - draw.setColor(palette.accent); - draw.drawLine(520, 407, 888, 407); - draw.setFont(ARCHIVE_LORE); - var lines = archiveLore(draw, card).lines(); - for (int i = 0; i < lines.size(); i++) { - int x = 520 + i / ARCHIVE_COLUMN_LINES * 184; - int y = 416 + i % ARCHIVE_COLUMN_LINES * draw.getFontMetrics().getHeight(); - draw.drawString(lines.get(i), x, y); - } - } - - private static String styledTitle(Document document) { - return switch (document.title()) { - case "Exchange · Purchase details" -> "Exchange checkout"; - case "Exchange · Add item" -> "Create listing"; - case "Exchange · Price" -> "Listing price"; - case "Exchange · Withdraw listing" -> "Withdraw listing"; - default -> document.title(); - }; - } - - private static boolean saleControls(Document document, Card card) { - return document.style() == Style.EXCHANGE_CHECKOUT && card.actionable() && - !document.title().equals("Exchange · Purchase details"); - } - - private static boolean hasCheckoutAction(Document document, int slot) { - return document.cards().stream().anyMatch(card -> card.slot() == slot && card.actionable()); - } - - private static List checkoutTerms(java.awt.Graphics2D graphics, String description) { - var lines = new ArrayList(); - for (String term : description.lines().toList()) { - var wrapped = wrap(graphics, term, 106, 9); - if (!wrapped.complete) return List.of(); - lines.addAll(wrapped.lines); - } - return lines; - } - - private static Wrapped fullCardLore(java.awt.Graphics2D draw, Style style, Card card) { - return wrapLore(draw, card.lore(), 114, compactCardLore(style) ? 6 : FULL_CARD_LORE_LINES); - } - - private static Wrapped wrapLore(java.awt.Graphics2D draw, List entries, int width, int limit) { - var lines = new ArrayList(); - for (String entry : entries) { - var wrapped = wrap(draw, entry, width, limit - lines.size()); - lines.addAll(wrapped.lines()); - if (!wrapped.complete()) return new Wrapped(lines, false); - } - return new Wrapped(lines, true); - } - - private static String styledLore(Style style, Card card) { - if (card.lore().isEmpty()) return ""; - if (style == Style.HOUSE && card.material().startsWith("house_")) - return card.lore().getFirst().equals("Your current House") ? card.lore().getFirst() : ""; - if (style == Style.EXCHANGE_CHECKOUT && !card.actionable()) return String.join(" ", card.lore()); - if (style == Style.EXCHANGE || style == Style.EXCHANGE_CHECKOUT) { - // The listing renderer appends the server price after the stored item lore. - for (int index = card.lore().size() - 1; index >= 0; index--) { - String line = card.lore().get(index); - if (line.endsWith(" DM each") || line.endsWith(" DM")) return line; - } - } - return card.lore().getFirst(); - } - - private void drawStyledIdentity(java.awt.Graphics2D draw, Scene scene, Palette palette) { - var document = scene.document; - var identity = document.identity(); - if (document.style() == Style.EXCHANGE) { - drawResource(draw, "/mcgui/native/exchange.png", 454, 343, 40, 31); - draw.setColor(palette.accent); - for (int row = 3; row <= 4; row++) draw.fillRect(510, row * 128 + 124, 388, 4); - return; - } - if (document.style() == Style.HOUSE) { - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 454, 343, 65, 31); - return; - } - draw.setColor(palette.background.darker()); - draw.fillRect(644, 389, 120, 232); - switch (document.style()) { - case GUILD, WAR_MUSTER -> { - draw.setColor(palette.accent); - draw.setFont(SIDEBAR_TERMS); - int y = 406; - for (String line : sidebarTerms(draw, document).lines()) { - draw.drawString(line, 649, y); - y += draw.getFontMetrics().getHeight(); - } - } - case SPICE -> drawSceneArt(draw, "npc_world_arrakis", 650, 422, 108, 162); - case CODEX -> { - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 650, 449, 108, 96); - draw.setColor(palette.accent); - draw.drawLine(650, 446, 758, 446); - draw.drawLine(650, 549, 758, 549); - } - case EXCHANGE_CHECKOUT -> { - draw.setColor(Color.WHITE); - draw.setFont(CHECKOUT_TERMS); - int y = 420; - for (String line : checkoutTerms(draw, document.description())) { - draw.drawString(line, 651, y); - y += draw.getFontMetrics().getHeight(); - } - } - case ORGANISATION -> { - if (identity == null || (identity.logo().isBlank() && identity.mentat().isBlank() && identity.portrait() < 0)) { - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 650, 449, 108, 96); - } else { - BufferedImage mark = organisationLogo(identity.logo()); - if (mark != null) drawImage(draw, mark, 660, 397, 88, 74); - if (identity.portrait() >= 0 && identity.portrait() <= 7) - drawSceneArt(draw, "npc_avatar_" + identity.portrait(), 662, 477, 84, 72); - draw.setColor(palette.accent); - draw.setFont(CARD_LORE); - writeWrapped(draw, identity.mentat().isBlank() ? "" : "Mentat", 649, 567, 110, 1); - draw.setFont(CARD_TITLE); - writeWrapped(draw, identity.mentat(), 649, 589, 110, 2); - } - } - - default -> {} - } - } - - private boolean drawStyledCard(java.awt.Graphics2D draw, Document document, Card card, Palette palette, int x, int y) { - Style style = document.style(); - if (style == Style.AUTO) return false; - String art = nativeArt(card.material()); - draw.setColor(palette.accent); - if (usesFullCardLore(style) || saleControls(document, card)) { - if (style == Style.ORGANISATION) draw.fillRect(x, y + 3, 4, 122); - draw.drawLine(x + 7, y + 48, x + 121, y + 48); - draw.setColor(Color.WHITE); - boolean compact = compactCardTitle(style); - draw.setFont(compact ? COMPACT_CARD_TITLE : CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + (compact ? 15 : 21), 114, compact ? 3 : 2); - draw.setColor(palette.accent); - draw.setFont(compactCardLore(style) ? COMPACT_CARD_LORE : FULL_CARD_LORE); - int lineY = y + (compactCardLore(style) ? 55 : 64); - for (String line : fullCardLore(draw, style, card).lines()) { - draw.drawString(line, x + 7, lineY); - lineY += draw.getFontMetrics().getHeight(); - } - if (style == Style.GUILD && card.actionable() && card.material().startsWith("guild_world_")) { - drawSceneArt(draw, "npc_world_" + card.material().substring("guild_world_".length()), x + 70, y + 76, 51, 42); - } - return true; - } else if (style == Style.EXCHANGE || style == Style.EXCHANGE_CHECKOUT) { - draw.fillRect(x, y + 70, 128, 5); - draw.fillRect(x, y + 120, 128, 5); - } else if (art != null) { - drawResource(draw, art, x + 39, y + 7, 50, 48); - draw.setFont(CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + 71, 114, 2); - draw.setFont(CARD_LORE); - writeWrapped(draw, styledLore(style, card), x + 7, y + 104, 114, 2); - return true; - } - draw.setColor(Color.WHITE); - draw.setFont(CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + 24, 114, 3); - draw.setColor(palette.accent); - draw.setFont(CARD_LORE); - writeWrapped(draw, styledLore(style, card), x + 7, y + 87, 114, 3); - return true; - } - - private static String nativeArt(String key) { - if (key.matches("mentat_(atreides|corrino|fremen|harkonnen|ordos)")) - return "/mcgui/native/" + key.replace('_', '-') + "-v1.png"; - return switch (key) { - case "house_atreides" -> "/mcgui/native/house-aerdrecht-v1.png"; - case "house_corrino" -> "/mcgui/native/house-korenholt-v1.png"; - case "house_fremen" -> "/mcgui/native/house-vrijduin-v1.png"; - case "house_harkonnen" -> "/mcgui/native/house-harkveen-v1.png"; - case "house_ordos" -> "/mcgui/native/house-oordwijk-v1.png"; - default -> null; - }; - } - - private static BufferedImage organisationLogo(String value) { - if (value.length() > 110000 || value.isBlank()) return null; - try (var input = javax.imageio.ImageIO.createImageInputStream( - new java.io.ByteArrayInputStream(Base64.getDecoder().decode(value)))) { - var readers = javax.imageio.ImageIO.getImageReaders(input); - if (!readers.hasNext()) return null; - var reader = readers.next(); - try { - reader.setInput(input, true, true); - if (!reader.getFormatName().equalsIgnoreCase("png") || - reader.getWidth(0) > 512 || reader.getHeight(0) > 512) return null; - return reader.read(0); - } finally { - reader.dispose(); - } - } catch (IllegalArgumentException | java.io.IOException error) { - return null; - } - } - - private static Roleplay roleplay(Document document) { - String[] title = document.title().split(" · ", 2); - if (title.length != 2) return null; - String heading = switch (title[0]) { - case "NPC dashboard" -> "YOUR MISSIONS"; - case "NPC next quest" -> "YOUR NEXT MISSION"; - case "NPC turn-in decision" -> "POLITICAL DECISION"; - case "NPC next quest decision" -> "DECISION RECORDED"; - case "NPC turn-in" -> document.cards().stream().anyMatch(card -> - card.actionable() && (card.title().equals("Claim verified reward") || card.title().equals("Next quest"))) - ? "MISSION COMPLETE" : "MISSION TURN-IN"; - default -> null; - }; - if (heading == null) return null; - var portrait = document.cards().stream().filter(card -> card.material().matches("npc_avatar_[0-7]")).findFirst().orElse(null); - var world = document.cards().stream().filter(card -> card.material().matches("npc_world_[a-z_]+")).findFirst().orElse(null); - var summary = document.description().isBlank() ? document.cards().stream() - .filter(card -> card.material().equals("npc_summary")).findFirst().orElse(null) : null; - return new Roleplay(heading, portrait == null ? title[1] : portrait.title(), portrait, world, summary); - } - - private static Document presentable(Document document, Roleplay roleplay) { - if (roleplay == null) return document; - var cards = document.cards().stream() - .filter(card -> card.actionable() || card != roleplay.portrait && card != roleplay.world && card != roleplay.summary) - .toList(); - return new Document(document.title(), document.description(), cards, document.style(), document.identity()); - } - - private static String displayLore(Roleplay roleplay, Card card) { - if (card.lore().isEmpty()) return ""; - if (roleplay == null || card.slot() < 0) return card.lore().getFirst(); - if (!card.actionable()) return String.join(" ", card.lore()); - return roleplay.heading.equals("YOUR MISSIONS") && card.slot() >= 9 && card.slot() < 45 - ? card.lore().getFirst() : ""; - } - - private static boolean fitsRoleplay(Document document, Roleplay roleplay) { - var graphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics(); - try { - graphics.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); - if (!wrap(graphics, roleplay.contact, 112, 2).complete) return false; - if (document.style() == Style.AUTO && !fitsCards(graphics, document, roleplay)) return false; - graphics.setFont(CARD_LORE); - String summary = roleplay.summary == null ? document.description() : String.join(" ", roleplay.summary.lore()); - return wrap(graphics, summary, 112, 6).complete; - } finally { - graphics.dispose(); - } - } - - private static boolean fitsCards(java.awt.Graphics2D graphics, Document document, Roleplay roleplay) { - for (Card card : document.cards()) { - graphics.setFont(CARD_TITLE); - if (!wrap(graphics, card.title(), 114, 3).complete) return false; - graphics.setFont(CARD_LORE); - if (!wrap(graphics, displayLore(roleplay, card), 114, 3).complete) return false; - } - return true; - } - - private void drawRoleplay(java.awt.Graphics2D draw, Scene scene) { - var role = scene.roleplay; - draw.setColor(new Color(23, 56, 40)); - draw.fillRect(644, 389, 120, 232); - String asset = role.portrait == null ? "npc_avatar_7" : role.portrait.material(); - drawSceneArt(draw, asset, 650, 395, 108, 83); - draw.setColor(new Color(250, 226, 169)); - draw.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); - writeWrapped(draw, role.contact, 648, 498, 112, 2); - draw.setColor(Color.WHITE); - draw.setFont(CARD_LORE); - String summary = role.summary == null ? scene.document.description() : String.join(" ", role.summary.lore()); - if (summary.isBlank() && role.world != null) drawSceneArt(draw, role.world.material(), 650, 518, 108, 78); - else writeWrapped(draw, summary, 648, 532, 112, 6); - } - - private void drawSceneArt(java.awt.Graphics2D draw, String asset, int x, int y, int width, int height) { - drawResource(draw, "/mcgui-npc-avatars/" + asset + ".png", x, y, width, height); - } - - private void drawResource(java.awt.Graphics2D draw, String resource, int x, int y, int width, int height) { - if (resource == null) return; - try (var stream = DecisionsViewTransport.class.getResourceAsStream(resource)) { - if (stream == null) return; - var image = javax.imageio.ImageIO.read(stream); - if (image == null) return; - drawImage(draw, image, x, y, width, height); - } catch (java.io.IOException error) { - plugin.getLogger().warning("Could not render fullscreen artwork: " + resource); - } - } - - private static void drawImage(java.awt.Graphics2D draw, BufferedImage image, int x, int y, int width, int height) { - double scale = Math.min((double) width / image.getWidth(), (double) height / image.getHeight()); - int w = (int) Math.round(image.getWidth() * scale), h = (int) Math.round(image.getHeight() * scale); - draw.drawImage(image, x + (width - w) / 2, y + (height - h) / 2, w, h, null); - } - - private record Wrapped(List lines, boolean complete) {} - - private static void writeWrapped(java.awt.Graphics2D draw, String text, int x, int y, int width, int lines) { - int lineHeight = draw.getFontMetrics().getHeight(); - for (String line : wrap(draw, text, width, lines).lines()) { - draw.drawString(line, x, y); - y += lineHeight; - } - } - - private static Wrapped wrap(java.awt.Graphics2D draw, String text, int width, int lines) { - var metrics = draw.getFontMetrics(); - var result = new ArrayList(); - String remaining = text.strip().replaceAll("\\s+", " "); - while (result.size() < lines && !remaining.isEmpty()) { - int end = remaining.length(); - while (end > 1 && metrics.stringWidth(remaining.substring(0, end)) > width) end--; - if (end < remaining.length()) { - int wordBreak = remaining.lastIndexOf(' ', end); - if (wordBreak > 0) end = wordBreak; - } - result.add(remaining.substring(0, end)); - remaining = remaining.substring(end).stripLeading(); - } - return new Wrapped(List.copyOf(result), remaining.isEmpty()); - } - - private BufferedImage focused(BufferedImage normal, int height) { - var image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); - var draw = image.createGraphics(); - try { - draw.drawImage(normal, 0, 0, null); - draw.setColor(new Color(250, 224, 152)); - draw.setStroke(new BasicStroke(8)); - draw.drawRect(5, 5, 117, height - 5); - } finally { - draw.dispose(); - } - return image; - } -} diff --git a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/SceneTeardown.java b/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/SceneTeardown.java deleted file mode 100644 index 9abc1710..00000000 --- a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/SceneTeardown.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.dunerealms.fullscreen; - -import java.util.UUID; -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; -import java.util.function.Supplier; - -final class SceneTeardown { - private SceneTeardown() {} - - record Position(UUID world, double x, double y, double z) {} - - static boolean restore(Position saved, BooleanSupplier teleport, Supplier current) { - return teleport.getAsBoolean() && saved.equals(current.get()); - } - - static void run(BooleanSupplier restore, Runnable select, Runnable dismiss, Runnable rejected, - Consumer report, Runnable... cleanup) { - boolean clean = true; - for (Runnable step : cleanup) { - try { - step.run(); - } catch (RuntimeException | LinkageError failure) { - clean = false; - report.accept(failure); - } - } - - boolean restored = false; - try { - restored = restore.getAsBoolean(); - } catch (RuntimeException | LinkageError failure) { - report.accept(failure); - } - - if (select != null && restored && clean) { - try { - select.run(); - } catch (RuntimeException | LinkageError failure) { - dismiss.run(); - report.accept(failure); - } - } else { - dismiss.run(); - if (select != null || !restored) rejected.run(); - } - } -} diff --git a/DuneFullscreenPaper/src/main/resources/plugin.yml b/DuneFullscreenPaper/src/main/resources/plugin.yml deleted file mode 100644 index e0a39528..00000000 --- a/DuneFullscreenPaper/src/main/resources/plugin.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: DuneFullscreenPaper -main: com.dunerealms.fullscreen.FullscreenProvider -version: 0.1.0 -api-version: '26.2' -depend: [DuneMenus] diff --git a/DuneFullscreenPaper/src/test/java/com/dunerealms/fullscreen/SceneTeardownTest.java b/DuneFullscreenPaper/src/test/java/com/dunerealms/fullscreen/SceneTeardownTest.java deleted file mode 100644 index 1e358c24..00000000 --- a/DuneFullscreenPaper/src/test/java/com/dunerealms/fullscreen/SceneTeardownTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.dunerealms.fullscreen; - -import static org.junit.jupiter.api.Assertions.*; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import org.junit.jupiter.api.Test; - -class SceneTeardownTest { - private final SceneTeardown.Position saved = new SceneTeardown.Position(UUID.randomUUID(), 10.5, 64, 7.5); - - @Test void cancelledReturnDoesNotRunSelection() { - assertRejected(() -> SceneTeardown.restore(saved, () -> false, () -> saved)); - } - - @Test void redirectedReturnDoesNotRunSelection() { - assertRejected(() -> SceneTeardown.restore(saved, () -> true, () -> new SceneTeardown.Position(saved.world(), 10.5, 70, 7.5))); - } - - @Test void returnToSameCoordinatesInAnotherWorldDoesNotRunSelection() { - assertRejected(() -> SceneTeardown.restore(saved, () -> true, - () -> new SceneTeardown.Position(UUID.randomUUID(), saved.x(), saved.y(), saved.z()))); - } - - @Test void exactReturnRunsSelectionOnceAfterCleanup() { - var calls = new ArrayList(); - SceneTeardown.run(() -> SceneTeardown.restore(saved, () -> true, () -> saved), - () -> calls.add("selected"), () -> fail("Unexpected dismissal"), () -> fail("Unexpected rejection"), - failure -> fail(failure), () -> calls.add("cleanup")); - assertEquals(List.of("cleanup", "selected"), calls); - } - - @Test void cleanupFailureStillRestoresAndReleasesSession() { - var calls = new ArrayList(); - SceneTeardown.run(() -> { calls.add("restored"); return true; }, () -> fail("Unsafe selection"), - () -> calls.add("dismissed"), () -> calls.add("rejected"), failure -> calls.add("reported"), - () -> { throw new IllegalStateException("failed to restore camera"); }, - () -> calls.add("removed entities")); - assertEquals(List.of("reported", "removed entities", "restored", "dismissed", "rejected"), calls); - } - - @Test void restorationExceptionStillReleasesSession() { - var calls = new ArrayList(); - SceneTeardown.run(() -> { throw new IllegalStateException("teleport failed"); }, null, - () -> calls.add("dismissed"), () -> calls.add("rejected"), failure -> calls.add("reported")); - assertEquals(List.of("reported", "dismissed", "rejected"), calls); - } - - @Test void incomingTeleportReleaseLeavesDestinationAlone() { - var calls = new ArrayList(); - SceneTeardown.run(() -> true, null, () -> calls.add("dismissed"), - () -> fail("Unexpected rejection"), failure -> fail(failure), () -> calls.add("cleanup")); - assertEquals(List.of("cleanup", "dismissed"), calls); - } - - private void assertRejected(java.util.function.BooleanSupplier restoration) { - var calls = new ArrayList(); - SceneTeardown.run(restoration, () -> fail("Unsafe selection"), () -> calls.add("dismissed"), - () -> calls.add("rejected"), failure -> fail(failure)); - assertEquals(List.of("dismissed", "rejected"), calls); - } -} diff --git a/DuneLobby/README.md b/DuneLobby/README.md deleted file mode 100644 index a6f04945..00000000 --- a/DuneLobby/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# Vaerkring lobby world - -A separate **Minecraft Java / Paper 1.21.4 / Java 21** End-dimension lobby. The rebuilt 1.1.0 world is already built and saved in [`../worlds/Dune-Guild-Lobby-1.1.0.zip`](../worlds/Dune-Guild-Lobby-1.1.0.zip); the deterministic builder and runtime companion are here. It does not replace a planet world. - -![Actual Minecraft Navigator chamber](previews/actual-1.1.0/navigator-chamber.jpg) - -The image above is an actual Minecraft 1.21.4 client capture of the rebuilt world, using vanilla rendering. Version 1.1.0 replaces the simplified 1.0.0 draft. It has opaque interior walls, enclosed connecting halls and flat ceilings; no outside or sky views. The original AI overview remains in previews as a historical reference, not evidence of the delivered build. The independently decoded block plan is in previews/actual-1.1.0/. - -## Rooms - -| Room | Centre X/Z | Contents | -|---|---|---| -| Central spawn | 0 / 0 | Safe arrival at **0.5, 81, 10.5**, facing north; monumental amber Navigator tank on a broad stepped dais, upper galleries and Guild liaison | -| Starport / teleport | -78 / -58 | Dune II inspired square arrival apron, grounded frigate, control tower and **five raised launch pads** with striped edges, lights and destination consoles | -| Official Exchange | -66 / 40 | CHOAM counters, commodities, storage and Exchange Broker | -| News | 62 / -42 | Illustrated dispatch panel, reading benches and interactive news lecterns | -| Rules | 62 / 37 | Charter panel, benches and interactive rules lecterns | -| Smuggler exchange | -66 / 101 | Enclosed dim side passage, framed paintings, screens, brown awnings, pipes, crates and worn copper; separate **water** and **spice** seller NPCs | - -All rooms connect by enclosed corridors. Launch consoles ask for confirmation. There are no Nether portals: the starport is a landing/launch design. - -## Install the already built world - -1. Use a **separate lobby Paper backend**. Stop that server before copying files. Leave existing planet servers and worlds in place. -2. Extract the ZIP into the server directory. It contains `guild_lobby/`, `plugins/DuneLobby-1.1.0.jar`, and these setup instructions. Do not extract over an existing `guild_lobby`; preserve it separately first. -3. Install [ImageFrame from Spigot](https://www.spigotmc.org/resources/106031/). The tested version is **2026.1.5.0**, which lists Minecraft 1.21.4 support. With Python available, `python DuneLobby/tools/install_imageframe.py /path/to/lobby-server` downloads that exact dependency and verifies its SHA256. The third-party JAR is not vendored in this repository/package. Dependency source: (GPL-3.0). -4. Start Paper. DuneLobby loads `guild_lobby` as **THE_END**, preserves the saved blocks and restores the 25 ImageFrame paintings. Artwork is included in DuneLobby's JAR, so no remote artwork hosting is required. ImageFrame map IDs are allocated for this server rather than trusting IDs from another world. Keep ImageFrame installed to render the pictures. -5. `/lobby` returns to central spawn. Console `dunelobby verify` checks spawn clearance, room/pad/vendor accessibility, NPCs and artwork. Console `dunelobby artwork` restores decorations if required; it reuses registered image maps instead of creating duplicates. - -DuneLobby creates a world only when **console** runs `dunelobby build`, and refuses if a folder with that name already exists. This command is for reproducing a new world, not installing the included map. No planet file or existing lobby structure is regenerated on startup. To replace a 1.0.0 lobby, stop the server, preserve that old guild_lobby folder, and import the new ZIP; merely updating the JAR will not replace the draft geometry. - -Keep Paper's default primary world as a small bootstrap world; the plugin loads the End lobby as a secondary world and routes joins/respawns there. Do not use `guild_lobby` as `level-name`, since that loads it as the primary overworld before the plugin can select THE_END. Example **lobby backend** settings: - -```properties -level-name=lobby_bootstrap -level-type=minecraft:flat -generator-settings={"layers":[],"biome":"minecraft:the_void","structures":{}} -generate-structures=false -allow-nether=false -spawn-protection=0 -``` - -For an existing multiworld server instead of a dedicated backend, set `join-at-lobby: false` and `respawn-at-lobby: false` in `plugins/DuneLobby/config.yml` to preserve other plugins' routing. The shipped ZIP is a **Paper multiworld import**, not a standalone singleplayer save or a schematic. DuneLobby supplies the void generator and prevents new End terrain around the build. - -## Network and economy - -- Optional DuneEss: launch consoles call the player's existing `/duneess travel `, preserving configured fares, permissions and Arrakis checks. The Navigator liaison opens `/duneess travel`. -- Without DuneEss: consoles teleport to an already loaded planet world, or request a Velocity/Bungee `Connect` using the names in the lobby config. Requests have no delivery acknowledgment and charge no fare. Configure and test the destinations on your own network; no live server deployment is performed by this package. -- The Exchange Broker opens `/dune exchange` when DuneCore is installed. Without DuneCore it explains that the official market needs that integration; no fake Solaris balances are created. -- Both smuggler sellers work without DuneCore/Vault: one drinking water potion for 4 emeralds, one orange-dye spice sample for 8 emeralds (configurable). **These are lobby barter goods**, deliberately not tagged finite Arrakis water or redeemable DuneCore spice. This avoids minting Solaris or faction rewards outside the existing economy. They are stationary, named, invulnerable villagers with custom merchant menus. -- News and rules lecterns display the text in the companion config. Run `dunelobby reload` after edits. Illustrated noticeboards are static artwork, not a live website feed. - -Velocity example (adapt the backend address): - -```toml -[servers] -lobby = "127.0.0.1:25570" -# Keep existing planet entries. -try = ["lobby"] - -[advanced] -bungee-plugin-message-channel = true -``` - -Use your existing modern forwarding configuration and forwarding secret. Do not install DuneTerrain on a dedicated lobby backend, since it is intended to create a selected planet. DuneCore/DuneEss remain optional and their shared economy/database setup is unchanged. - -## Protection and build - -Visitors cannot break/place blocks, manipulate frames, use ordinary container blocks or damage entities in the lobby. Explosions do not damage blocks, hostile spawns are suppressed, and falling below the build returns the player to spawn. Operators have `dunelobby.build` for maintenance; other worlds are unaffected. This companion does not implement a general-purpose region protection system for other plugins' console edits. - -Build the companion with `gradle -p DuneLobby build` using Java 21 and Gradle 8.14+. Typographic boards are reproducible with `python DuneLobby/tools/prepare_boards.py` (Pillow). Existing project artwork is copied unchanged from `docs/artwork`. The build embeds the local artwork; it downloads no artwork. - -Design references: [1984 Navigator / heighliner production artwork](https://www.duneinfo.com/arrakis/navigators/), [Dune II Starport](https://dunerts.wiki.gg/wiki/Starport_(Dune_II)). Reference designs are interpreted in blocks; the original game sprites and film stills are not included as new assets. - -## Validation - -See `VALIDATION.md` for the recorded build, actual saved-world checks and limitations. The package includes `manifest.json` with file hashes. No live network, paid Solaris transfer or real player account is used in local validation. - -## Rendering and compatibility - -There are 25 ImageFrame paintings (1,024 map tiles), plus framed item displays and lit copper/blackstone borders. Local artwork is embedded in the companion JAR. No client mod or shader is required. The visual check used the installed Java client against a loopback-only test server. Computer control was then stopped by the user; no further app input was issued. - -The companion disables the End dragon-fight controller using the tested Paper 1.21.4 ServerLevel.setDragonFight API through a narrow reflection adapter. This prevents a boss bar, dragon and exit-portal generation after a real player joins. Other Paper versions require validation; incompatible versions report an explicit error instead of silently claiming the lobby is ready. diff --git a/DuneLobby/VALIDATION.md b/DuneLobby/VALIDATION.md deleted file mode 100644 index f73d55c6..00000000 --- a/DuneLobby/VALIDATION.md +++ /dev/null @@ -1,31 +0,0 @@ -# Guild lobby 1.1.0 validation — 2026-10-18 - -This rebuild supersedes the simplified 1.0.0 draft. The current package is `worlds/Dune-Guild-Lobby-1.1.0.zip` (21,383,329 bytes), SHA256 `f66c0bc3192a1b1010b28e7123af60133b7ec32a2eb5fc62ca88e6d36a2bc5cf`. - -## Changes and visual evidence - -- Monumental Navigator tank, broad stepped dais, gold floor medallion, upper galleries, carved blackstone columns, short diagonal connections and furnished rooms replace the sparse grid layout. -- All connecting halls and room boundaries are opaque interiors with flat ceilings. There are no exterior/sky views. The outer enclosure is opaque too. -- Twenty-five ImageFrame paintings use 1,024 map tiles; fifteen separate item displays decorate the official market. Water and spice sellers remain separate NPCs in the dim, screened smuggler market. -- `previews/actual-1.1.0/navigator-chamber.jpg` is an actual installed Minecraft Java 1.21.4 client window capture, using vanilla rendering. It was displayed to the user before their approval. It is not an AI rendering. The historical concept remains separately labelled. -- The real client joined the local loopback test server. An End dragon-controller issue discovered during that check was corrected: the companion disables the controller through the tested Paper 1.21.4 adapter, preventing the boss bar, dragon and vanilla exit portal from appearing. -- Computer control was stopped by the user after the visual check. No further app input was issued. The previously captured game image was exported as an artifact through file operations. - -## Checks completed - -1. Java 21 / Gradle 8.14 build passed against Paper API 1.21.4. There is no separate unit-test suite; these checks run the real server and decode the saved world. -2. Built a fresh world on Paper 1.21.4 build 232 with ImageFrame 2026.1.5.0. The builder performed 565,328 block placements. -3. Restarted with the final companion, restored all 25 image maps and verified the saved world without regenerating its blocks. -4. Runtime flood-fill and environment checks passed: six rooms, both seller approaches, five launch pads, four named NPCs, 1,024 artwork frames, clear supported spawn, opaque flat ceiling/enclosure and no active dragon battle controller. -5. After clean shutdown, an independent Anvil/NBT reader confirmed data version 4189, spawn 0/81/10, 386,882 non-air blocks in the inspected height range (including enclosure), four villagers, 1,024 glowing painting frames, fifteen item frames, six text labels, and no Ender Dragon. It checked the flat ceiling and outer walls directly from saved blocks. Results and an actual-block plan are in `previews/actual-1.1.0/`. -6. ZIP integrity check passed. The package includes a per-file SHA256 manifest, the actual saved End chunks, companion JAR and setup/dependency installer. Locks, UUID identity files, player data and the server executable are excluded. Local test servers were shut down. - -Final runtime output: - -```text -GUILD_VERIFY PASS walkable=13791 artwork=1024 [] -``` - -## Limits - -The screenshot verifies the Navigator interior; it is not a claim of pixel-for-pixel equivalence to the earlier AI art. Other room geometry, paint placement and connectivity were checked from the saved world and running server. Merchant clicks, paid Solaris transfers, remote proxy destinations and production concurrency were not exercised. No live server was deployed. The smuggler merchants use emerald barter and sample goods, separate from redeemable faction rewards. Paper versions other than the tested 1.21.4 require validation because the dragon-controller adapter is version-specific. Install the new world folder to replace a 1.0.0 draft; updating only the JAR deliberately leaves existing blocks intact. diff --git a/DuneLobby/artwork/arrakis-cover.png b/DuneLobby/artwork/arrakis-cover.png deleted file mode 100644 index 4cc00ac0..00000000 Binary files a/DuneLobby/artwork/arrakis-cover.png and /dev/null differ diff --git a/DuneLobby/artwork/exchange.png b/DuneLobby/artwork/exchange.png deleted file mode 100644 index c92d16ea..00000000 Binary files a/DuneLobby/artwork/exchange.png and /dev/null differ diff --git a/DuneLobby/artwork/guild-navigator.png b/DuneLobby/artwork/guild-navigator.png deleted file mode 100644 index ffea0c0f..00000000 Binary files a/DuneLobby/artwork/guild-navigator.png and /dev/null differ diff --git a/DuneLobby/artwork/news.png b/DuneLobby/artwork/news.png deleted file mode 100644 index 64e38914..00000000 Binary files a/DuneLobby/artwork/news.png and /dev/null differ diff --git a/DuneLobby/artwork/rules.png b/DuneLobby/artwork/rules.png deleted file mode 100644 index e54da647..00000000 Binary files a/DuneLobby/artwork/rules.png and /dev/null differ diff --git a/DuneLobby/artwork/shai-hulud-encounter.png b/DuneLobby/artwork/shai-hulud-encounter.png deleted file mode 100644 index 410d5033..00000000 Binary files a/DuneLobby/artwork/shai-hulud-encounter.png and /dev/null differ diff --git a/DuneLobby/artwork/sietch-panorama.png b/DuneLobby/artwork/sietch-panorama.png deleted file mode 100644 index 8b70aa46..00000000 Binary files a/DuneLobby/artwork/sietch-panorama.png and /dev/null differ diff --git a/DuneLobby/artwork/smuggler-spice-mission.png b/DuneLobby/artwork/smuggler-spice-mission.png deleted file mode 100644 index 4b3aa32c..00000000 Binary files a/DuneLobby/artwork/smuggler-spice-mission.png and /dev/null differ diff --git a/DuneLobby/artwork/smuggler-water-camp.png b/DuneLobby/artwork/smuggler-water-camp.png deleted file mode 100644 index 07236060..00000000 Binary files a/DuneLobby/artwork/smuggler-water-camp.png and /dev/null differ diff --git a/DuneLobby/artwork/spice-expedition.png b/DuneLobby/artwork/spice-expedition.png deleted file mode 100644 index b9b50e68..00000000 Binary files a/DuneLobby/artwork/spice-expedition.png and /dev/null differ diff --git a/DuneLobby/artwork/world-0.png b/DuneLobby/artwork/world-0.png deleted file mode 100644 index 8bcb66b3..00000000 Binary files a/DuneLobby/artwork/world-0.png and /dev/null differ diff --git a/DuneLobby/artwork/world-1.png b/DuneLobby/artwork/world-1.png deleted file mode 100644 index adf80037..00000000 Binary files a/DuneLobby/artwork/world-1.png and /dev/null differ diff --git a/DuneLobby/artwork/world-2.png b/DuneLobby/artwork/world-2.png deleted file mode 100644 index 031610ea..00000000 Binary files a/DuneLobby/artwork/world-2.png and /dev/null differ diff --git a/DuneLobby/artwork/world-3.png b/DuneLobby/artwork/world-3.png deleted file mode 100644 index ec6e5cf6..00000000 Binary files a/DuneLobby/artwork/world-3.png and /dev/null differ diff --git a/DuneLobby/artwork/world-4.png b/DuneLobby/artwork/world-4.png deleted file mode 100644 index 7ba50f52..00000000 Binary files a/DuneLobby/artwork/world-4.png and /dev/null differ diff --git a/DuneLobby/build.gradle.kts b/DuneLobby/build.gradle.kts deleted file mode 100644 index 9f3cdafb..00000000 --- a/DuneLobby/build.gradle.kts +++ /dev/null @@ -1,19 +0,0 @@ -plugins { java } -group = "com.example" -version = "1.1.0" -repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") } -dependencies { compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") } -java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } -tasks.withType { options.encoding = "UTF-8" } -tasks.processResources { from("artwork") { into("artwork") } } - -repositories { maven("https://repo.opencollab.dev/main/") } -dependencies { compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") } -dependencies { - testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") - testRuntimeOnly("org.junit.platform:junit-platform-launcher") -} -tasks.test { useJUnitPlatform() } -sourceSets.main { java.srcDir("../gui-common/src/main/java") } - -tasks.jar { archiveFileName.set("DuneRealms-Lobby.jar") } diff --git a/DuneLobby/previews/README.md b/DuneLobby/previews/README.md deleted file mode 100644 index b31d870a..00000000 --- a/DuneLobby/previews/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Delivered 1.1.0 interior - -ctual-1.1.0/navigator-chamber.jpg is the actual installed Minecraft Java 1.21.4 client, captured during local visual verification. It is not an AI rendering. ctual-1.1.0/saved-world-plan.png and JSON are decoded from the saved blocks. The approved revision uses opaque interiors and flat ceilings; the older roofless concept below is retained only as historical design material. - -# Lobby previews - -- `guild-lobby-concept.png`: built-in ImageGen concept rendering, generated 2026-10-18. This is a visual design reference, not a Minecraft screenshot. -- `saved-world-plan.png` and `.json`: rendered and inspected from the actual saved Anvil world by `tools/inspect_world.py`; no image-generation model is used for the plan. - -Final ImageGen prompt (reference image was the preceding five-room starport concept): - -> Update this Minecraft Dune Vaerkring lobby rendering with a SIXTH room, a shady SMUGGLER EXCHANGE. Preserve every existing room: central spawn with amber Guild Navigator tank, Dune II-inspired STARPORT / TELEPORT upper left with square landing and launch pads and block-built frigate, official EXCHANGE left, NEWS upper right, RULES right, purple End atmosphere and gold/blackstone architecture. Widen framing or pull back as needed to show all six distinct connected rooms clearly. Add the new smugglers' den as a substantial enclosed annex in the lower foreground below the official Exchange, attached via a narrow dim side corridor branching off the official Exchange. It must be visibly different: lower vaulted ceiling (removed for cutaway), dark worn stone, rusty copper pipes, patchwork brown cloth awnings/screens, stacked barrels and crates, low amber lanterns, discreet violet accents. TWO separate Minecraft villager seller NPCs behind separate screened market counters: WATER SELLER next to blue glass water vessels and a cauldron, SPICE SELLER beside orange spice samples and sacks represented by brown blocks and barrels. Small clear labels over counters 'WATER' and 'SPICE'. Shady illicit back-room atmosphere but navigable and readable. Clearly label the new annex 'SMUGGLER EXCHANGE' with matching clean external architectural callout. Keep five other callouts correctly pointing to their rooms. Floor of annex is fully supported and bounded, no unsafe holes; visible corridor connection. High-quality architectural Minecraft shader concept overview, block-built geometry and pixel textures, no photoreal smooth creatures. Retain wall artwork in framed maps. One wide coherent elevated isometric roofless cutaway, clean presentation, no HUD or watermark. diff --git a/DuneLobby/previews/actual-1.1.0/navigator-chamber.jpg b/DuneLobby/previews/actual-1.1.0/navigator-chamber.jpg deleted file mode 100644 index 7685593e..00000000 Binary files a/DuneLobby/previews/actual-1.1.0/navigator-chamber.jpg and /dev/null differ diff --git a/DuneLobby/previews/actual-1.1.0/saved-world-plan.json b/DuneLobby/previews/actual-1.1.0/saved-world-plan.json deleted file mode 100644 index 582604bb..00000000 --- a/DuneLobby/previews/actual-1.1.0/saved-world-plan.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "minecraft": "1.21.4", - "data_version": 4189, - "spawn": [ - 0, - 81, - 10 - ], - "saved_non_air_blocks_in_build_height": 386882, - "entities": { - "minecraft:glow_item_frame": 1024, - "minecraft:text_display": 6, - "minecraft:item_frame": 15, - "minecraft:villager": 4 - }, - "npc_roles": { - "exchange": 1, - "water": 1, - "spice": 1, - "liaison": 1 - }, - "checks": "PASS: saved spawn, five launch pads, six rooms, four unique NPCs, 1024 artwork frames, opaque enclosure and flat ceiling, no dragon" -} diff --git a/DuneLobby/previews/actual-1.1.0/saved-world-plan.png b/DuneLobby/previews/actual-1.1.0/saved-world-plan.png deleted file mode 100644 index 5964125b..00000000 Binary files a/DuneLobby/previews/actual-1.1.0/saved-world-plan.png and /dev/null differ diff --git a/DuneLobby/previews/guild-lobby-concept.png b/DuneLobby/previews/guild-lobby-concept.png deleted file mode 100644 index f280684b..00000000 Binary files a/DuneLobby/previews/guild-lobby-concept.png and /dev/null differ diff --git a/DuneLobby/previews/saved-world-plan.json b/DuneLobby/previews/saved-world-plan.json deleted file mode 100644 index b97981fa..00000000 --- a/DuneLobby/previews/saved-world-plan.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "minecraft": "1.21.4", - "data_version": 4189, - "spawn": [ - 0, - 81, - 10 - ], - "saved_non_air_blocks_in_build_height": 109535, - "entities": { - "minecraft:glow_item_frame": 276, - "minecraft:villager": 4 - }, - "npc_roles": { - "exchange": 1, - "water": 1, - "spice": 1, - "liaison": 1 - }, - "checks": "PASS: saved spawn, five launch pads, six rooms, four unique NPCs, 276 artwork frames, no dragon" -} diff --git a/DuneLobby/previews/saved-world-plan.png b/DuneLobby/previews/saved-world-plan.png deleted file mode 100644 index 99d9f542..00000000 Binary files a/DuneLobby/previews/saved-world-plan.png and /dev/null differ diff --git a/DuneLobby/settings.gradle.kts b/DuneLobby/settings.gradle.kts deleted file mode 100644 index be5a57e8..00000000 --- a/DuneLobby/settings.gradle.kts +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = "DuneLobby" diff --git a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java deleted file mode 100644 index 1181cdae..00000000 --- a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.example.dunelobby; - -import org.bukkit.*; -import org.bukkit.block.BlockFace; -import org.bukkit.command.*; -import org.bukkit.entity.*; -import org.bukkit.event.*; -import org.bukkit.event.block.*; -import org.bukkit.event.entity.*; -import org.bukkit.event.hanging.HangingBreakEvent; -import org.bukkit.event.inventory.*; -import org.bukkit.event.player.*; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.generator.WorldInfo; -import org.bukkit.inventory.*; -import org.bukkit.inventory.meta.*; -import org.bukkit.persistence.PersistentDataType; -import org.bukkit.plugin.java.JavaPlugin; -import java.io.*; -import java.nio.file.*; -import java.util.*; - -/** Separate optional lobby backend; never changes planet terrain or existing world blocks. */ -public final class DuneLobby extends JavaPlugin implements Listener, CommandExecutor { - private World lobby; - private NamespacedKey roleKey; - private final Map travelCooldown = new HashMap<>(); - private static final class TravelMenu implements InventoryHolder { - final String planet; final Inventory inventory; - TravelMenu(String planet) { this.planet=planet; inventory=Bukkit.createInventory(this,9,"Guild departure: "+planet); } - public Inventory getInventory() { return inventory; } - } - public static final class VoidGenerator extends ChunkGenerator { - @Override public void generateNoise(WorldInfo info, Random random,int x,int z,ChunkData data) {} - @Override public boolean shouldGenerateNoise() { return false; } - @Override public boolean shouldGenerateSurface() { return false; } - @Override public boolean shouldGenerateBedrock() { return false; } - @Override public boolean shouldGenerateCaves() { return false; } - @Override public boolean shouldGenerateDecorations() { return false; } - @Override public boolean shouldGenerateMobs() { return false; } - @Override public boolean shouldGenerateStructures() { return false; } - } - @Override public void onEnable() { - saveDefaultConfig(); roleKey=new NamespacedKey(this,"role"); - getCommand("lobby").setExecutor(this); getCommand("dunelobby").setExecutor(this); - Bukkit.getPluginManager().registerEvents(this,this); - Bukkit.getMessenger().registerOutgoingPluginChannel(this,"BungeeCord"); - Bukkit.getScheduler().runTask(this,()-> { - File folder=new File(Bukkit.getWorldContainer(),getConfig().getString("world","guild_lobby")); - if(LobbyWorldStorage.imported(new File(folder,"level.dat"))) { - loadWorld(); ensureNpcs(); - if(Bukkit.getPluginManager().isPluginEnabled("ImageFrame")) Bukkit.getScheduler().runTaskLater(this,()->new LobbyArtwork(this,lobby).restore(),80); - getLogger().info("Existing Guild lobby loaded; structure left unchanged."); - } else getLogger().info("No lobby imported. Console: dunelobby build to create a NEW world."); - }); - } - private void loadWorld() { - String name=getConfig().getString("world","guild_lobby"); - if(!name.matches("[A-Za-z0-9_-]+")) throw new IllegalArgumentException("world must be a simple folder name"); - lobby=Bukkit.createWorld(new WorldCreator(name).environment(World.Environment.THE_END).generator(new VoidGenerator()).generateStructures(false)); - disableDragonBattle(); - lobby.setSpawnLocation(new Location(lobby,.5,81,10.5,180,0)); - lobby.setGameRule(GameRule.DO_MOB_SPAWNING,false); lobby.setGameRule(GameRule.DO_FIRE_TICK,false); - lobby.setGameRule(GameRule.MOB_GRIEFING,false); lobby.setGameRule(GameRule.DO_DAYLIGHT_CYCLE,false); - lobby.setGameRule(GameRule.DO_WEATHER_CYCLE,false); lobby.setGameRule(GameRule.DO_INSOMNIA,false); - lobby.setGameRule(GameRule.KEEP_INVENTORY,true); lobby.setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS,false); - lobby.setGameRule(GameRule.SPAWN_RADIUS,0); lobby.setTime(18000); lobby.setDifficulty(Difficulty.PEACEFUL); - lobby.setPVP(false); lobby.getWorldBorder().setCenter(-16,16); lobby.getWorldBorder().setSize(330); - lobby.setKeepSpawnInMemory(false); - // Keep the bounded lobby footprint loaded: NPC/art restoration must see all rooms. - for(int cx=-8;cx<=6;cx++) for(int cz=-7;cz<=8;cz++) lobby.addPluginChunkTicket(cx,cz,this); - for(EnderDragon dragon:lobby.getEntitiesByClass(EnderDragon.class)) dragon.remove(); - } - private void disableDragonBattle() { - // Paper 1.21.4 exposes ServerLevel.setDragonFight. Clearing the controller prevents - // both a boss bar and vanilla portal/dragon generation after a real player joins. - try { - Object handle=lobby.getClass().getMethod("getHandle").invoke(lobby); - var setter=Arrays.stream(handle.getClass().getMethods()) - .filter(m->m.getName().equals("setDragonFight")&&m.getParameterCount()==1).findFirst().orElseThrow(); - setter.invoke(handle,new Object[]{null}); - } catch(ReflectiveOperationException|NoSuchElementException e) { - throw new IllegalStateException("This lobby requires the tested Paper 1.21.4 dragon-controller API",e); - } - } - private boolean inLobby(World world) { return lobby!=null && world.equals(lobby); } - private void ensureNpcs() { - for(int x=-8;x<=6;x++) for(int z=-6;z<=8;z++) lobby.getChunkAt(x,z).load(); - npc("liaison","Vaerkring Routekeeper Liaison",13,87,-11,Villager.Profession.CLERIC); - npc("exchange","Koopkring Exchange Broker",-82,81,23,Villager.Profession.LIBRARIAN); - npc("water","Discreet Welvaarder",-78,81,110,Villager.Profession.FISHERMAN); - npc("spice","Discreet Spice Seller",-54,81,110,Villager.Profession.LEATHERWORKER); - } - private void npc(String role,String name,int x,int y,int z,Villager.Profession profession) { - for(Villager entity:lobby.getEntitiesByClass(Villager.class)) if(role.equals(entity.getPersistentDataContainer().get(roleKey,PersistentDataType.STRING))) return; - lobby.spawn(new Location(lobby,x+.5,y,z+.5,180,0),Villager.class,v->{ - v.setCustomName(ChatColor.GOLD+name); v.setCustomNameVisible(true); v.setAI(false); v.setSilent(true); - v.setInvulnerable(true); v.setPersistent(true); v.setRemoveWhenFarAway(false); v.setProfession(profession); - v.setVillagerType(role.equals("water")||role.equals("spice")?Villager.Type.SWAMP:Villager.Type.DESERT); - v.getPersistentDataContainer().set(roleKey,PersistentDataType.STRING,role); v.setRecipes(List.of()); - }); - } - @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) { - if(command.getName().equals("lobby")) { - if(sender instanceof Player p) { if(lobby==null) p.sendMessage("The Guild lobby is not loaded."); else p.teleport(lobby.getSpawnLocation()); } - return true; - } - if(args.length==0) { sender.sendMessage("/dunelobby build | artwork | verify | reload"); return true; } - switch(args[0].toLowerCase(Locale.ROOT)) { - case "build" -> { - if(sender instanceof Player) { sender.sendMessage("World creation is console-only."); return true; } - File target=new File(Bukkit.getWorldContainer(),getConfig().getString("world","guild_lobby")); - if(LobbyWorldStorage.buildBlocked(target) || lobby!=null) { sender.sendMessage("Refusing to overwrite an existing world. Import it or choose a new world name."); return true; } - loadWorld(); long n=new LobbyBuilder(lobby).build(); ensureNpcs(); lobby.save(); - try { Files.writeString(lobby.getWorldFolder().toPath().resolve("DUNE-LOBBY.txt"),"DuneLobby 1.1.0 / Minecraft Java 1.21.4 / End lighting, opaque enclosure / spawn 0.5 81 10.5 yaw 180\n"); } - catch(IOException e) { getLogger().warning(e.toString()); } - sender.sendMessage("GUILD_BUILD_COMPLETE: "+n+" placements. Run dunelobby artwork, then dunelobby verify."); - } - case "artwork" -> { if(lobby!=null) new LobbyArtwork(this,lobby).install(); } - case "verify" -> { if(lobby==null) sender.sendMessage("Lobby not loaded."); else Bukkit.getScheduler().runTaskLater(this,()->verify(sender),10); } - case "reload" -> { reloadConfig(); sender.sendMessage("Rules, notices, trade prices and routing reloaded."); } - default -> sender.sendMessage("Unknown lobby operation."); - } - return true; - } - private void verify(CommandSender sender) { - List failures=new ArrayList<>(); - Location s=lobby.getSpawnLocation(); - if(lobby.getEnvironment()!=World.Environment.THE_END) failures.add("environment"); - if(lobby.getEnderDragonBattle()!=null) failures.add("dragon battle controller active"); - if(!lobby.getBlockAt(s.getBlockX(),80,s.getBlockZ()).getType().isSolid() || !lobby.getBlockAt(s.getBlockX(),81,s.getBlockZ()).isPassable() || !lobby.getBlockAt(s.getBlockX(),82,s.getBlockZ()).isPassable()) failures.add("spawn clearance"); - // Flood-fill two-block-high walkable cells with step height <= 1. - Set seen=new HashSet<>(); ArrayDeque todo=new ArrayDeque<>(); todo.add(new int[]{0,81,10}); - while(!todo.isEmpty()) { - int[] p=todo.removeFirst(); String k=p[0]+","+p[1]+","+p[2]; - if(p[0]<-120||p[0]>92||p[2]<-94||p[2]>128||p[1]<79||p[1]>101||!seen.add(k)) continue; - if(!walkable(p[0],p[1],p[2])) { seen.remove(k); continue; } - for(int[] d:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}) for(int dy:new int[]{0,1,-1}) { - int x=p[0]+d[0],y=p[1]+dy,z=p[2]+d[1]; - if(!seen.contains(x+","+y+","+z) && walkable(x,y,z)) { todo.add(new int[]{x,y,z}); break; } - } - } - int[][] targets={{0,81,10},{-66,81,35},{62,81,-36},{66,81,30},{-66,81,100},{-78,81,-32},{-78,81,109},{-54,81,109}}; - for(int[] p:targets) if(!seen.contains(p[0]+","+p[1]+","+p[2])) failures.add("unreachable "+Arrays.toString(p)); - for(int[] p:LobbyBuilder.PADS) if(!seen.contains(p[0]+",83,"+p[1])) failures.add("launch pad "+Arrays.toString(p)); - for(int[] p:new int[][]{{0,10},{-78,-58},{-66,40},{62,-42},{62,37},{-66,101},{-30,-21},{31,21}}) - if(!lobby.getBlockAt(p[0],128,p[1]).getType().isOccluding()) failures.add("missing flat ceiling "+Arrays.toString(p)); - for(int y:new int[]{81,96,120}) for(int[] p:new int[][]{{-126,0},{96,0},{0,-98},{0,130}}) - if(!lobby.getBlockAt(p[0],y,p[1]).getType().isOccluding()) failures.add("visible sky boundary "+Arrays.toString(p)); - for(String role:List.of("liaison","exchange","water","spice")) if(lobby.getEntitiesByClass(Villager.class).stream().noneMatch(v->role.equals(v.getPersistentDataContainer().get(roleKey,PersistentDataType.STRING)))) failures.add("missing NPC "+role); - long art=lobby.getEntitiesByClass(ItemFrame.class).stream().filter(v->v.getPersistentDataContainer().has(new NamespacedKey(this,"art"),PersistentDataType.STRING)).count(); - if(art!=LobbyArtwork.tileCount()) failures.add("art frames "+art+" != "+LobbyArtwork.tileCount()); - String result="GUILD_VERIFY "+(failures.isEmpty()?"PASS":"FAIL")+" walkable="+seen.size()+" artwork="+art+" "+failures; - sender.sendMessage(result); - try { Files.writeString(getDataFolder().toPath().resolve("verification.txt"),result+"\n"); } catch(IOException e) { getLogger().warning(e.toString()); } - } - private boolean walkable(int x,int y,int z) { - return lobby.getBlockAt(x,y-1,z).getType().isSolid() && lobby.getBlockAt(x,y,z).isPassable() && !lobby.getBlockAt(x,y,z).isLiquid() && lobby.getBlockAt(x,y+1,z).isPassable(); - } - @EventHandler public void join(PlayerJoinEvent e) { - if(lobby!=null && getConfig().getBoolean("join-at-lobby",true)) Bukkit.getScheduler().runTask(this,()->e.getPlayer().teleport(lobby.getSpawnLocation())); - } - @EventHandler public void respawn(PlayerRespawnEvent e) { if(lobby!=null && getConfig().getBoolean("respawn-at-lobby",true)) e.setRespawnLocation(lobby.getSpawnLocation()); } - @EventHandler public void move(PlayerMoveEvent e) { - if(inLobby(e.getPlayer().getWorld()) && e.getTo()!=null && e.getTo().getY()<65) e.setTo(lobby.getSpawnLocation()); - } - @EventHandler public void damage(EntityDamageEvent e) { if(inLobby(e.getEntity().getWorld())) e.setCancelled(true); } - @EventHandler public void spawn(CreatureSpawnEvent e) { - if(inLobby(e.getLocation().getWorld()) && (e.getEntity() instanceof EnderDragon || e.getSpawnReason()!=CreatureSpawnEvent.SpawnReason.CUSTOM)) e.setCancelled(true); - } - @EventHandler public void breakBlock(BlockBreakEvent e) { if(inLobby(e.getBlock().getWorld())&&!e.getPlayer().hasPermission("dunelobby.build")) e.setCancelled(true); } - @EventHandler public void placeBlock(BlockPlaceEvent e) { if(inLobby(e.getBlock().getWorld())&&!e.getPlayer().hasPermission("dunelobby.build")) e.setCancelled(true); } - @EventHandler public void explode(EntityExplodeEvent e) { if(inLobby(e.getLocation().getWorld())) e.blockList().clear(); } - @EventHandler public void blockExplode(BlockExplodeEvent e) { if(inLobby(e.getBlock().getWorld())) e.blockList().clear(); } - @EventHandler public void hanging(HangingBreakEvent e) { if(inLobby(e.getEntity().getWorld())) e.setCancelled(true); } - @EventHandler public void entityInteract(PlayerInteractEntityEvent e) { - if(!inLobby(e.getPlayer().getWorld())) return; - if(e.getRightClicked() instanceof ItemFrame) { e.setCancelled(true); return; } - String role=e.getRightClicked().getPersistentDataContainer().get(roleKey,PersistentDataType.STRING); - if(role==null) return; e.setCancelled(true); if(e.getHand()!=EquipmentSlot.HAND) return; - switch(role) { - case "liaison" -> { if(Bukkit.getPluginCommand("duneess")!=null) e.getPlayer().performCommand("duneess travel"); else departure(e.getPlayer(),"arrakis"); } - case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"Koopkring market integration requires DuneCore on this backend."); } - case "water","spice" -> trade(e.getPlayer(),role); - } - } - private void trade(Player player,String role) { - boolean water=role.equals("water"); - ItemStack result=new ItemStack(water?Material.POTION:Material.ORANGE_DYE); - ItemMeta meta=result.getItemMeta(); meta.setDisplayName(ChatColor.GOLD+(water?"Smuggled drinking water":"Smuggler spice sample")); - meta.setLore(List.of("Guild lobby barter goods","Not redeemable for Solaris or faction rewards")); - if(meta instanceof PotionMeta potion) potion.setBasePotionType(org.bukkit.potion.PotionType.WATER); - result.setItemMeta(meta); - int price=Math.max(1,Math.min(64,getConfig().getInt(water?"water-price-emeralds":"spice-price-emeralds",water?4:8))); - MerchantRecipe recipe=new MerchantRecipe(result,0,999,false,0,0f); recipe.addIngredient(new ItemStack(Material.EMERALD,price)); - Merchant merchant=Bukkit.createMerchant(water?"Discreet Welvaarder":"Discreet Spice Seller"); merchant.setRecipes(List.of(recipe)); player.openMerchant(merchant,true); - } - @EventHandler public void interact(PlayerInteractEvent e) { - if(!inLobby(e.getPlayer().getWorld()) || e.getClickedBlock()==null || e.getAction()!=Action.RIGHT_CLICK_BLOCK) return; - var b=e.getClickedBlock(); e.setCancelled(true); if(e.getHand()!=EquipmentSlot.HAND) return; - int x=b.getX(),z=b.getZ(); - for(int i=0;i=p[1]-9 && z<=p[1]-7) { departure(e.getPlayer(),LobbyBuilder.PLANETS.get(i)); return; } } - if(b.getType()==Material.LECTERN) { - boolean rules=z>0; List text=getConfig().getStringList(rules?"rules":"news"); - com.example.dunegui.NativeMenus.show(this,e.getPlayer(),rules?"Guild Charter":"Guild News",String.join("\n\n",text),List.of( - new com.example.dunegui.NativeMenus.Choice("Close","",e.getPlayer()::closeInventory))); - - } - } - private void departure(Player player,String planet) { - TravelMenu menu=new TravelMenu(planet); ItemStack confirm=new ItemStack(Material.LIME_CONCRETE); ItemMeta meta=confirm.getItemMeta(); - meta.setDisplayName("Confirm departure: "+planet); meta.setLore(List.of("DuneEss fares and access rules apply when installed.")); confirm.setItemMeta(meta); - menu.inventory.setItem(4,confirm); - com.example.dunegui.NativeMenus.show(this,player,"Guild departure",List.of( - new com.example.dunegui.NativeMenus.Choice("Confirm departure: "+planet,"DuneEss fares and access rules apply.",()->depart(player,planet)), - new com.example.dunegui.NativeMenus.Choice("Cancel","",player::closeInventory))); - } - private void depart(Player player,String planet) { - long now=System.currentTimeMillis(); if(now-travelCooldown.getOrDefault(player.getUniqueId(),0L)<5000) return; - travelCooldown.put(player.getUniqueId(),now); - Bukkit.getScheduler().runTask(this,()-> { - player.closeInventory(); - if(Bukkit.getPluginCommand("duneess")!=null) { player.performCommand("duneess travel "+planet); return; } - World target=Bukkit.getWorld(planet); - if(target!=null) { player.teleport(target.getSpawnLocation()); return; } - String server=getConfig().getString("servers."+planet,""); - if(server.isBlank()) { player.sendMessage("No destination configured."); return; } - try { - ByteArrayOutputStream bytes=new ByteArrayOutputStream(); DataOutputStream out=new DataOutputStream(bytes); out.writeUTF("Connect"); out.writeUTF(server); - player.sendPluginMessage(this,"BungeeCord",bytes.toByteArray()); player.sendMessage("Guild departure requested. If you remain here, the destination or proxy is unavailable."); - } catch(IOException ex) { player.sendMessage("Guild departure could not be requested."); } - }); - } - @EventHandler public void drag(InventoryDragEvent e) { if(e.getView().getTopInventory().getHolder() instanceof TravelMenu) e.setCancelled(true); } - @EventHandler public void quit(PlayerQuitEvent e) { travelCooldown.remove(e.getPlayer().getUniqueId()); } - @Override public void onDisable() { if(lobby!=null) lobby.save(); } -} diff --git a/DuneLobby/src/main/java/com/example/dunelobby/LobbyArtwork.java b/DuneLobby/src/main/java/com/example/dunelobby/LobbyArtwork.java deleted file mode 100644 index 6fcd9f47..00000000 --- a/DuneLobby/src/main/java/com/example/dunelobby/LobbyArtwork.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.example.dunelobby; - -import org.bukkit.*; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.*; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.MapMeta; -import org.bukkit.map.MapView; -import org.bukkit.persistence.PersistentDataType; -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.lang.reflect.*; -import java.util.*; -import java.util.concurrent.Future; - -/** Uses ImageFrame's published loader API through reflection; no vendored third-party code. */ -final class LobbyArtwork { - private final DuneLobby plugin; - private final World world; - private final NamespacedKey key; - private static final java.util.concurrent.atomic.AtomicBoolean INSTALLING=new java.util.concurrent.atomic.AtomicBoolean(); - private static final UUID OWNER=UUID.fromString("79a66e02-e519-4489-a153-89f0037d7d11"); - private record Panel(String name,String file,int x,int y,int z,int width,int height) {} - private static final List PANELS=List.of( - new Panel("guild","guild-navigator.png",-3,85,26,6,4), - new Panel("choam","exchange.png",-88,85,20,5,3), - new Panel("expedition","spice-expedition.png",-54,85,20,5,3), - new Panel("news","news.png",57,85,-60,10,5), - new Panel("rules","rules.png",58,85,17,8,5), - new Panel("smugglers","smuggler-water-camp.png",-70,84,122,8,4), - new Panel("arrakis","world-0.png",-110,88,-87,5,4), - new Panel("giedi","world-1.png",-100,88,-87,5,4), - new Panel("kaitain","world-2.png",-90,88,-87,5,4), - new Panel("caladan","world-3.png",-68,88,-87,5,4), - new Panel("sigma","world-4.png",-58,88,-87,5,4), - new Panel("navigator_left","guild-navigator.png",-23,103,-26,6,10), - new Panel("navigator_right","arrakis-cover.png",18,103,-26,6,10), - new Panel("choam_history_south","spice-expedition.png",-86,85,60,10,6), - new Panel("choam_arrakis_south","arrakis-cover.png",-56,85,60,10,6), - new Panel("news_caladan","world-3.png",44,85,-60,6,6), - new Panel("news_kaitain","world-2.png",73,85,-60,6,6), - new Panel("news_expedition_south","spice-expedition.png",47,85,-22,8,6), - new Panel("news_sandworm_south","shai-hulud-encounter.png",69,85,-22,8,6), - new Panel("charter_sietch_south","sietch-panorama.png",45,85,56,10,6), - new Panel("charter_arrakis_south","arrakis-cover.png",70,85,56,10,6), - new Panel("starport_guild_south","guild-navigator.png",-110,86,-29,10,7), - new Panel("starport_arrakis_south","arrakis-cover.png",-59,86,-29,10,7), - new Panel("smuggler_water","smuggler-water-camp.png",-85,84,84,8,5), - new Panel("smuggler_spice","smuggler-spice-mission.png",-57,84,84,8,5)); - LobbyArtwork(DuneLobby plugin,World world) { this.plugin=plugin; this.world=world; key=new NamespacedKey(plugin,"art"); } - static int tileCount() { return PANELS.stream().mapToInt(p->p.width*p.height).sum(); } - static int panelCount() { return PANELS.size(); } - void restore() { install(); } - void install() { - if(!Bukkit.getPluginManager().isPluginEnabled("ImageFrame")) { plugin.getLogger().warning("Install ImageFrame 2026.1.5.0 to restore image decorations; structural lobby remains usable."); return; } - if(!INSTALLING.compareAndSet(false,true)) { plugin.getLogger().info("Artwork restoration is already running."); return; } - // Creation waits for ImageFrame's sync map allocation: run OFF the server thread. - Bukkit.getScheduler().runTaskAsynchronously(plugin,()-> { - try { - ClassLoader cl=Bukkit.getPluginManager().getPlugin("ImageFrame").getClass().getClassLoader(); - Class main=cl.loadClass("com.loohp.imageframe.ImageFrame"); Object manager=main.getField("imageMapManager").get(null); - Class managerType=cl.loadClass("com.loohp.imageframe.objectholders.ImageMapManager"); - // ImageFrame loads saved maps asynchronously after enable. Avoid creating duplicate - // names/map IDs while its storage is still being restored. - Object storage=managerType.getMethod("getStorage").invoke(manager); - Class storageType=cl.loadClass("com.loohp.imageframe.storage.ImageFrameStorage"); - for(int attempt=0;;attempt++) { - var saved=(Set)storageType.getMethod("getAllImageIndexes").invoke(storage); - var loaded=(Collection)managerType.getMethod("getMaps").invoke(manager); - if(loaded.size()>=saved.size()) break; - if(attempt>=60) throw new IllegalStateException("ImageFrame data did not finish loading; retry dunelobby artwork after checking its logs."); - Thread.sleep(1000); - } - Class infoType=cl.loadClass("com.loohp.imageframe.objectholders.NonUpdatableImageMapCreateInfo"); - Class mapType=cl.loadClass("com.loohp.imageframe.objectholders.NonUpdatableStaticImageMap"); - Class dithering=cl.loadClass("com.loohp.imageframe.objectholders.DitheringType"); - Object dither=dithering.getMethod("fromName",String.class).invoke(null,"floyd-steinberg"); - Class loaders=cl.loadClass("com.loohp.imageframe.objectholders.ImageMapLoaders"); - Object loader=loaders.getMethod("getLoader",Class.class,Class.class,String.class,org.bukkit.command.CommandSender.class).invoke(null,mapType,infoType,"image/png",Bukkit.getConsoleSender()); - for(Panel p:PANELS) { - String name="dune_lobby_"+p.name; - Object map=managerType.getMethod("getFromCreator",UUID.class,String.class).invoke(manager,OWNER,name); - if(map==null) { - BufferedImage original; - try(var input=plugin.getResource("artwork/"+p.file)) { if(input==null) throw new IllegalStateException("Missing artwork "+p.file); original=ImageIO.read(input); } - // Map tiles are a display-format conversion; ImageFrame stores and renders them. - BufferedImage canvas=new BufferedImage(p.width*128,p.height*128,BufferedImage.TYPE_INT_ARGB); - var g=canvas.createGraphics(); g.drawImage(original,0,0,canvas.getWidth(),canvas.getHeight(),null); g.dispose(); - BufferedImage[] tiles=new BufferedImage[p.width*p.height]; - for(int i=0;i)loader.getClass().getMethod("create",infoType).invoke(loader,info)).get(); - managerType.getMethod("addMap",cl.loadClass("com.loohp.imageframe.objectholders.ImageMap")).invoke(manager,map); - } - @SuppressWarnings("unchecked") List views=(List)map.getClass().getMethod("getMapViews").invoke(map); - Bukkit.getScheduler().callSyncMethod(plugin,()-> { mount(p,views); return null; }).get(); - } - Bukkit.getScheduler().runTask(plugin,()-> { world.save(); plugin.getLogger().info("GUILD_ARTWORK_COMPLETE: "+PANELS.size()+" ImageFrame panels installed."); }); - } catch(Exception e) { plugin.getLogger().log(java.util.logging.Level.SEVERE,"ImageFrame artwork failed",e); } - finally { INSTALLING.set(false); } - }); - } - private void mount(Panel p,List views) { - Map existing=new HashMap<>(); - for(ItemFrame frame:world.getEntitiesByClass(ItemFrame.class)) { - String tag=frame.getPersistentDataContainer().get(key,PersistentDataType.STRING); if(tag!=null) existing.put(tag,frame); - } - boolean facesNorth=p.name.equals("guild")||p.name.equals("smugglers")||p.name.endsWith("_south"); - int backing=p.z+(facesNorth?1:-1); - for(int x=p.x-1;x<=p.x+p.width;x++) for(int y=p.y-1;y<=p.y+p.height;y++) { - if(x!=p.x-1&&x!=p.x+p.width&&y!=p.y-1&&y!=p.y+p.height) continue; - world.getBlockAt(x,y,backing).setType(Material.WAXED_CUT_COPPER,false); - } - for(int x:new int[]{p.x-2,p.x+p.width+1}) { - for(int y=p.y-1;y<=p.y+p.height;y++) world.getBlockAt(x,y,backing).setType(Material.CHISELED_POLISHED_BLACKSTONE,false); - world.getBlockAt(x,p.y+p.height+1,backing).setType(Material.LANTERN,false); - } - for(int row=0;rowf.setFacingDirection(face,true)); - frame.setVisible(false); frame.setFixed(true); frame.setInvulnerable(true); frame.setPersistent(true); - frame.getPersistentDataContainer().set(key,PersistentDataType.STRING,tag); - ItemStack item=new ItemStack(Material.FILLED_MAP); MapMeta meta=(MapMeta)item.getItemMeta(); meta.setMapView(views.get(row*p.width+col)); item.setItemMeta(meta); frame.setItem(item,false); - } - } -} diff --git a/DuneLobby/src/main/java/com/example/dunelobby/LobbyBuilder.java b/DuneLobby/src/main/java/com/example/dunelobby/LobbyBuilder.java deleted file mode 100644 index f3bb2670..00000000 --- a/DuneLobby/src/main/java/com/example/dunelobby/LobbyBuilder.java +++ /dev/null @@ -1,443 +0,0 @@ -package com.example.dunelobby; - -import org.bukkit.*; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Sign; -import org.bukkit.block.sign.Side; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.type.Slab; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.TextDisplay; -import org.bukkit.entity.Display; -import org.bukkit.inventory.ItemStack; -import java.util.*; - -/** Deterministic, bounded build. Coordinates are also used by the saved-world verifier. */ -final class LobbyBuilder { - static final int FLOOR = 80; - static final List PLANETS = List.of("arrakis", "caladan", "giedi_prime", "kaitain", "sigma_draconis_iv"); - static final int[][] PADS = {{-100,-73},{-78,-75},{-56,-73},{-101,-39},{-55,-39}}; - private final World w; - private long count; - LobbyBuilder(World world) { w = world; } - void block(int x,int y,int z,Material m) { w.getBlockAt(x,y,z).setType(m,false); count++; } - void box(int x1,int y1,int z1,int x2,int y2,int z2,Material m) { - for(int x=x1;x<=x2;x++) for(int z=z1;z<=z2;z++) for(int y=y1;y<=y2;y++) block(x,y,z,m); - } - private boolean inside(int x,int z,int rx,int rz) { - return Math.abs(x)<=rx && Math.abs(z)<=rz && Math.abs(x)+Math.abs(z)<=rx+rz-5; - } - /** Heavy carved room walls; the entire lobby shares a flat opaque ceiling. */ - private void room(int cx,int cz,int rx,int rz,int height,boolean shady) { - for(int x=-rx;x<=rx;x++) for(int z=-rz;z<=rz;z++) { - if(!inside(x,z,rx,rz)) continue; - boolean edge = !inside(x+1,z,rx,rz)||!inside(x-1,z,rx,rz)||!inside(x,z+1,rx,rz)||!inside(x,z-1,rx,rz); - block(cx+x,76,cz+z,Material.DEEPSLATE_TILES); - block(cx+x,77,cz+z,Material.POLISHED_BLACKSTONE_BRICKS); - block(cx+x,78,cz+z,Material.POLISHED_BLACKSTONE_BRICKS); - block(cx+x,79,cz+z,Material.CHISELED_POLISHED_BLACKSTONE); - Material floor = Math.floorMod(Math.floorDiv(x,4)+Math.floorDiv(z,4),2)==0?Material.DEEPSLATE_TILES:Material.POLISHED_BLACKSTONE_BRICKS; - if(Math.abs(x)==rx-3 || Math.abs(z)==rz-3) floor=shady?Material.WAXED_WEATHERED_COPPER:Material.GILDED_BLACKSTONE; - if(Math.abs(x)==rx-5 || Math.abs(z)==rz-5) floor=shady?Material.CRACKED_DEEPSLATE_BRICKS:Material.WAXED_CUT_COPPER; - block(cx+x,80,cz+z,floor); - int wallTop=FLOOR+height; - if(edge) { - for(int y=65;y<=wallTop;y++) { - Material m=Material.POLISHED_BLACKSTONE_BRICKS; - if(y>=85 && y=-12;z--) { - int y=80+(int)Math.ceil(-z/2.0); - box(-6,81,z,6,y,z,Material.POLISHED_BLACKSTONE_BRICKS); - for(int x:new int[]{-6,6}) block(x,y,z,Material.GOLD_BLOCK); - for(int x:new int[]{-8,8}) { block(x,y+1,z,Material.POLISHED_BLACKSTONE_BRICK_WALL); if(z%3==0) block(x,y+2,z,Material.LANTERN); } - } - box(-10,87,-27,10,89,-15,Material.WAXED_CUT_COPPER); - box(-9,90,-26,9,121,-14,Material.ORANGE_STAINED_GLASS); - box(-8,91,-25,8,120,-15,Material.AIR); - box(-10,122,-27,10,123,-14,Material.WAXED_CUT_COPPER); - box(-9,124,-26,9,124,-15,Material.CHISELED_POLISHED_BLACKSTONE); - for(int x:new int[]{-11,11}) { - box(x-1,87,-27,x+1,124,-14,Material.POLISHED_BLACKSTONE_BRICKS); - for(int y=89;y<=123;y+=4) { - box(x-1,y,-15,x+1,y,-13,Material.WAXED_OXIDIZED_COPPER); - block(x,y,-12,Material.GOLD_BLOCK); - } - for(int y=91;y<=119;y+=7) { block(x, y,-12,Material.LANTERN); } - } - for(int x=-8;x<=8;x+=4) for(int z:new int[]{-24,-16}) { block(x,90,z,Material.SHROOMLIGHT); block(x,121,z,Material.SHROOMLIGHT); } - // Oversized folded aquatic body, bulbous head, ribbed trunk and fanned hands. - ellipsoid(0,105,-21,4.0,8.3,3.0,Material.SMOOTH_SANDSTONE); - ellipsoid(0,115,-20,5.6,4.3,3.5,Material.CUT_SANDSTONE); - ellipsoid(0,112,-17,3.5,2.1,1.5,Material.SMOOTH_SANDSTONE); - ellipsoid(0,95,-22,5.7,2.7,2.6,Material.SANDSTONE); - block(-3,115,-17,Material.BROWN_TERRACOTTA); block(3,115,-17,Material.BROWN_TERRACOTTA); - block(0,111,-16,Material.BLACK_TERRACOTTA); - for(int s:new int[]{-1,1}) { - ellipsoid(s*4.6,104,-19,1.5,5.2,1.6,Material.CUT_SANDSTONE); - ellipsoid(s*5.4,99,-19,2.7,1.4,2.3,Material.SMOOTH_SANDSTONE); - for(int f=0;f<5;f++) { - int end=s*(4+f); - box(Math.min(s*3,end),100+f/2,-17-f/2,Math.max(s*3,end),100+f/2,-17-f/2,Material.SMOOTH_SANDSTONE); - } - } - for(int y=99;y<=111;y+=2) for(int s:new int[]{-1,1}) box(s<0?-4:2,y,-18,s<0?-2:4,y,-17,Material.SANDSTONE); - for(int x:new int[]{-14,14}) for(int z=-25;z<=-11;z+=5) lamp(x,87,z,false); - box(11,87,-12,15,88,-12,Material.WAXED_CUT_COPPER); - sign(13,88,-11,BlockFace.SOUTH,"VAERKRING","NAVIGATOR","Right-click liaison","for planet travel"); - for(int x=-18;x<=18;x++) for(int z=-5;z<=23;z++) { - double r=Math.hypot(x,z-10); - if((r>=11.5 && r<=12.5)||(r>=4.5&&r<=5.5)) block(x,80,z,Material.GOLD_BLOCK); - if(r>12.5 && r<13.5) block(x,80,z,Material.WAXED_CUT_COPPER); - } - galleries(); - } - private void galleries() { - for(int x=-24;x<=24;x++) for(int z=-26;z<=26;z++) { - if(!inside(x,z,24,26) || !(Math.abs(x)>=21 || z>=24)) continue; - block(x,90,z,Material.POLISHED_BLACKSTONE_BRICKS); - if(Math.abs(x)==21 || z==24) { block(x,91,z,Material.POLISHED_BLACKSTONE_BRICK_WALL); if(Math.floorMod(x+z,6)==0) block(x,92,z,Material.LANTERN); } - } - for(int s:new int[]{-1,1}) for(int i=0;i<10;i++) { - int z=18-i,y=81+i; - box(s<0?-24:22,81,z,s<0?-22:24,y,z,Material.POLISHED_BLACKSTONE_BRICKS); - block(s*21,y+1,z,Material.WAXED_CUT_COPPER); - } - for(int s:new int[]{-1,1}) for(int z:new int[]{-19,-7,5,23}) { - box(s<0?-24:22,81,z-1,s<0?-22:24,89,z+1,Material.DEEPSLATE_BRICKS); - for(int y:new int[]{84,89}) block(s*22,y,z,Material.GOLD_BLOCK); - block(s*20,85,z,Material.LANTERN); - } - } - private void bridge(int x1,int z1,int x2,int z2,boolean shady) { - int minX=Math.min(x1,x2)-4,maxX=Math.max(x1,x2)+4,minZ=Math.min(z1,z2)-4,maxZ=Math.max(z1,z2)+4; - double vx=x2-x1,vz=z2-z1,length2=vx*vx+vz*vz; - for(int x=minX;x<=maxX;x++) for(int z=minZ;z<=maxZ;z++) { - double t=Math.max(0,Math.min(1,((x-x1)*vx+(z-z1)*vz)/length2)); - double d=Math.hypot(x-x1-t*vx,z-z1-t*vz); - if(d>3.6) continue; - box(x,76,z,x,79,z,Material.POLISHED_BLACKSTONE_BRICKS); - block(x,80,z,d<.8?Material.GOLD_BLOCK:d>2.5?Material.WAXED_CUT_COPPER:Material.DEEPSLATE_TILES); - box(x,81,z,x,88,z,Material.AIR); - block(x,93,z,Material.POLISHED_BLACKSTONE_BRICKS); - if(d>2.5) box(x,89,z,x,92,z,Material.CHISELED_POLISHED_BLACKSTONE); - } - for(int x=minX;x<=maxX;x++) for(int z=minZ;z<=maxZ;z++) { - double t=Math.max(0,Math.min(1,((x-x1)*vx+(z-z1)*vz)/length2)); - double d=Math.hypot(x-x1-t*vx,z-z1-t*vz); - if(d<2.5 || d>3.6 || !w.getBlockAt(x,80,z).getType().isSolid()) continue; - boolean outer=false; - for(int[] v:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}) if(!w.getBlockAt(x+v[0],80,z+v[1]).getType().isSolid()) outer=true; - if(!outer) continue; - box(x,81,z,x,92,z,Material.POLISHED_BLACKSTONE_BRICKS); - block(x,84,z,Material.WAXED_CUT_COPPER); block(x,90,z,Material.WAXED_CUT_COPPER); - if(Math.floorMod(x+z,6)==0) { - block(x,88,z,Material.SHROOMLIGHT); - box(x,68,z,x,75,z,Material.DEEPSLATE_BRICKS); block(x,72,z,Material.WAXED_CUT_COPPER); - } - } - } - private void pad(int cx,int cz,int radius,int y,boolean launch,int number) { - box(cx-radius-1,80,cz-radius-1,cx+radius+1,y,cz+radius+1,Material.GRAY_CONCRETE); - for(int x=-radius;x<=radius;x++) for(int z=-radius;z<=radius;z++) { - Material m=Material.POLISHED_BASALT; - if(Math.abs(x)==radius || Math.abs(z)==radius) m=Math.floorMod(x+z,4)<2?Material.YELLOW_CONCRETE:Material.BLACK_CONCRETE; - if((Math.abs(x)<=1 && Math.abs(z)<=radius-2)||(Math.abs(z)<=1 && Math.abs(x)<=radius-2)) m=Material.SMOOTH_QUARTZ; - block(cx+x,y,cz+z,m); - } - for(int s:new int[]{-1,1}) for(int t:new int[]{-1,1}) { block(cx+s*radius,y+1,cz+t*radius,Material.LANTERN); } - if(launch) { - box(cx-2,81,cz+radius+1,cx+2,81,cz+radius+2,Material.SMOOTH_STONE); - box(cx-2,81,cz+radius+3,cx+2,81,cz+radius+3,Material.SMOOTH_STONE_SLAB); - box(cx-2,83,cz-radius-2,cx+2,84,cz-radius-2,Material.WAXED_CUT_COPPER); - block(cx,85,cz-radius-2,Material.LANTERN); - sign(cx,84,cz-radius-1,BlockFace.SOUTH,"DEPARTURE 0"+number,PLANETS.get(number-1).replace('_',' '),"Right-click console","Confirm destination"); - } - } - private void starport() { - pad(-78,-53,10,80,false,0); - for(int i=0;i