From eb2d7d77f57cc4c0998c8c35b6de734ed9919f59 Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Mon, 23 Nov 2026 17:09:08 +0000 Subject: [PATCH] Bring Base Minerals to Minecraft 1.14.4 --- .github/workflows/ci.yml | 14 +- .github/workflows/codeql-analysis.yml | 6 +- .github/workflows/deploy-release.yml | 43 +- .github/workflows/release-on-tag.yml | 6 +- .github/workflows/validate-gradle-build.yml | 6 +- .gitignore | 2 + CHANGELOG.txt | 10 + README.md | 23 +- build.gradle | 68 +++- docs/BUILDING.md | 109 ++++-- docs/KNOWN_ISSUES.md | 22 +- docs/MANUAL_TESTING.md | 27 ++ docs/PORTING_114.md | 50 +++ docs/RELEASING.md | 17 +- docs/WORLD_UPGRADES.md | 23 +- gradle.properties | 9 +- gradle/compatibility-114.gradle | 99 +++++ gradle/dependencies.json | 17 +- gradle/local-companions-114.gradle | 63 +++ ...{release-113.gradle => release-114.gradle} | 39 +- .../moddev/mc/baseminerals/BaseMinerals.java | 8 +- .../client/MineralFluidRenderer.java | 52 +-- .../baseminerals/content/MineralContent.java | 56 ++- .../content/MoltenMineralBlock.java | 23 ++ .../content/MoltenMineralFluid.java | 39 +- .../baseminerals/loot/MineralPowderCount.java | 30 ++ .../migration/LegacyWorldUpgrade.java | 91 +++-- .../recipe/SharedCrushingSerializer.java | 21 +- .../mc/baseminerals/trade/MineralTrades.java | 32 +- src/main/resources/META-INF/mods.toml | 15 +- .../models/block/lithium_molten.json | 2 +- .../models/block/silicon_molten.json | 2 +- .../baseminerals/models/item/lithium.json | 2 +- .../models/item/lithium_bucket.json | 6 +- .../baseminerals/models/item/silicon.json | 2 +- .../models/item/silicon_bucket.json | 6 +- .../{blocks => block}/molten_metal_flow.png | Bin .../molten_metal_flow.png.mcmeta | 0 .../{blocks => block}/molten_metal_still.png | Bin .../molten_metal_still.png.mcmeta | 0 .../textures/items/bucket_fluid.png | Bin 0 -> 163 bytes .../textures/items/bucket_overlay.png | Bin 0 -> 214 bytes .../baseminerals_legacy_world_upgrade.js | 148 +++---- .../tags/blocks/crackhammer_crushable.json | 4 + .../loot_tables/blocks/lithium.json | 4 + .../loot_tables/blocks/lithium_block.json | 9 +- .../loot_tables/blocks/lithium_ore.json | 9 +- .../loot_tables/blocks/niter_block.json | 9 +- .../loot_tables/blocks/niter_ore.json | 38 +- .../loot_tables/blocks/phosphorus_block.json | 9 +- .../loot_tables/blocks/phosphorus_ore.json | 38 +- .../loot_tables/blocks/potash_block.json | 9 +- .../loot_tables/blocks/potash_ore.json | 38 +- .../loot_tables/blocks/salt_block.json | 9 +- .../loot_tables/blocks/salt_ore.json | 38 +- .../loot_tables/blocks/saltpeter_block.json | 9 +- .../loot_tables/blocks/saltpeter_ore.json | 38 +- .../loot_tables/blocks/silicon.json | 4 + .../loot_tables/blocks/silicon_block.json | 9 +- .../loot_tables/blocks/sulfur_block.json | 9 +- .../loot_tables/blocks/sulfur_ore.json | 38 +- .../recipes/lithium_ore_blasting.json | 9 + .../recipes/lithium_powder_blasting.json | 9 + .../recipes/lithium_smallpowder_blasting.json | 9 + .../recipes/silicon_blend_blasting.json | 9 + .../recipes/silicon_powder_blasting.json | 9 + .../recipes/silicon_smallblend_blasting.json | 9 + .../recipes/silicon_smallpowder_blasting.json | 9 + .../tags/blocks/crackhammer_crushable.json | 20 + .../data/forge/tags/blocks/ores.json | 12 + .../forge/tags/blocks/storage_blocks.json | 13 + .../tags/blocks/storage_blocks/lithium.json | 6 + .../tags/blocks/storage_blocks/niter.json | 6 + .../blocks/storage_blocks/phosphorus.json | 6 + .../tags/blocks/storage_blocks/potash.json | 6 + .../tags/blocks/storage_blocks/salt.json | 6 + .../tags/blocks/storage_blocks/saltpeter.json | 6 + .../tags/blocks/storage_blocks/silicon.json | 6 + .../tags/blocks/storage_blocks/sulfur.json | 6 + .../resources/data/forge/tags/items/ores.json | 12 + .../data/forge/tags/items/storage_blocks.json | 13 + .../tags/blocks/crackhammer_crushable.json | 4 + .../migration/LegacyWorldUpgradeTest.java | 46 +-- tools/test_114_resources.js | 57 +++ .../port114/ParseEclipseArguments.java | 27 ++ .../java/test/MineralClientProbe.java | 250 ++++++++++++ .../client-probe/resources/META-INF/mods.toml | 13 + .../client-probe/resources/pack.mcmeta | 1 + .../java/test/MineralGenerationProbe.java | 115 ++++++ .../resources/META-INF/mods.toml | 13 + .../generation-probe/resources/pack.mcmeta | 1 + .../java/test/MineralMiningProbe.java | 370 ++++++++++++++++++ .../mining-probe/resources/META-INF/mods.toml | 12 + .../mining-probe/resources/pack.mcmeta | 1 + tools/validation/port114/requirements.txt | 1 + tools/validation/port114/run_forge.py | 125 ++++++ tools/validation/port114/verify_census.py | 74 ++++ tools/validation/port114/verify_client.py | 67 ++++ tools/validation/port114/verify_generation.py | 41 ++ tools/validation/port114/verify_mining.py | 39 ++ .../port114/verify_named_upgrade.py | 37 ++ tools/validation/port114/verify_upgrade.py | 275 +++++++++++++ 102 files changed, 2803 insertions(+), 456 deletions(-) create mode 100644 docs/MANUAL_TESTING.md create mode 100644 docs/PORTING_114.md create mode 100644 gradle/compatibility-114.gradle create mode 100644 gradle/local-companions-114.gradle rename gradle/{release-113.gradle => release-114.gradle} (85%) create mode 100644 src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java create mode 100644 src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java rename src/main/resources/assets/baseminerals/textures/{blocks => block}/molten_metal_flow.png (100%) rename src/main/resources/assets/baseminerals/textures/{blocks => block}/molten_metal_flow.png.mcmeta (100%) mode change 100755 => 100644 rename src/main/resources/assets/baseminerals/textures/{blocks => block}/molten_metal_still.png (100%) rename src/main/resources/assets/baseminerals/textures/{blocks => block}/molten_metal_still.png.mcmeta (100%) mode change 100755 => 100644 create mode 100644 src/main/resources/assets/baseminerals/textures/items/bucket_fluid.png create mode 100644 src/main/resources/assets/baseminerals/textures/items/bucket_overlay.png create mode 100644 src/main/resources/data/basemetals/tags/blocks/crackhammer_crushable.json create mode 100644 src/main/resources/data/baseminerals/loot_tables/blocks/lithium.json create mode 100644 src/main/resources/data/baseminerals/loot_tables/blocks/silicon.json create mode 100644 src/main/resources/data/baseminerals/recipes/lithium_ore_blasting.json create mode 100644 src/main/resources/data/baseminerals/recipes/lithium_powder_blasting.json create mode 100644 src/main/resources/data/baseminerals/recipes/lithium_smallpowder_blasting.json create mode 100644 src/main/resources/data/baseminerals/recipes/silicon_blend_blasting.json create mode 100644 src/main/resources/data/baseminerals/recipes/silicon_powder_blasting.json create mode 100644 src/main/resources/data/baseminerals/recipes/silicon_smallblend_blasting.json create mode 100644 src/main/resources/data/baseminerals/recipes/silicon_smallpowder_blasting.json create mode 100644 src/main/resources/data/baseminerals/tags/blocks/crackhammer_crushable.json create mode 100644 src/main/resources/data/forge/tags/blocks/ores.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/lithium.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/niter.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/phosphorus.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/potash.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/salt.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/saltpeter.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/silicon.json create mode 100644 src/main/resources/data/forge/tags/blocks/storage_blocks/sulfur.json create mode 100644 src/main/resources/data/forge/tags/items/ores.json create mode 100644 src/main/resources/data/forge/tags/items/storage_blocks.json create mode 100644 src/main/resources/data/modernmetals/tags/blocks/crackhammer_crushable.json create mode 100644 tools/test_114_resources.js create mode 100644 tools/validation/port114/ParseEclipseArguments.java create mode 100644 tools/validation/port114/client-probe/java/test/MineralClientProbe.java create mode 100644 tools/validation/port114/client-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port114/client-probe/resources/pack.mcmeta create mode 100644 tools/validation/port114/generation-probe/java/test/MineralGenerationProbe.java create mode 100644 tools/validation/port114/generation-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port114/generation-probe/resources/pack.mcmeta create mode 100644 tools/validation/port114/mining-probe/java/test/MineralMiningProbe.java create mode 100644 tools/validation/port114/mining-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port114/mining-probe/resources/pack.mcmeta create mode 100644 tools/validation/port114/requirements.txt create mode 100644 tools/validation/port114/run_forge.py create mode 100644 tools/validation/port114/verify_census.py create mode 100644 tools/validation/port114/verify_client.py create mode 100644 tools/validation/port114/verify_generation.py create mode 100644 tools/validation/port114/verify_mining.py create mode 100644 tools/validation/port114/verify_named_upgrade.py create mode 100644 tools/validation/port114/verify_upgrade.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc85d08..9ce513f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,16 +1,16 @@ -name: Base Minerals 1.13.2 CI +name: Base Minerals 1.14.4 CI on: push: - branches: [master-1.13.2, 'feature/**'] + branches: [master-1.14.4, 'feature/**'] pull_request: - branches: [master-1.13.2] + branches: [master-1.14.4] permissions: contents: read concurrency: - group: baseminerals-113-${{ github.workflow }}-${{ github.ref }} + group: baseminerals-114-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: @@ -44,7 +44,7 @@ jobs: run: python3 gradle/stage-legacy-dependencies.py .gradle/legacy-dependencies - name: Build, audit and generate Eclipse launches run: | - bash ./gradlew clean check build javadoc verify113ReleaseArtifacts write113ReleaseChecksums genEclipseRuns eclipse \ + bash ./gradlew clean check build javadoc verify114ReleaseArtifacts write114ReleaseChecksums genEclipseRuns eclipse \ -PreleaseBuild=true -PlegacyDependencyVerificationRepository="$PWD/.gradle/legacy-dependencies" \ --no-daemon --stacktrace --max-workers=2 \ "-Dorg.gradle.java.installations.paths=$JAVA_HOME,$JAVA_HOME_8_X64,$JAVA_HOME_25_X64" \ @@ -57,7 +57,7 @@ jobs: - name: Upload audited release candidate uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: - name: BaseMinerals-1.13.2-${{ github.sha }} + name: BaseMinerals-1.14.4-${{ github.sha }} if-no-files-found: error retention-days: 30 path: build/release-bundle/ @@ -65,7 +65,7 @@ jobs: if: failure() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: - name: BaseMinerals-1.13.2-diagnostics-${{ github.sha }} + name: BaseMinerals-1.14.4-diagnostics-${{ github.sha }} if-no-files-found: ignore retention-days: 14 path: | diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index cceb756..e91eb28 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -3,11 +3,11 @@ name: CodeQL on: push: branches: - - master-1.13.2 - - feature/baseminerals-1.13.2 + - master-1.14.4 + - feature/baseminerals-1.14.4 pull_request: branches: - - master-1.13.2 + - master-1.14.4 schedule: - cron: '47 7 * * 4' diff --git a/.github/workflows/deploy-release.yml b/.github/workflows/deploy-release.yml index 1dd2676..51dd0c8 100644 --- a/.github/workflows/deploy-release.yml +++ b/.github/workflows/deploy-release.yml @@ -1,15 +1,15 @@ -name: Release Base Minerals 1.13.2 +name: Release Base Minerals 1.14.4 run-name: Base Minerals ${{ inputs.release_version }} (${{ inputs.confirm_live_publication && 'publish' || 'verify' }}) on: workflow_dispatch: inputs: release_version: - description: Four-part version for Minecraft 1.13.2 + description: Four-part version for Minecraft 1.14.4 required: true type: string release_commit: - description: Full SHA of the checked MMD master-1.13.2 commit + description: Full SHA of the checked MMD master-1.14.4 commit required: true type: string tested_jar_sha256: @@ -33,13 +33,13 @@ permissions: contents: read concurrency: - group: baseminerals-release-113 + group: baseminerals-release-114 cancel-in-progress: false jobs: qualify: name: Verify merged CI candidate - if: github.repository == 'MinecraftModDevelopmentMods/BaseMinerals' && github.ref == 'refs/heads/master-1.13.2' + if: github.repository == 'MinecraftModDevelopmentMods/BaseMinerals' && github.ref == 'refs/heads/master-1.14.4' runs-on: ubuntu-latest timeout-minutes: 10 permissions: @@ -61,21 +61,21 @@ jobs: TESTED_SHA: ${{ inputs.tested_jar_sha256 }} run: | set -euo pipefail - [[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.113021$ ]] + [[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.114041$ ]] [[ "$RELEASE_SHA" =~ ^[[:xdigit:]]{40}$ ]] [[ "$TESTED_SHA" =~ ^[[:xdigit:]]{64}$ ]] test "$(git rev-parse HEAD)" = "$RELEASE_SHA" - test "$(gh api "repos/$GITHUB_REPOSITORY/branches/master-1.13.2" --jq .commit.sha)" = "$RELEASE_SHA" + test "$(gh api "repos/$GITHUB_REPOSITORY/branches/master-1.14.4" --jq .commit.sha)" = "$RELEASE_SHA" grep -Fxq "mod_version=$RELEASE_VERSION" gradle.properties - grep -Fxq 'minecraft_version=1.13.2' gradle.properties + grep -Fxq 'minecraft_version=1.14.4' gradle.properties ci_run="$(gh api --method GET "repos/$GITHUB_REPOSITORY/actions/workflows/ci.yml/runs" \ - -f branch=master-1.13.2 -f head_sha="$RELEASE_SHA" -f event=push -f status=success \ + -f branch=master-1.14.4 -f head_sha="$RELEASE_SHA" -f event=push -f status=success \ --jq '.workflow_runs[0].id // empty')" test -n "$ci_run" echo "ci_run=$ci_run" >> "$GITHUB_OUTPUT" - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: - name: BaseMinerals-1.13.2-${{ inputs.release_commit }} + name: BaseMinerals-1.14.4-${{ inputs.release_commit }} run-id: ${{ steps.candidate.outputs.ci_run }} github-token: ${{ github.token }} path: ${{ runner.temp }}/release-input @@ -152,7 +152,7 @@ jobs: - uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6 - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: - name: BaseMinerals-1.13.2-${{ inputs.release_commit }} + name: BaseMinerals-1.14.4-${{ inputs.release_commit }} run-id: ${{ needs.qualify.outputs.ci_run }} github-token: ${{ github.token }} path: ${{ runner.temp }}/release-input @@ -179,7 +179,7 @@ jobs: steps: - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: - name: BaseMinerals-1.13.2-${{ inputs.release_commit }} + name: BaseMinerals-1.14.4-${{ inputs.release_commit }} run-id: ${{ needs.qualify.outputs.ci_run }} github-token: ${{ github.token }} path: ${{ runner.temp }}/release-input @@ -187,16 +187,17 @@ jobs: working-directory: ${{ runner.temp }}/release-input run: sha256sum --check --strict SHA256SUMS - name: Publish Base Minerals + id: curseforge uses: Kira-NT/mc-publish@52307b03863581dec6b652b83e597aec02ebb075 # v3.3.1 with: curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} curseforge-id: '270972' - name: Base Minerals ${{ inputs.release_version }} for Minecraft 1.13.2 (Forge) + name: Base Minerals ${{ inputs.release_version }} for Minecraft 1.14.4 (Forge) version: ${{ inputs.release_version }} version-type: ${{ inputs.curseforge_release_level }} changelog-file: ${{ runner.temp }}/release-input/CHANGELOG.txt loaders: forge - game-versions: '1.13.2' + game-versions: '1.14.4' game-version-filter: none environment: client | server java: Java 8 @@ -210,6 +211,16 @@ jobs: ${{ runner.temp }}/release-input/BaseMinerals-${{ inputs.release_version }}-sources.jar ${{ runner.temp }}/release-input/BaseMinerals-${{ inputs.release_version }}-javadoc.jar + - name: Record the accepted CurseForge files + env: + CURSEFORGE_URL: ${{ steps.curseforge.outputs.curseforge-url }} + CURSEFORGE_FILES: ${{ steps.curseforge.outputs.curseforge-files }} + run: | + python3 - <<'PY' + import json, os + print(json.dumps({'url': os.environ['CURSEFORGE_URL'], 'files': os.environ['CURSEFORGE_FILES']})) + PY + publish_github: name: Publish GitHub Release needs: [qualify, publish_curseforge] @@ -222,7 +233,7 @@ jobs: steps: - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: - name: BaseMinerals-1.13.2-${{ inputs.release_commit }} + name: BaseMinerals-1.14.4-${{ inputs.release_commit }} run-id: ${{ needs.qualify.outputs.ci_run }} github-token: ${{ github.token }} path: ${{ runner.temp }}/release-input @@ -235,5 +246,5 @@ jobs: set -euo pipefail sha256sum --check --strict SHA256SUMS gh release create "$RELEASE_VERSION" --repo "$GITHUB_REPOSITORY" --verify-tag \ - --title "Base Minerals $RELEASE_VERSION for Minecraft 1.13.2 (Forge)" \ + --title "Base Minerals $RELEASE_VERSION for Minecraft 1.14.4 (Forge)" \ --notes-file CHANGELOG.txt "BaseMinerals-$RELEASE_VERSION"{,-sources,-javadoc}.jar SHA256SUMS diff --git a/.github/workflows/release-on-tag.yml b/.github/workflows/release-on-tag.yml index 9085d64..a935640 100644 --- a/.github/workflows/release-on-tag.yml +++ b/.github/workflows/release-on-tag.yml @@ -1,7 +1,7 @@ -name: Validate Base Minerals 1.13.2 tag +name: Validate Base Minerals 1.14.4 tag on: push: - tags: ['*.*.*.113021'] + tags: ['*.*.*.114041'] permissions: contents: read actions: read @@ -16,5 +16,5 @@ jobs: run: | set -euo pipefail test "$GITHUB_REF_NAME" = "$(sed -n 's/^mod_version=//p' gradle.properties)" - grep -Fxq 'minecraft_version=1.13.2' gradle.properties + grep -Fxq 'minecraft_version=1.14.4' gradle.properties echo 'Tag validated. Publication uses deploy-release.yml with explicit confirmation.' >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/validate-gradle-build.yml b/.github/workflows/validate-gradle-build.yml index 81225e5..cf7fcd4 100644 --- a/.github/workflows/validate-gradle-build.yml +++ b/.github/workflows/validate-gradle-build.yml @@ -3,11 +3,11 @@ name: Validate Gradle Wrapper on: push: branches: - - master-1.13.2 - - feature/baseminerals-1.13.2 + - master-1.14.4 + - feature/baseminerals-1.14.4 pull_request: branches: - - master-1.13.2 + - master-1.14.4 permissions: contents: read diff --git a/.gitignore b/.gitignore index 3a14b22..3e153ec 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,8 @@ run /forge-*-changelog.txt secret.json +/local-basemetals.json +/local-modernmetals.json # Local context and generated verification /AGENTS.md /agent-notes/ diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 5095bf7..e717c0a 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,13 @@ +2.5.2.114041 for Minecraft 1.14.4 + +This brings the released 1.13.2 build across to Forge 28, using OreSpawn 4.1.7.114041. The mineral IDs, ore depths and deposit shapes stay the same, and saved ore settings carry forward. + +The ores keep their earlier drops, Fortune and Silk Touch behaviour, and work with Base Metals or Modern Metals crackhammers. Lithium and silicon can also be smelted in a blast furnace. Molten fluids use Forge's native renderer, and the ingot trades use the new villager professions. + +The minerals now join both hammer mining tags, so breaking an ore uses the hammer's proper speed. Local test launches pin the fixed Base Metals and Modern Metals jars by hash, including the ore overlay fix. + +The old numeric-world conversion is adapted for 1.14.4. Keep the full save and its baseminerals-legacy-registry.dat file together, and test an upgrade on a copy. The older material settings screens and Tinkers integration are still unavailable. + 2.5.2.113021 for Minecraft 1.13.2 This fixes the ore drops to match 1.10 to 1.12. Lithium drops one ore block; the other six ores drop 2–4 powders. Fortune increases the maximum, and Silk Touch returns the ore block. diff --git a/README.md b/README.md index 2cce877..0f99699 100644 --- a/README.md +++ b/README.md @@ -4,26 +4,32 @@ Base Minerals adds lithium, niter, phosphorus, potash, salt, saltpeter, sulfur and silicon. The seven ores use KiriCattus's overlays. OreSpawn handles placement, including the saved rules and shared ore sources. -This branch targets Minecraft 1.13.2 and Forge 25.0.223. Install -[OreSpawn 4.1.7.113021](https://www.curseforge.com/minecraft/mc-mods/mmd-orespawn/files/9611746). -[Base Metals 3.0.3.113021](https://github.com/MinecraftModDevelopmentMods/BaseMetals/releases/tag/3.0.3.113021) +This branch targets Minecraft 1.14.4 and Forge 28.2.26. Install +[OreSpawn 4.1.7.114041](https://github.com/MinecraftModDevelopmentMods/OreSpawn/releases/tag/4.1.7.114041). +[Base Metals 3.0.2.114041](https://github.com/MinecraftModDevelopmentMods/BaseMetals/releases/tag/3.0.2.114041) is optional in new worlds and supplies the Crack Hammer. Keep Base Metals installed when upgrading a world that already contains its blocks or items. -Use 3.0.3.113021 or a later compatible 1.13.2 build when installing the two together. +Use 3.0.2.114041 or a later compatible 1.14.4 build when installing the two together. Base Minerals shares its ore crushing recipes with Base Metals when installed. -If Base Metals is absent, Modern Metals crackhammers can crush the ores instead. +If Base Metals is absent, +[Modern Metals 3.0.0.114041](https://github.com/MinecraftModDevelopmentMods/ModernMetals/releases/tag/3.0.0.114041) +crackhammers can crush the ores instead. Both metal mods remain optional. Mining lithium returns one ore block. Niter, phosphorus, potash, salt, saltpeter and sulfur drop 2–4 powders, with Fortune increasing the upper limit by its level. Silk Touch returns one ore block. A Crack Hammer gives two powders per ore, as on the earlier branches. +Lithium and silicon smelting also works in the blast furnace, with the same +outputs and experience at half the cooking time. The old smith ingot trades +are available from level-two armorers, toolsmiths and weaponsmiths. + ## Upgrading a world -Copy the whole save folder before opening it on 1.13.2, including level.dat +Copy the whole save folder before opening it on 1.14.4, including level.dat and serverconfig. Start the copy with Forge, Base Minerals, OreSpawn and the -1.13.2 versions of any other mods whose content it uses. Check existing blocks +1.14.4 versions of any other mods whose content it uses. Check existing blocks and inventories, save, then reopen the copy. Base Minerals reads the old Forge registry from the world and saves the @@ -33,4 +39,5 @@ Placed molten lithium and silicon keep their fluid level. The old Forge filled buckets become the matching named buckets. See [building](docs/BUILDING.md), [ore generation](docs/ORE_GENERATION.md), -[upgrade checks](docs/WORLD_UPGRADES.md) and [known limits](docs/KNOWN_ISSUES.md). +[upgrade checks](docs/WORLD_UPGRADES.md), [port decisions](docs/PORTING_114.md) +and [known limits](docs/KNOWN_ISSUES.md). diff --git a/build.gradle b/build.gradle index 5816a65..6c965c2 100644 --- a/build.gradle +++ b/build.gradle @@ -40,7 +40,7 @@ def stageRunClasses = tasks.register('stageRunClasses', Sync) { } minecraft { - mappings channel: 'snapshot', version: '20180921-1.13' + mappings channel: 'snapshot', version: '20190719-1.14.3' if (gradle.startParameter.offline) mavenizerArguments.add('--offline') runs { configureEach { @@ -48,11 +48,11 @@ minecraft { workingDir.convention layout.projectDirectory.dir( providers.gradleProperty('baseMineralsRunDirectory').getOrElse('run')) mods { baseminerals { source sourceSets.main } } - environment 'target', name == 'client' ? 'fmluserdevclient' : 'fmluserdevserver' - environment 'MC_VERSION', '1.13.2' - environment 'MCP_VERSION', '20190213.203750' - environment 'MCP_MAPPINGS', 'snapshot_20180921-1.13' - environment 'FORGE_VERSION', '25.0.223' + environment 'target', name.toLowerCase().contains('client') ? 'fmluserdevclient' : 'fmluserdevserver' + environment 'MC_VERSION', '1.14.4' + environment 'MCP_VERSION', '20190829.143755' + environment 'MCP_MAPPINGS', 'snapshot_20190719-1.14.3' + environment 'FORGE_VERSION', '28.2.26' environment 'FORGE_GROUP', 'net.minecraftforge' def path = modClasses.get().asFile.absolutePath environment 'MOD_CLASSES', "baseminerals%%${path}${File.pathSeparator}baseminerals%%${path}" @@ -80,12 +80,12 @@ repositories { exclusiveContent { forRepository { maven { - name = 'PublishedBaseMetals' + name = 'PublishedOreSpawn' url = mirror.isDirectory() ? mirror.toURI() : uri('https://maven.moddev.zone/releases') metadataSources { artifact() } } } - filter { includeModule('zone.moddev.mc.basemetals', 'BaseMetals') } + filter { includeModule('zone.moddev.mc.orespawn', 'OreSpawn'); includeModule('zone.moddev.mc.modernmetals', 'ModernMetals'); includeModule('zone.moddev.mc.basemetals', 'BaseMetals') } } mavenCentral() } @@ -95,7 +95,7 @@ configurations { pinnedMods { canBeConsumed = false; transitive = false } } dependencies { - implementation minecraft.dependency('net.minecraftforge:forge:1.13.2-25.0.223') + implementation minecraft.dependency('net.minecraftforge:forge:1.14.4-28.2.26') specs.each { spec -> pinnedMods spec.coordinate if (spec.runtime) implementation renamer.dependency(spec.coordinate) @@ -142,9 +142,19 @@ tasks.named('compileJava') { dependsOn 'verifyPinnedMods' } tasks.named('test') { useJUnitPlatform() } sourceSets { + generationProbe { + java.srcDirs = ['tools/validation/port114/generation-probe/java'] + resources.srcDirs = ['tools/validation/port114/generation-probe/resources'] + compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath + } + clientProbe { + java.srcDirs = ['tools/validation/port114/client-probe/java'] + resources.srcDirs = ['tools/validation/port114/client-probe/resources'] + compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath + } miningProbe { - java.srcDirs = ['tools/validation/legacy113/mining-probe/java'] - resources.srcDirs = ['tools/validation/legacy113/mining-probe/resources'] + java.srcDirs = ['tools/validation/port114/mining-probe/java'] + resources.srcDirs = ['tools/validation/port114/mining-probe/resources'] compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath } } @@ -160,15 +170,39 @@ def packagedMiningProbe = renamer.classes(miningProbeJar) { output = layout.buildDirectory.file('test-mods/mineral-mining-probe.jar') } tasks.register('packagedMiningProbeJar') { dependsOn packagedMiningProbe } + +def generationProbeJar = tasks.register('generationProbeJar', Jar) { + dependsOn tasks.named('generationProbeClasses') + from sourceSets.generationProbe.output + destinationDirectory = layout.buildDirectory.dir('test-mods') + archiveFileName = 'mineral-generation-probe-dev.jar' +} +def packagedGenerationProbe = renamer.classes(generationProbeJar) { + map.from minecraft.dependency.toSrgFile + archiveClassifier = null + output = layout.buildDirectory.file('test-mods/mineral-generation-probe.jar') +} +tasks.register('packagedGenerationProbeJar') { dependsOn packagedGenerationProbe } +tasks.register('clientProbeJar', Jar) { + dependsOn tasks.named('clientProbeClasses') + from sourceSets.clientProbe.output + destinationDirectory = layout.buildDirectory.dir('test-mods') + archiveFileName = 'mineral-client-probe-dev.jar' +} // Keep the executable test mod out of Eclipse's normal game launches. eclipse.classpath.sourceSets = [sourceSets.main, sourceSets.test] -tasks.register('verifyFluidRegistration', Exec) { +tasks.register('verifyStartupRegistration', Exec) { group = 'verification' description = 'Checks that fluid registration runs before blocks, outside parallel construction.' commandLine 'node', '--test', 'tools/test_fluid_registration.js' } -tasks.named('check') { dependsOn 'verifyFluidRegistration' } +tasks.named('check') { dependsOn 'verifyStartupRegistration' } +tasks.register('verify114Resources', Exec) { + group = 'verification' + commandLine 'node', '--test', 'tools/test_114_resources.js' +} +tasks.named('check') { dependsOn 'verify114Resources' } ['client', 'server'].each { run -> tasks.matching { it.name == 'run' + run.capitalize() }.configureEach { dependsOn stageRunClasses @@ -187,6 +221,10 @@ tasks.matching { it.name.startsWith('genEclipseRun') && it.name.endsWith('ForFor File launch = layout.projectDirectory.file(launchName).asFile doLast { Node configuration = new XmlParser().parse(launch) + if (launchName in ['runClient.launch', 'runServer.launch']) { + new Node(configuration, 'booleanAttribute', + [key: 'org.eclipse.jdt.launching.ATTR_EXCLUDE_TEST_CODE', value: 'true']) + } Node programArguments = configuration.stringAttribute.find { it.attribute('key') == 'org.eclipse.jdt.launching.PROGRAM_ARGUMENTS' } @@ -231,6 +269,8 @@ tasks.named('processResources', ProcessResources) { apply from: 'gradle/ore-models.gradle' -apply from: 'gradle/release-113.gradle' +apply from: 'gradle/release-114.gradle' apply from: 'gradle/normalize-javadoc-trees.gradle' + +apply from: 'gradle/compatibility-114.gradle' diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 9c520c2..2a2c9b8 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -1,35 +1,88 @@ -# Building Base Minerals 1.13.2 +# Building Base Minerals 1.14.4 -Use Java 17 for Gradle, Java 25 for Forge's Mavenizer, and Java 8 for compilation -and Minecraft. The wrapper is Gradle 9.6.1 with ForgeGradle 7.0.34, Renamer 1.1.5, -Forge 25.0.223 and MCP snapshot 20180921-1.13. +Use Java 17 for Gradle, Java 25 for Mavenizer, and Java 8 for compilation and +Minecraft. The wrapper uses Gradle 9.6.1, ForgeGradle 7.0.34 and Renamer 1.1.5. +The target is Forge 28.2.26 with MCP snapshot 20190719-1.14.3 and MCP config +20190829.143755. Select one Gradle cache for Eclipse and the terminal. Stage the checksum-pinned -public OreSpawn and Base Metals jars, then build with Java 17 as JAVA_HOME. -Base Metals is pinned to the published MMD Maven release 3.0.3.113021 and -checked by SHA-256. It remains optional when playing. +public OreSpawn 4.1.7.114041, Base Metals 3.0.2.114041 and Modern Metals +3.0.0.114041 jars, then build with Java 17 as JAVA_HOME. Both metal mods remain +optional when playing. - python gradle/stage-legacy-dependencies.py - .\gradlew.bat check build genEclipseRuns eclipse "-PlegacyDependencyVerificationRepository=" +```powershell +python gradle/stage-legacy-dependencies.py .gradle/legacy-dependencies +.\gradlew.bat check build javadoc verify114ReleaseArtifacts genEclipseRuns eclipse +``` -On a configured machine, add --offline to rebuild from the same cache. -The reobfuscated player jar is build/libs/BaseMinerals-2.5.2.113021.jar. -Development output lives under build/libs-dev. Sources and Javadocs are separate. +Set org.gradle.java.installations.paths to the three JDK directories when +toolchain discovery is disabled. In this workspace GRADLE_USER_HOME is +D:/BaseMetals/.gradle-verify-cache. Add --offline to rebuild from the same cache. +The player jar is build/libs/BaseMinerals-2.5.2.114041.jar. Development output +is under build/libs-dev; sources and Javadocs are separate. Import the inner checkout as an Eclipse Gradle project. The generated client -and server launch files use the Java 8 game toolchain and staged mod output. -Gradle refresh regenerates them with quoted paths for checkouts containing spaces. -For a terminal launch, use runClient or runServer. Use the published Base Metals -jar with the packaged Forge profile when checking Crack Hammer integration. - -The test runners in tools/validation/legacy113 use an independently installed -Forge server template. Install requirements.txt from that directory for the -Anvil and NBT checks. - -Build the separate survival-mining test mod with packagedMiningProbeJar, then -run verify_mining.py --help for the packaged-server options. Add --processing -to check furnace and crushing recipes as well. Run with Base Minerals alone, -with Base Metals, with Modern Metals, and with both hammer mods. The probe -checks normal drops, Fortune, Silk Touch, weak tools, hammer drops, block -properties, fluid light and smith offers. Its jar stays under build/test-mods -and must not be installed in a normal game. +and server launches use Java 8 and staged main output. Gradle refresh preserves +quoted paths for directories containing spaces. Use runClient.launch alone, +runClientWithBaseMetals.launch, runClientWithModernMetals.launch or +runClientWithBoth.launch. The four profiles use separate run directories and +the pinned public metal jars by default. Terminal runClient accepts +-PwithBaseMetals=true and -PwithModernMetals=true. + +To test the current local Base Metals and Modern Metals fixes, build those +sibling checkouts, then run these as separate commands: + +```powershell +.\gradlew.bat pinLocalCompanions +.\gradlew.bat check genEclipseRuns eclipse +``` + +The ignored local-basemetals.json and local-modernmetals.json files pin both +player and mapped jars by SHA-256. Gradle checks the source hashes and the exact +copies staged in each profile. Old managed companion copies are retained under +.gradle/retired-compatibility-jars; worlds, settings and unrelated mods are kept. +After rebuilding either sibling, repin it with pinLocalBaseMetals or +pinLocalModernMetals, then regenerate the launches. + +With the local pins present, runClientWithBaseMetals.launch and +runClientWithBoth.launch load the fixed local Base Metals build. The latter +also loads the pinned local Modern Metals build. runClientWithModernMetals.launch +uses Modern Metals alone. Terminal runClient accepts -PwithBaseMetals=true and +-PwithModernMetals=true. Use -PuseLocalBaseMetals=false to test the published +Base Metals baseline. Release builds (-PreleaseBuild=true) select published +dependencies and reject explicitly enabled local overrides. + +## Local gameplay checks + +The tools under tools/validation/port114 use an independently installed +Forge 1.14.4-28.2.26 server directory containing its launcher and libraries. +Install tools/validation/port114/requirements.txt for the Anvil/NBT checks. +Each runner creates a new disposable output directory and retains its logs. +Never use a player save or install a probe in a normal game. + +```powershell +.\gradlew.bat packagedMiningProbeJar packagedGenerationProbeJar clientProbeJar +python tools/validation/port114/verify_mining.py --help +python tools/validation/port114/verify_census.py --help +python tools/validation/port114/verify_upgrade.py --help +python tools/validation/port114/verify_named_upgrade.py --help +python tools/validation/port114/verify_client.py --help +``` + +The mining probe checks survival tools, Fortune, Silk Touch, shared hammers, +native cooking and crushing, block properties, fluid light and smith offers. +Use --processing and run it alone, with Base Metals, with Modern Metals and +with both. Hammer checks use the native start/tick/stop digging path and assert +mining speed as well as drops and durability. The client probe additionally +holds mining through the real client controller and network packets, checks +server/client block agreement and verifies Base Metals' fixed ore overlay gap. +The generation probe populates a margin around 256 interior chunks +in each vanilla dimension, scans Y=0..255, checks mineral heights and repeats +the census after later generation and reload. It handles actual seed zero +through an empty explicitly seeded save. The client probe checks models, +translations, ore layers, bucket tint and fluid atlas sprites, then saves and +reopens a disposable integrated world. It uses the actual Eclipse Windows +argument parser. Compile ParseEclipseArguments.java into a disposable helper +directory and include that directory and the installed Eclipse DebugPlugin +bundles in --parser-classpath; use the matching Java runtime as --parser-java. +None of these probes is included in the player jar. diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 1fcf2bf..7f5eca7 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -1,9 +1,25 @@ -# Known limits for Minecraft 1.13.2 +# Known limits for Minecraft 1.14.4 The 1.12 material and molten-form switches in BaseMinerals.cfg and their settings -screens have not been ported. The 1.13 registries keep the old content available +screens have not been ported. The registries keep the old content available for saved blocks and inventories. Use OreSpawn to change ore generation. -The 1.12 Tinkers' Construct integration does not carry over to Forge 25. +The 1.12 Tinkers' Construct integration does not carry over to Forge 28. + +Modern Metals 1.14 is currently tested using a frozen local candidate. Its +compatibility launch is available after staging that fixture; this does not +make Modern Metals a published or required dependency. + +The development profiles also pin the locally fixed Base Metals bars and ore +overlays. That jar has the same version as the published build but a different +hash. Publish those companion fixes and update the public pins before treating +the local combined profile as release-dependency qualification. + +OreSpawn 4.1.7.114041 writes empty dimensions or dimension_selectors objects +for some vanilla and companion-mod rules. Its published JSON schema rejects +those empty objects, although the engine loads and runs them. The Base Minerals +rules validate against that schema. This needs an OreSpawn serialization/schema +correction before claiming full saved-profile schema validation; the local +receipt retains the failures. OreSpawn 1 settings need to be imported on a supported older installation before moving the world. Carry the resulting saved profile with the world. diff --git a/docs/MANUAL_TESTING.md b/docs/MANUAL_TESTING.md new file mode 100644 index 0000000..9ac064e --- /dev/null +++ b/docs/MANUAL_TESTING.md @@ -0,0 +1,27 @@ +# Manual testing on 1.14.4 + +Refresh the inner BaseMinerals Gradle project in Eclipse. Start with +runClientWithBoth.launch to load the pinned local Base Metals and Modern Metals +fixes. Run pinLocalCompanions and regenerate launches after rebuilding those +siblings. runClient.launch is standalone; +runClientWithBaseMetals.launch and runClientWithModernMetals.launch test the +two companions separately. Each profile has its own run directory. + +Use a disposable world for these checks: + +1. Look at all seven ores in terrain and in the inventory. Check their stone + layer, transparent overlays and names. Mine them with ordinary picks, + Fortune, Silk Touch and the installed Crack Hammers. +2. Check lithium and silicon smelting in a furnace and blast furnace, storage + crafting and crushing, and the two molten buckets. Place and collect each + fluid, check its appearance and light, then save and reopen the world. +3. Open a copy of an older save with the matching companion mods installed. + Check familiar mineral deposits, stored items, placed molten blocks and + buckets. Save and reopen the copy. Keep its saved OreSpawn profile and + baseminerals-legacy-registry.dat together. See WORLD_UPGRADES.md for the + expected Forge 25 vanilla-registry prompts. + +The older material settings screens and Tinkers integration remain unavailable, +as on the released 1.13.2 branch. Change generation through OreSpawn. Automated +checks cover the main content and migration paths; visual and ordinary gameplay +acceptance are still needed before release. diff --git a/docs/PORTING_114.md b/docs/PORTING_114.md new file mode 100644 index 0000000..cd541f4 --- /dev/null +++ b/docs/PORTING_114.md @@ -0,0 +1,50 @@ +# Minecraft 1.14.4 port + +The starting point is released Base Minerals 2.5.2.113021, commit 6206d8a6. +The target is Forge 28.2.26, MCP snapshot 20190719-1.14.3/config +20190829.143755, Java 8, ForgeGradle 7.0.34 and Gradle 9.6.1. Gradle uses +Java 17 and Mavenizer uses Java 25. + +## Target decisions + +- Keep the baseminerals namespace, 17 block IDs, 41 item IDs, four fluid IDs, + translations and all existing recipe IDs. No equipment or Fantasy policy + is added. Niter and saltpeter remain distinct; silicon has no generated ore. +- Move block drops to native loot tables. Lithium returns one ore block; + the other six ores return a uniform 2..4+Fortune powders. A small registered + loot function preserves that exact distribution. Silk Touch returns one + ore, weak tools return nothing, and hammers use the shared crushing recipe. +- Keep the restored hardness, mining tiers, effective blast resistance and + storage-block beacon eligibility from 2.5.2. +- Use Forge 28 recipe serializers and native recipe types. Base Metals owns + shared crushing when installed; otherwise Modern Metals supplies it. The + contribution IDs stay under baseminerals. The seven existing smelts also + work in the blast furnace at half the cooking time with the same outputs/XP. +- Register fluids through Forge's fluid registry after constructing the pairs + in the sequential block event. Native fluid attributes replace Forge 25's + renderer patch. Keep molten light, colour, flow properties, dedicated + buckets and heat. The generic bucket mask/overlay artwork is reused from + the MMD Modern Metals sibling; existing ore artwork stays unchanged. +- Map the level-two ingot offers to armorer, toolsmith and weaponsmith, with + native restocking and villager experience. +- Preserve world-specific numeric mappings in baseminerals-legacy-registry.dat. + Hook the target SaveFormat and ChunkLoader before vanilla data fixing; the + chunk loader's own region directory selects the correct world's mapping. + The numeric-state lookup remains scoped to the conversion thread, and + upgraded completed chunks use 1.14's full status. Forge 25's leaves-fixer + repair and fluid-renderer hooks are not part of the Forge 28 port. +- Keep the same schema-5 OreSpawn provider, seven stable rule IDs, quantities, + shapes, heights, material groups and standard placement channel. OreSpawn + owns generation; the mod contributes no terrain, strata or fallback engine. +- Pin the public OreSpawn 4.1.7.114041 and Base Metals 3.0.2.114041 artifacts + by checksum. Modern Metals 1.14 is a separately fingerprinted local test + fixture and remains optional. Do not present it as a published dependency. + +References: [Forge's porting notes](https://docs.minecraftforge.net/en/1.14.x/legacy/porting1214/), +[Forge registries](https://docs.minecraftforge.net/en/1.14.x/concepts/registries/), +[Minecraft 1.14.4 notes](https://www.minecraft.net/en-us/article/minecraft-java-1-14-4-released), +the exact mapped Forge/Minecraft sources, and the public +[OreSpawn 4.1.7.114041 release](https://github.com/MinecraftModDevelopmentMods/OreSpawn/releases/tag/4.1.7.114041). + +The local verification receipt records actual tests and limitations. Manual +gameplay/visual acceptance and any publication are separate steps. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 23ca12f..a68ffd0 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,16 +1,18 @@ -# Releasing Base Minerals for Minecraft 1.13.2 +# Releasing Base Minerals for Minecraft 1.14.4 Build with Java 17, Temurin 8u502-b07 for compilation and Java 25 for -Mavenizer. Run check, build, verify113ReleaseArtifacts, -write113ReleaseChecksums, genEclipseRuns and eclipse. Keep the packaged +Mavenizer. Run check, build, verify114ReleaseArtifacts, +write114ReleaseChecksums, genEclipseRuns and eclipse. Keep the packaged gameplay and saved-world checks local, then complete manual testing. -Open a PR from the fork to MMD's master-1.13.2. After merging, wait for the -successful push CI run and download BaseMinerals-1.13.2-. Compare +The new master-1.14.4 branch needs to be established on MMD before opening its +first port PR. After manual acceptance, open a PR from the fork to that branch. +After merging, wait for the successful push CI run and download +BaseMinerals-1.14.4-. Compare all three jars with the locally qualified bundle. The CI bundle contains the player, sources and Javadoc jars, SHA256SUMS and CHANGELOG.txt. -Run deploy-release.yml on master-1.13.2 with the release version, full merged +Run deploy-release.yml on master-1.14.4 with the release version, full merged commit and qualified game-jar SHA-256. Leave confirm_live_publication false for verification. Set it true only when publication is authorised. The workflow checks the branch tip, successful merged CI and bundle hashes, @@ -25,4 +27,5 @@ Verify anonymous downloads and hashes on all three services, including the CurseForge dependency metadata. If a publication job fails, preserve its logs and retry only the failed job; do not duplicate an accepted upload. Base Metals is optional and OreSpawn is required. Publish Base Metals first -and keep the compatibility pin on its public 1.13.2 release. +and keep the compatibility pin on its public 1.14.4 release. The local Modern +Metals fixture must not be uploaded or bundled with Base Minerals. diff --git a/docs/WORLD_UPGRADES.md b/docs/WORLD_UPGRADES.md index b651ce1..2c5ac21 100644 --- a/docs/WORLD_UPGRADES.md +++ b/docs/WORLD_UPGRADES.md @@ -1,4 +1,4 @@ -# Base Minerals 1.13.2 upgrade checks +# Base Minerals 1.14.4 upgrade checks The older saves store a Forge registry snapshot alongside their numeric chunks. Two saves may assign different numbers to the same mineral block. The upgrade @@ -14,14 +14,27 @@ mineral coordinates and states, chest inventory slots, stack sizes, custom names, unrelated NBT tags and the saved OreSpawn mineral rules. A test chest and placed blocks extend coverage to every item and block in the source registry. The fixture also covers all 16 fluid levels for each registered -molten block. Each original chunk must use the flattened 1.13.2 format. +molten block. Each original chunk must reach the flattened 1.14.4 format +(DataVersion 1976 or later). Already flattened 1.13.2 saves are checked with +the separate named-world runner, including their inventories and saved rules. - python tools/validation/legacy113/verify_upgrade.py --java --runtime --source --output --mods [basemetals.jar] + python tools/validation/port114/verify_upgrade.py --java --runtime --source --output --mods [basemetals.jar] + +Use verify_named_upgrade.py with the same arguments for a 1.13.2 source. It +does not insert the numeric fixture or alter the source world. Keep +baseminerals-legacy-registry.dat with any previously flattened save: chunks +that were never loaded may still need its original registry mapping. The default probe chunk is (64, 64). Supply --probe-chunk X Z to use a different generated chunk outside the spawn area. Add --natural-open to check a normal -first open before converting the remaining chunks. Use verify_generation.py -with the same Java, template, output and mod arguments to census new ores. +first open before converting the remaining chunks. Use verify_census.py with +--seed and --probe to check new ores across all three vanilla dimensions. Keep the original world and its mod set together. Forge and any companion mods own conversion of their own blocks, items and saved data. + +Forge 28 may ask for confirmation when opening a Forge 25 world because the +old villager-profession registry was removed and the vanilla signs and three +dye IDs were renamed. The disposable runner accepts only those exact vanilla +lists and records the prompts. It stops for any unknown missing content. +Do not use blanket confirmation on a player world; inspect its missing list. diff --git a/gradle.properties b/gradle.properties index cbdc905..450a2e9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,6 +4,9 @@ org.gradle.configuration-cache=false org.gradle.caching=true org.gradle.parallel=false net.minecraftforge.gradle.merge-source-sets=false -minecraft_version=1.13.2 -forge_version=25.0.223 -mod_version=2.5.2.113021 +minecraft_version=1.14.4 +forge_version=28.2.26 +mod_version=2.5.2.114041 + +basemetals_version=3.0.2.114041 +modernmetals_version=3.0.0.114041 diff --git a/gradle/compatibility-114.gradle b/gradle/compatibility-114.gradle new file mode 100644 index 0000000..b7d02d2 --- /dev/null +++ b/gradle/compatibility-114.gradle @@ -0,0 +1,99 @@ +import groovy.xml.XmlParser +import groovy.xml.XmlUtil +import java.security.MessageDigest + +apply from: 'gradle/local-companions-114.gradle' + +def basePin = localCompanionPins.basemetals +def modernPin = localCompanionPins.modernmetals +def withBase = providers.gradleProperty('withBaseMetals').map { it.toBoolean() }.orElse(false) +def withModern = providers.gradleProperty('withModernMetals').map { it.toBoolean() }.orElse(false) +def published = new groovy.json.JsonSlurper().parse(file('gradle/dependencies.json')).collectEntries { [(it.id): it] } +def haveModern = modernPin.enabled || published.modernmetals != null +configurations { baseMetalsDevelopment; modernMetalsDevelopment } +def mappedBase = basePin.enabled ? files(file(basePin.pin.mappedJar)) : renamer.dependency(published.basemetals.coordinate) +def mappedModern = modernPin.enabled ? files(file(modernPin.pin.mappedJar)) : renamer.dependency(published.modernmetals.coordinate) +dependencies { + baseMetalsDevelopment mappedBase + if (withBase.get()) runtimeOnly mappedBase + if (haveModern) modernMetalsDevelopment mappedModern + if (withModern.get()) { + if (!haveModern) throw new GradleException('Run pinLocalModernMetals before using withModernMetals') + runtimeOnly mappedModern + } +} +tasks.named('compileJava') { dependsOn 'verifyLocalCompanions' } + +def profiles = ['WithBaseMetals': ['base']] +if (haveModern) { + profiles['WithModernMetals'] = ['modern'] + profiles['WithBoth'] = ['base', 'modern'] +} +tasks.register('generateCompatibilityRuns') { + dependsOn 'genEclipseRunClientForForge', 'verifyPinnedMods', 'verifyLocalCompanions' + dependsOn configurations.baseMetalsDevelopment + if (haveModern) dependsOn configurations.modernMetalsDevelopment + doLast { + profiles.each { label, mods -> + File directory = file('run/' + label) + File modDirectory = new File(directory, 'mods') + modDirectory.mkdirs() + def selected = [:] + if (mods.contains('base')) selected['BaseMetals-3.0.2.114041-mapped.jar'] = configurations.baseMetalsDevelopment.singleFile + if (mods.contains('modern')) selected['ModernMetals-3.0.0.114041-mapped.jar'] = configurations.modernMetalsDevelopment.singleFile + // Preserve replaced copies; retire only managed companion files. + modDirectory.listFiles().findAll { it.isFile() && + (it.name ==~ /(?:BaseMetals-|base-metals-240967-|ModernMetals-).+\.jar/) && + (!selected.containsKey(it.name) || !java.util.Arrays.equals(it.bytes, selected[it.name].bytes)) }.each { obsolete -> + String digest = MessageDigest.getInstance('SHA-256').digest(obsolete.bytes).encodeHex().toString() + File retained = file('.gradle/retired-compatibility-jars/' + label + '/' + digest + '-' + obsolete.name) + retained.parentFile.mkdirs() + retained.bytes = obsolete.bytes + if (!obsolete.delete()) throw new GradleException("Could not retire stale companion jar ${obsolete}") + } + selected.each { name, source -> + File target = new File(modDirectory, name) + target.bytes = source.bytes + if (!java.util.Arrays.equals(target.bytes, source.bytes)) throw new GradleException("Staged jar differs: ${target}") + } + Node launch = new XmlParser().parse(file('runClient.launch')) + launch.stringAttribute.find { it.attribute('key') == 'org.eclipse.jdt.launching.WORKING_DIRECTORY' } + .attributes().put('value', directory.absolutePath) + file('runClient' + label + '.launch').setText(XmlUtil.serialize(launch), 'UTF-8') + } + } +} +tasks.register('verifyStagedCompanions') { + group = 'verification' + dependsOn 'generateCompatibilityRuns' + doLast { + def hash = { File jar -> MessageDigest.getInstance('SHA-256').digest(jar.bytes).encodeHex().toString() } + profiles.each { label, mods -> + File directory = file('run/' + label + '/mods') + ['base': ['BaseMetals-3.0.2.114041-mapped.jar', configurations.baseMetalsDevelopment], + 'modern': ['ModernMetals-3.0.0.114041-mapped.jar', configurations.modernMetalsDevelopment]].each { kind, spec -> + if (mods.contains(kind) && hash(new File(directory, spec[0])) != hash(spec[1].singleFile)) + throw new GradleException("Wrong ${kind} jar staged for ${label}") + } + } + } +} +tasks.named('check') { dependsOn 'verifyStagedCompanions' } + +tasks.named('genEclipseRuns') { dependsOn 'generateCompatibilityRuns' } +tasks.named('eclipse') { dependsOn 'verifyStagedCompanions' } + +tasks.register('configureEclipseBuildship') { + doLast { + File target = file('.settings/org.eclipse.buildship.core.prefs') + target.parentFile.mkdirs() + Properties settings = new Properties() + ['eclipse.preferences.version':'1', 'connection.gradle.distribution':'GRADLE_DISTRIBUTION(WRAPPER)', + 'connection.gradle.user.home':gradle.gradleUserHomeDir.canonicalPath, + 'connection.project.dir':'', 'gradle.user.home':gradle.gradleUserHomeDir.canonicalPath, + 'java.home':new File(System.getProperty('java.home')).canonicalPath, + 'override.workspace.settings':'true'].each { key, value -> settings.setProperty(key, value) } + target.withOutputStream { settings.store(it, 'Generated Base Minerals Buildship settings') } + } +} +tasks.named('genEclipseRuns') { dependsOn 'configureEclipseBuildship' } diff --git a/gradle/dependencies.json b/gradle/dependencies.json index 76b4d14..098fddd 100644 --- a/gradle/dependencies.json +++ b/gradle/dependencies.json @@ -1,16 +1,23 @@ [ { "id": "orespawn", - "coordinate": "curse.maven:mmd-orespawn-245586:9611746", - "repository": "https://www.cursemaven.com", + "coordinate": "zone.moddev.mc.orespawn:OreSpawn:4.1.7.114041", + "repository": "https://maven.moddev.zone/releases", "runtime": true, - "sha256": "E65DCCA0623A20111C40779CB0FE2078E98C618FAA68F79C9A28E1E53C63957E" + "sha256": "C6171543240D43CD6273601D537D46A8F8C8A8B5992B258827E2F6F713AB7D44" }, { "id": "basemetals", - "coordinate": "zone.moddev.mc.basemetals:BaseMetals:3.0.3.113021", + "coordinate": "zone.moddev.mc.basemetals:BaseMetals:3.0.2.114041", + "repository": "https://maven.moddev.zone/releases", + "runtime": false, + "sha256": "11C0C4A6FE26B22EE794EA76CD6E0F1C5B65FB03540F9E8E0C52425CFEFB062B" + }, + { + "id": "modernmetals", + "coordinate": "zone.moddev.mc.modernmetals:ModernMetals:3.0.0.114041", "repository": "https://maven.moddev.zone/releases", "runtime": false, - "sha256": "88B9DB908249B9CD7E415F5577311ED03A22CF6BF17800688F67FC65F6BE2ECD" + "sha256": "22942EBC37BE76D940EA6EFCA53DA6E47085D72EAD95D348DE70D7526389683B" } ] diff --git a/gradle/local-companions-114.gradle b/gradle/local-companions-114.gradle new file mode 100644 index 0000000..2314626 --- /dev/null +++ b/gradle/local-companions-114.gradle @@ -0,0 +1,63 @@ +import groovy.json.JsonOutput +import groovy.json.JsonSlurper +import java.security.MessageDigest + +// Local candidates are selected by hash. Release builds keep published dependencies. +def releaseBuild = providers.gradleProperty('releaseBuild').map { it.toBoolean() }.orElse(false).get() +def definitions = [ + basemetals: [label: 'BaseMetals', version: '3.0.2.114041', checkout: '../../BaseMetals 114/BaseMetals', property: 'baseMetalsCheckout'], + modernmetals: [label: 'ModernMetals', version: '3.0.0.114041', checkout: '../../ModernMetals 114/ModernMetals', property: 'modernMetalsCheckout'] +] +def hash = { File jar -> MessageDigest.getInstance('SHA-256').digest(jar.bytes).encodeHex().toString() } +def pins = [:] +definitions.each { modId, definition -> + File pinFile = file("local-${modId}.json") + String flag = 'useLocal' + definition.label + boolean enabled = providers.gradleProperty(flag).map { it.toBoolean() } + .orElse(pinFile.isFile() && !releaseBuild).get() + if (enabled && releaseBuild) throw new GradleException("Release builds must not use local ${definition.label}") + def pin = enabled && pinFile.isFile() ? new JsonSlurper().parse(pinFile) : [:] + if (enabled && pin.isEmpty()) throw new GradleException("Run pinLocal${definition.label} first") + pins[modId] = [enabled: enabled, pin: pin] + tasks.register('pinLocal' + definition.label) { + group = 'development' + description = "Pins the already-built sibling ${definition.label} jars for local testing." + doLast { + File checkout = file(providers.gradleProperty(definition.property).orElse(definition.checkout).get()).canonicalFile + def next = [version: definition.version] + [player: "build/libs/${definition.label}-${definition.version}.jar", + mapped: "build/libs-dev/${definition.label}-${definition.version}-deobf.jar"].each { kind, path -> + File jar = new File(checkout, path) + if (!jar.isFile()) throw new GradleException("Build ${definition.label} first: ${jar}") + next[kind + 'Jar'] = jar.canonicalPath + next[kind + 'Sha256'] = hash(jar) + } + pinFile.setText(JsonOutput.prettyPrint(JsonOutput.toJson(next)) + '\n', 'UTF-8') + } + } +} +ext.localCompanionPins = pins +tasks.register('pinLocalCompanions') { + group = 'development' + dependsOn 'pinLocalBaseMetals', 'pinLocalModernMetals' +} +tasks.register('verifyLocalCompanions') { + group = 'verification' + doLast { + definitions.each { modId, definition -> + def selected = pins[modId] + if (selected.enabled) { + if (selected.pin.version != definition.version) throw new GradleException("Wrong local ${definition.label} version") + ['player', 'mapped'].each { kind -> + File jar = file(selected.pin[kind + 'Jar']) + if (!jar.isFile() || hash(jar) != selected.pin[kind + 'Sha256']) + throw new GradleException("Local ${definition.label} changed. Rebuild, run pinLocal${definition.label}, then regenerate Eclipse launches: ${jar}") + } + } + } + } +} +tasks.named('check') { dependsOn 'verifyLocalCompanions' } +tasks.withType(JavaExec).configureEach { + if (name in ['runClient', 'runServer']) dependsOn 'verifyLocalCompanions' +} diff --git a/gradle/release-113.gradle b/gradle/release-114.gradle similarity index 85% rename from gradle/release-113.gradle rename to gradle/release-114.gradle index 5892a4b..7d38455 100644 --- a/gradle/release-113.gradle +++ b/gradle/release-114.gradle @@ -37,13 +37,13 @@ tasks.withType(Javadoc).configureEach { tasks.named('jar', Jar) { manifest.attributes('Implementation-Title': archiveName, 'Implementation-Version': project.version, 'Maven-Artifact': "${expectedGroup}:${archiveName}:${project.version}".toString(), - 'Build-Target': 'minecraft-1.13.2-forge-25.0.223-java-8') + 'Build-Target': 'minecraft-1.14.4-forge-28.2.26-java-8') } tasks.named('assemble') { dependsOn playerJar, tasks.named('sourcesJar'), tasks.named('javadocJar') } def sha256 = { File file -> MessageDigest.getInstance('SHA-256').digest(file.bytes).encodeHex().toString() } def audit = { File directory -> - if (project.group.toString() != expectedGroup || !(project.version.toString() ==~ /\d+\.\d+\.\d+\.113021/)) { + if (project.group.toString() != expectedGroup || !(project.version.toString() ==~ /\d+\.\d+\.\d+\.114041/)) { throw new GradleException('Wrong Maven or Minecraft release identity') } if (directory.listFiles().findAll { it.name.endsWith('.jar') }.collect { it.name }.sort() != releaseNames.sort(false)) { @@ -77,8 +77,8 @@ def audit = { File directory -> String metadata = zip.getInputStream(zip.getEntry('META-INF/mods.toml')).getText('UTF-8') if (metadata.contains('${') || !metadata.contains('modId="' + modId + '"') || !metadata.contains('version="' + project.version + '"') - || !metadata.contains('versionRange="[1.13.2]"') - || !metadata.contains('versionRange="[4.1.7.113021,5.0.0)"')) { + || !metadata.contains('versionRange="[1.14.4]"') + || !metadata.contains('versionRange="[4.1.7.114041,5.0.0)"')) { throw new GradleException('Wrong or unresolved release mod metadata') } } @@ -86,14 +86,14 @@ def audit = { File directory -> } } -tasks.register('verify113ReleaseArtifacts') { +tasks.register('verify114ReleaseArtifacts') { group = 'verification' dependsOn tasks.named('assemble'), tasks.named('check') doLast { audit(layout.buildDirectory.dir('libs').get().asFile) } } -tasks.register('write113ReleaseChecksums') { +tasks.register('write114ReleaseChecksums') { group = 'verification' - dependsOn tasks.named('verify113ReleaseArtifacts') + dependsOn tasks.named('verify114ReleaseArtifacts') doLast { File output = layout.buildDirectory.file('release/SHA256SUMS').get().asFile output.parentFile.mkdirs() @@ -102,7 +102,7 @@ tasks.register('write113ReleaseChecksums') { }.join('\n') + '\n', 'UTF-8') } } -tasks.register('verify113PreparedReleaseArtifacts') { +tasks.register('verify114PreparedReleaseArtifacts') { group = 'verification' doLast { if (!preparedDirectory.isPresent()) throw new GradleException('preparedReleaseDir is required') @@ -146,7 +146,7 @@ publishing { } pom { name = 'Base Minerals' - description = 'Base Minerals for Minecraft 1.13.2, using Forge 25 and OreSpawn 4.' + description = 'Base Minerals for Minecraft 1.14.4, using Forge 28 and OreSpawn 4.' url = 'https://github.com/MinecraftModDevelopmentMods/BaseMinerals' licenses { license { @@ -159,8 +159,13 @@ publishing { def dependency = asNode().appendNode('dependencies').appendNode('dependency') dependency.appendNode('groupId', 'zone.moddev.mc.basemetals') dependency.appendNode('artifactId', 'BaseMetals') - dependency.appendNode('version', '3.0.3.113021') + dependency.appendNode('version', '3.0.2.114041') dependency.appendNode('optional', 'true') + def modern = dependency.parent().appendNode('dependency') + modern.appendNode('groupId', 'zone.moddev.mc.modernmetals') + modern.appendNode('artifactId', 'ModernMetals') + modern.appendNode('version', project.modernmetals_version.toString()) + modern.appendNode('optional', 'true') } } } @@ -175,18 +180,24 @@ publishing { } } } -tasks.register('verify113MavenCoordinates') { +tasks.register('verify114MavenCoordinates') { dependsOn 'generatePomFileForMavenJavaPublication' doLast { def pom = new XmlSlurper(false, false).parse(layout.buildDirectory.file('publications/mavenJava/pom-default.xml').get().asFile) if ([pom.groupId.text(), pom.artifactId.text(), pom.version.text()] != [expectedGroup, archiveName, project.version.toString()]) { throw new GradleException('Wrong Maven publication coordinates') } + ['BaseMetals': ['zone.moddev.mc.basemetals', project.basemetals_version.toString()], + 'ModernMetals': ['zone.moddev.mc.modernmetals', project.modernmetals_version.toString()]].each { name, required -> + if (!pom.dependencies.dependency.any { it.groupId.text() == required[0] && it.artifactId.text() == name + && it.version.text() == required[1] && it.optional.text() == 'true' }) + throw new GradleException('Maven metadata must pin the optional released ' + name + ' dependency') + } } } tasks.withType(PublishToMavenRepository).configureEach { - dependsOn 'verify113MavenCoordinates' - dependsOn preparedDirectory.isPresent() ? 'verify113PreparedReleaseArtifacts' : 'verify113ReleaseArtifacts' + dependsOn 'verify114MavenCoordinates' + dependsOn preparedDirectory.isPresent() ? 'verify114PreparedReleaseArtifacts' : 'verify114ReleaseArtifacts' doFirst { def url = providers.environmentVariable('MAVEN_UPLOAD_URL').getOrElse('') if (!url.startsWith('https://') || url.startsWith('https://invalid.invalid') @@ -196,3 +207,5 @@ tasks.withType(PublishToMavenRepository).configureEach { } } } + +tasks.named('check') { dependsOn 'verify114MavenCoordinates' } diff --git a/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java b/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java index f85f222..76b1cb9 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java +++ b/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java @@ -1,6 +1,5 @@ package zone.moddev.mc.baseminerals; -import net.minecraft.item.crafting.RecipeSerializers; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.DeferredWorkQueue; import net.minecraftforge.fml.DistExecutor; @@ -9,8 +8,8 @@ import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import zone.moddev.mc.baseminerals.client.MineralFluidRenderer; -import zone.moddev.mc.baseminerals.recipe.SharedCrushingSerializer; -import zone.moddev.mc.baseminerals.trade.MineralTrades; +import zone.moddev.mc.baseminerals.loot.MineralPowderCount; +import net.minecraft.world.storage.loot.functions.LootFunctionManager; import zone.moddev.mc.baseminerals.worldgen.BaseMineralsWorldgenProvider; @Mod(BaseMinerals.MOD_ID) @@ -25,8 +24,7 @@ public BaseMinerals() { private void setup(FMLCommonSetupEvent event) { DeferredWorkQueue.runLater(() -> { - RecipeSerializers.register(new SharedCrushingSerializer()); - MineralTrades.register(); + LootFunctionManager.registerFunction(new MineralPowderCount.Serializer()); }); } diff --git a/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java b/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java index 6d8264d..4486aa9 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java +++ b/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java @@ -1,54 +1,22 @@ package zone.moddev.mc.baseminerals.client; -import zone.moddev.mc.baseminerals.BaseMinerals; -import zone.moddev.mc.baseminerals.content.MineralContent; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.fluid.IFluidState; -import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.client.event.ColorHandlerEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import zone.moddev.mc.baseminerals.content.MineralContent; -/** Adds the fluid textures and colours that Forge 25 doesn't render on its own. */ +/** Forge fluid attributes provide the world sprites; item colours tint the bucket contents. */ @OnlyIn(Dist.CLIENT) public final class MineralFluidRenderer { - private static final ResourceLocation STILL = new ResourceLocation(BaseMinerals.MOD_ID, "blocks/molten_metal_still"); - private static final ResourceLocation FLOW = new ResourceLocation(BaseMinerals.MOD_ID, "blocks/molten_metal_flow"); - private static volatile TextureAtlasSprite[] sprites; - private MineralFluidRenderer() {} - public static void register() { - MinecraftForge.EVENT_BUS.addListener(MineralFluidRenderer::onTexturePre); - MinecraftForge.EVENT_BUS.addListener(MineralFluidRenderer::onTexturePost); - } - - private static void onTexturePre(TextureStitchEvent.Pre event) { - event.getMap().registerSprite(Minecraft.getInstance().getResourceManager(), STILL); - event.getMap().registerSprite(Minecraft.getInstance().getResourceManager(), FLOW); - } - - private static void onTexturePost(TextureStitchEvent.Post event) { - sprites = new TextureAtlasSprite[] { event.getMap().getSprite(STILL), event.getMap().getSprite(FLOW) }; - } - - public static boolean useOpaqueFluidPath(IFluidState state, boolean vanillaValue) { - return isOurs(state) || vanillaValue; - } - - public static TextureAtlasSprite[] overrideSprites(IFluidState state, TextureAtlasSprite[] vanillaSprites) { - TextureAtlasSprite[] current = sprites; - return isOurs(state) && current != null ? current : vanillaSprites; - } - - public static int overrideColor(IFluidState state, int vanillaColor) { - return isOurs(state) ? 0xC5C8C1 : vanillaColor; + FMLJavaModLoadingContext.get().getModEventBus().addListener(MineralFluidRenderer::bucketColours); } - - private static boolean isOurs(IFluidState state) { - return state != null && MineralContent.ownsFluid(state.getFluid()); + private static void bucketColours(ColorHandlerEvent.Item event) { + for (String material : new String[] {"lithium", "silicon"}) { + event.getItemColors().register((stack, tint) -> tint == 1 ? 0xC5C8C1 : 0xFFFFFF, + MineralContent.bucket(material)); + } } } diff --git a/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java b/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java index e3edeb8..d8052dc 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java @@ -2,27 +2,23 @@ import java.util.LinkedHashMap; import java.util.Map; -import java.util.Random; import net.minecraft.block.Block; -import net.minecraft.block.BlockFlowingFluid; +import net.minecraft.block.FlowingFluidBlock; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; -import net.minecraft.block.state.IBlockState; +import net.minecraft.block.BlockState; import net.minecraft.fluid.FlowingFluid; import net.minecraft.fluid.Fluid; import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemBucket; +import net.minecraft.item.BlockItem; +import net.minecraft.item.BucketItem; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; -import net.minecraft.init.Items; +import net.minecraft.item.Items; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.ResourceLocation; -import net.minecraft.util.IItemProvider; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.registry.IRegistry; import net.minecraft.world.IWorldReader; -import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.ToolType; @@ -46,21 +42,23 @@ public final class MineralContent { private MineralContent() {} - // Vanilla's fluid registries are shared, so use Forge's sequential block event. + // Construct pairs in the sequential block event, before blocks or buckets use them. private static void initializeFluids() { for (String name : new String[] {"lithium", "silicon"}) { Molten molten = new Molten(); MOLTEN.put(name, molten); molten.flowing = new MoltenMineralFluid.Flowing(molten); molten.source = new MoltenMineralFluid.Source(molten); - IRegistry.field_212619_h.put(id("flowing_" + name), molten.flowing); - IRegistry.field_212619_h.put(id(name), molten.source); - for (Fluid fluid : new Fluid[] {molten.flowing, molten.source}) { - fluid.getStateContainer().getValidStates().forEach(Fluid.STATE_REGISTRY::add); - } + molten.flowing.setRegistryName(id("flowing_" + name)); + molten.source.setRegistryName(id(name)); } } + @SubscribeEvent + public static void registerFluids(RegistryEvent.Register event) { + MOLTEN.values().forEach(molten -> event.getRegistry().registerAll(molten.source, molten.flowing)); + } + @SubscribeEvent public static void registerBlocks(RegistryEvent.Register event) { initializeFluids(); @@ -69,8 +67,8 @@ public static void registerBlocks(RegistryEvent.Register event) { if (!"silicon".equals(name)) putBlock(event, name + "_ore", new MineralBlock(name, true)); } MOLTEN.forEach((name, molten) -> { - molten.block = new BlockFlowingFluid(molten.source, Block.Properties.create(Material.LAVA) - .doesNotBlockMovement().hardnessAndResistance(100.0F).lightValue(10).variableOpacity()) {}; + molten.block = new MoltenMineralBlock(molten.source, Block.Properties.create(Material.LAVA) + .doesNotBlockMovement().hardnessAndResistance(100.0F).lightValue(10).variableOpacity()); putBlock(event, name, molten.block); }); } @@ -83,7 +81,7 @@ private static void putBlock(RegistryEvent.Register event, String name, B @SubscribeEvent public static void registerItems(RegistryEvent.Register event) { - BLOCKS.forEach((name, block) -> putItem(event, name, new ItemBlock(block, + BLOCKS.forEach((name, block) -> putItem(event, name, new BlockItem(block, MOLTEN.containsKey(name) ? new Item.Properties() : itemProperties()))); for (String name : MATERIALS) { putItem(event, name + "_powder", new Item(itemProperties())); @@ -92,7 +90,7 @@ public static void registerItems(RegistryEvent.Register event) { MOLTEN.forEach((name, molten) -> { putItem(event, name + "_ingot", new Item(itemProperties())); putItem(event, name + "_nugget", new Item(itemProperties())); - molten.bucket = new ItemBucket(molten.source, itemProperties().containerItem(Items.BUCKET).maxStackSize(1)); + molten.bucket = new BucketItem(molten.source, itemProperties().containerItem(Items.BUCKET).maxStackSize(1)); putItem(event, name + "_bucket", molten.bucket); }); putItem(event, "silicon_blend", new Item(itemProperties())); @@ -106,24 +104,23 @@ private static void putItem(RegistryEvent.Register event, String name, Ite private static Item.Properties itemProperties() { return new Item.Properties().group(GROUP); } public static ResourceLocation id(String name) { return new ResourceLocation(BaseMinerals.MOD_ID, name); } public static boolean ownsFluid(Fluid fluid) { return fluid instanceof MoltenMineralFluid; } + public static Item bucket(String material) { return MOLTEN.get(material).bucket; } static final class Molten { FlowingFluid source; FlowingFluid flowing; - BlockFlowingFluid block; + FlowingFluidBlock block; Item bucket; } private static final class MineralBlock extends Block { private final boolean ore; private final int harvestLevel; - private final ResourceLocation powder; MineralBlock(String material, boolean ore) { super(properties(material, ore)); this.ore = ore; this.harvestLevel = isMetal(material) ? 2 : 1; - this.powder = ore && !isMetal(material) ? id(material + "_powder") : null; } private static boolean isMetal(String material) { @@ -140,18 +137,9 @@ private static Block.Properties properties(String material, boolean ore) { .hardnessAndResistance(hardness, resistance); } - @Override public ToolType getHarvestTool(IBlockState state) { return ToolType.PICKAXE; } - @Override public int getHarvestLevel(IBlockState state) { return harvestLevel; } - @Override public IItemProvider getItemDropped(IBlockState state, World world, BlockPos pos, int fortune) { - return powder == null ? this : ForgeRegistries.ITEMS.getValue(powder); - } - @Override public int quantityDropped(IBlockState state, Random random) { - return getItemsToDropCount(state, 0, null, BlockPos.ORIGIN, random); - } - @Override public int getItemsToDropCount(IBlockState state, int fortune, World world, BlockPos pos, Random random) { - return powder == null ? 1 : 2 + random.nextInt(3 + fortune); - } - @Override public boolean isBeaconBase(IBlockState state, IWorldReader world, BlockPos pos, BlockPos beacon) { + @Override public ToolType getHarvestTool(BlockState state) { return ToolType.PICKAXE; } + @Override public int getHarvestLevel(BlockState state) { return harvestLevel; } + @Override public boolean isBeaconBase(BlockState state, IWorldReader world, BlockPos pos, BlockPos beacon) { return !ore; } @Override @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java new file mode 100644 index 0000000..e4f4d5a --- /dev/null +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java @@ -0,0 +1,23 @@ +package zone.moddev.mc.baseminerals.content; + +import net.minecraft.block.BlockState; +import net.minecraft.block.FlowingFluidBlock; +import net.minecraft.entity.Entity; +import net.minecraft.entity.LivingEntity; +import net.minecraft.fluid.FlowingFluid; +import net.minecraft.util.DamageSource; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +/** Keeps molten-block heat without declaring the custom fluids to be vanilla lava. */ +public final class MoltenMineralBlock extends FlowingFluidBlock { + public MoltenMineralBlock(FlowingFluid fluid, Properties properties) { super(fluid, properties); } + @Override public void onEntityCollision(BlockState state, World world, BlockPos pos, Entity entity) { + super.onEntityCollision(state, world, pos, entity); + if (!world.isRemote && entity instanceof LivingEntity && !entity.isImmuneToFire() && !entity.isInLava() + && entity.getBoundingBox().minY < pos.getY() + state.getFluidState().func_215679_a(world, pos)) { + entity.attackEntityFrom(DamageSource.LAVA, 4.0F); + entity.setFire(15); + } + } +} diff --git a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java index 9f61048..ca9bdc2 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java @@ -1,19 +1,21 @@ package zone.moddev.mc.baseminerals.content; -import net.minecraft.block.BlockFlowingFluid; -import net.minecraft.block.state.IBlockState; +import net.minecraft.block.FlowingFluidBlock; +import net.minecraft.block.BlockState; import net.minecraft.fluid.FlowingFluid; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.IFluidState; import net.minecraft.item.Item; import net.minecraft.state.StateContainer; import net.minecraft.util.BlockRenderLayer; -import net.minecraft.util.EnumFacing; +import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IWorld; -import net.minecraft.world.IWorldReaderBase; +import net.minecraft.world.IWorldReader; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.fluids.FluidAttributes; +import net.minecraft.util.ResourceLocation; /** Common flow behaviour for the molten metals. */ public abstract class MoltenMineralFluid extends FlowingFluid { @@ -23,6 +25,12 @@ protected MoltenMineralFluid(MineralContent.Molten content) { this.content = content; } + @Override protected FluidAttributes createAttributes() { + return FluidAttributes.builder(new ResourceLocation("baseminerals", "block/molten_metal_still"), + new ResourceLocation("baseminerals", "block/molten_metal_flow")) + .color(0xFFC5C8C1).density(2000).viscosity(10000).temperature(330).luminosity(10).build(this); + } + @Override public Fluid getFlowingFluid() { return content.flowing; } @Override public Fluid getStillFluid() { return content.source; } @@ -31,31 +39,32 @@ protected MoltenMineralFluid(MineralContent.Molten content) { @Override @OnlyIn(Dist.CLIENT) public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.TRANSLUCENT; } @Override protected boolean canSourcesMultiply() { return false; } - @Override protected void beforeReplacingBlock(IWorld world, BlockPos pos, IBlockState state) { - state.dropBlockAsItem(world.getWorld(), pos, 0); + @Override protected void beforeReplacingBlock(IWorld world, BlockPos pos, BlockState state) { + net.minecraft.block.Block.spawnDrops(state, world.getWorld(), pos); } - @Override public int getSlopeFindDistance(IWorldReaderBase world) { return 2; } - @Override public int getLevelDecreasePerBlock(IWorldReaderBase world) { return 2; } - @Override public int getTickRate(IWorldReaderBase world) { return 30; } + @Override public int getSlopeFindDistance(IWorldReader world) { return 2; } + @Override public int getLevelDecreasePerBlock(IWorldReader world) { return 2; } + @Override public int getTickRate(IWorldReader world) { return 30; } @Override protected float getExplosionResistance() { return 100.0F; } @Override public boolean isEquivalentTo(Fluid fluid) { return fluid == content.source || fluid == content.flowing; } - @Override protected boolean canOtherFlowInto(IFluidState state, Fluid fluid, EnumFacing direction) { - return direction == EnumFacing.DOWN && !fluid.isEquivalentTo(this); + @Override protected boolean func_215665_a(IFluidState state, net.minecraft.world.IBlockReader world, + BlockPos pos, Fluid fluid, Direction direction) { + return direction == Direction.DOWN && !fluid.isEquivalentTo(this); } - @Override public IBlockState getBlockState(IFluidState state) { + @Override public BlockState getBlockState(IFluidState state) { return content.block.getDefaultState() - .with(BlockFlowingFluid.LEVEL, Integer.valueOf(getLevelFromState(state))); + .with(FlowingFluidBlock.LEVEL, Integer.valueOf(getLevelFromState(state))); } public static final class Flowing extends MoltenMineralFluid { public Flowing(MineralContent.Molten content) { super(content); } @Override protected void fillStateContainer(StateContainer.Builder builder) { super.fillStateContainer(builder); - builder.add(LEVEL_1_TO_8); + builder.add(LEVEL_1_8); } - @Override public int getLevel(IFluidState state) { return state.get(LEVEL_1_TO_8); } + @Override public int getLevel(IFluidState state) { return state.get(LEVEL_1_8); } @Override public boolean isSource(IFluidState state) { return false; } } diff --git a/src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java b/src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java new file mode 100644 index 0000000..b75fa75 --- /dev/null +++ b/src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java @@ -0,0 +1,30 @@ +package zone.moddev.mc.baseminerals.loot; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonObject; +import net.minecraft.enchantment.EnchantmentHelper; +import net.minecraft.enchantment.Enchantments; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.storage.loot.LootContext; +import net.minecraft.world.storage.loot.LootFunction; +import net.minecraft.world.storage.loot.LootParameters; +import net.minecraft.world.storage.loot.conditions.ILootCondition; + +/** Preserves the earlier uniform 2..4+Fortune powder yield in native block loot. */ +public final class MineralPowderCount extends LootFunction { + private MineralPowderCount(ILootCondition[] conditions) { super(conditions); } + + @Override protected ItemStack doApply(ItemStack stack, LootContext context) { + ItemStack tool = context.get(LootParameters.TOOL); + int fortune = tool == null ? 0 : EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, tool); + stack.setCount(2 + context.getRandom().nextInt(3 + Math.max(0, fortune))); + return stack; + } + + public static final class Serializer extends LootFunction.Serializer { + public Serializer() { super(new ResourceLocation("baseminerals", "mineral_powder_count"), MineralPowderCount.class); } + @Override public MineralPowderCount deserialize(JsonObject json, JsonDeserializationContext context, + ILootCondition[] conditions) { return new MineralPowderCount(conditions); } + } +} diff --git a/src/main/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgrade.java b/src/main/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgrade.java index 0bf1924..360067e 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgrade.java +++ b/src/main/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgrade.java @@ -1,6 +1,6 @@ package zone.moddev.mc.baseminerals.migration; -import com.mojang.datafixers.DSL.TypeReference; +import net.minecraft.util.datafix.DefaultTypeReferences; import com.mojang.datafixers.DataFixer; import com.mojang.datafixers.Dynamic; import java.io.File; @@ -16,16 +16,15 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.minecraft.block.Block; -import net.minecraft.block.BlockFlowingFluid; -import net.minecraft.block.state.IBlockState; +import net.minecraft.block.FlowingFluidBlock; +import net.minecraft.block.BlockState; import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.INBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.INBT; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.nbt.ListNBT; import net.minecraft.nbt.NBTUtil; import net.minecraft.util.ResourceLocation; import net.minecraft.util.datafix.fixes.BlockStateFlatteningMap; -import net.minecraft.world.chunk.storage.AnvilChunkLoader; import net.minecraft.world.storage.SaveHandler; import net.minecraftforge.registries.ForgeRegistries; @@ -36,17 +35,17 @@ public final class LegacyWorldUpgrade { private static final String PRESERVE = "BaseMineralsLegacyPreserveChunk"; private static final ThreadLocal[]>> ACTIVE = new ThreadLocal<>(); private static final Map[]>> WORLDS = new ConcurrentHashMap<>(); - private static final Map DISCOVERED = new ConcurrentHashMap<>(); + private static final Map DISCOVERED = new ConcurrentHashMap<>(); private LegacyWorldUpgrade() {} - public static void prepareWorld(NBTTagCompound root, File file, SaveHandler handler) { + public static void prepareWorld(CompoundNBT root, File file, SaveHandler handler) { migrateItems(root.getCompound("Data").getCompound("Player")); if (Boolean.getBoolean("baseminerals.debugUpgrade")) { LOGGER.info("World read {} active={} dataVersion={} root={}", file, handler != null, root.getCompound("Data").getInt("DataVersion"), root.keySet()); } - NBTTagList minerals = mineralIds(root); + ListNBT minerals = mineralIds(root); if (minerals.isEmpty()) return; try { Path directory = file.getCanonicalFile().getParentFile().toPath(); @@ -59,12 +58,12 @@ public static void prepareWorld(NBTTagCompound root, File file, SaveHandler hand } } - private static NBTTagList mineralIds(NBTTagCompound root) { - NBTTagList ids = root.getCompound("FML").getCompound("Registries") + private static ListNBT mineralIds(CompoundNBT root) { + ListNBT ids = root.getCompound("FML").getCompound("Registries") .getCompound("minecraft:blocks").getList("ids", 10); - NBTTagList minerals = new NBTTagList(); + ListNBT minerals = new ListNBT(); for (int i = 0; i < ids.size(); i++) { - NBTTagCompound id = ids.getCompound(i); + CompoundNBT id = ids.getCompound(i); if (id.getString("K").startsWith("baseminerals:")) minerals.add(id.copy()); } if (Boolean.getBoolean("baseminerals.debugUpgrade")) { @@ -73,11 +72,11 @@ private static NBTTagList mineralIds(NBTTagCompound root) { return minerals; } - private static synchronized Map[]> persistRegistry(Path directory, NBTTagList minerals) + private static synchronized Map[]> persistRegistry(Path directory, ListNBT minerals) throws IOException { Path snapshot = directory.resolve(SNAPSHOT); - NBTTagCompound registry = new NBTTagCompound(); - registry.setTag("Blocks", minerals); + CompoundNBT registry = new CompoundNBT(); + registry.put("Blocks", minerals); Map[]> states = bake(minerals); if (Files.isRegularFile(snapshot)) { if (!registry.equals(CompressedStreamTools.readCompressed(Files.newInputStream(snapshot)))) { @@ -97,15 +96,15 @@ private static synchronized Map[]> persistRegistry(Path dire return states; } - public static NBTTagCompound fixChunk(DataFixer fixer, TypeReference type, NBTTagCompound chunk, - int fromVersion, int toVersion, AnvilChunkLoader loader) { + public static CompoundNBT fixChunk(DataFixer fixer, DefaultTypeReferences type, CompoundNBT chunk, + int fromVersion, int toVersion, File regionDirectory) { migrateItems(chunk.getCompound("Level")); - Map[]> states = statesFor(loader.chunkSaveLocation); + Map[]> states = statesFor(regionDirectory); if (states.isEmpty()) return NBTUtil.update(fixer, type, chunk, fromVersion, toVersion); - NBTTagCompound level = chunk.getCompound("Level"); - level.setBoolean("TerrainPopulated", true); - level.setBoolean("LightPopulated", true); - level.setBoolean(PRESERVE, true); + CompoundNBT level = chunk.getCompound("Level"); + level.putBoolean("TerrainPopulated", true); + level.putBoolean("LightPopulated", true); + level.putBoolean(PRESERVE, true); Map[]> previous = ACTIVE.get(); ACTIVE.set(states); try { @@ -116,12 +115,12 @@ public static NBTTagCompound fixChunk(DataFixer fixer, TypeReference type, NBTTa } } - public static NBTTagCompound finishChunk(DataFixer fixer, TypeReference type, NBTTagCompound chunk, int version) { - NBTTagCompound fixed = NBTUtil.update(fixer, type, chunk, version); - NBTTagCompound level = fixed.getCompound("Level"); + public static CompoundNBT finishChunk(DataFixer fixer, DefaultTypeReferences type, CompoundNBT chunk, int version) { + CompoundNBT fixed = NBTUtil.update(fixer, type, chunk, version); + CompoundNBT level = fixed.getCompound("Level"); if (level.getBoolean(PRESERVE)) { - level.setString("Status", "postprocessed"); - level.removeTag(PRESERVE); + level.putString("Status", "full"); + level.remove(PRESERVE); } return fixed; } @@ -143,7 +142,7 @@ private static Map[]> statesFor(File chunkDirectory) { if (Files.isRegularFile(snapshot)) { return WORLDS.computeIfAbsent(directory, ignored -> { try { - NBTTagCompound data = CompressedStreamTools.readCompressed(Files.newInputStream(snapshot)); + CompoundNBT data = CompressedStreamTools.readCompressed(Files.newInputStream(snapshot)); return bake(data.getList("Blocks", 10)); } catch (IOException e) { throw new IllegalStateException("Could not read " + snapshot, e); @@ -152,7 +151,7 @@ private static Map[]> statesFor(File chunkDirectory) { } Path level = directory.resolve("level.dat"); if (Files.isRegularFile(level)) { - NBTTagList minerals = DISCOVERED.get(directory); + ListNBT minerals = DISCOVERED.get(directory); if (minerals == null) { minerals = mineralIds(CompressedStreamTools.readCompressed(Files.newInputStream(level))); } @@ -166,10 +165,10 @@ private static Map[]> statesFor(File chunkDirectory) { } } - private static Map[]> bake(NBTTagList ids) { + private static Map[]> bake(ListNBT ids) { Map[]> result = new HashMap<>(); for (int i = 0; i < ids.size(); i++) { - NBTTagCompound id = ids.getCompound(i); + CompoundNBT id = ids.getCompound(i); ResourceLocation name = new ResourceLocation(id.getString("K")); int numeric = id.getInt("V"); if (!"baseminerals".equals(name.getNamespace()) || numeric < 1 || numeric > 4095 @@ -179,8 +178,8 @@ private static Map[]> bake(NBTTagList ids) { Block block = ForgeRegistries.BLOCKS.getValue(name); Dynamic[] entries = new Dynamic[16]; for (int meta = 0; meta < entries.length; meta++) { - IBlockState state = block.getDefaultState(); - if (block instanceof BlockFlowingFluid) state = state.with(BlockFlowingFluid.LEVEL, meta); + BlockState state = block.getDefaultState(); + if (block instanceof FlowingFluidBlock) state = state.with(FlowingFluidBlock.LEVEL, meta); entries[meta] = BlockStateFlatteningMap.makeDynamic(NBTUtil.writeBlockState(state).toString()); } result.put(numeric, entries); @@ -188,24 +187,24 @@ private static Map[]> bake(NBTTagList ids) { return Collections.unmodifiableMap(result); } - public static void migrateItems(INBTBase value) { - if (value instanceof NBTTagCompound) { - NBTTagCompound compound = (NBTTagCompound) value; + public static void migrateItems(INBT value) { + if (value instanceof CompoundNBT) { + CompoundNBT compound = (CompoundNBT) value; if ("forge:bucketfilled".equals(compound.getString("id")) && compound.contains("Count", 99) && compound.contains("tag", 10)) { - NBTTagCompound tag = compound.getCompound("tag"); + CompoundNBT tag = compound.getCompound("tag"); String fluid = tag.getString("FluidName"); if (fluid.startsWith("baseminerals:")) fluid = fluid.substring("baseminerals:".length()); if ("lithium".equals(fluid) || "silicon".equals(fluid)) { - compound.setString("id", "baseminerals:" + fluid + "_bucket"); - tag.removeTag("FluidName"); - tag.removeTag("Amount"); - if (tag.isEmpty()) compound.removeTag("tag"); + compound.putString("id", "baseminerals:" + fluid + "_bucket"); + tag.remove("FluidName"); + tag.remove("Amount"); + if (tag.isEmpty()) compound.remove("tag"); } } - for (String key : new ArrayList<>(compound.keySet())) migrateItems(compound.getTag(key)); - } else if (value instanceof NBTTagList) { - NBTTagList list = (NBTTagList) value; + for (String key : new ArrayList<>(compound.keySet())) migrateItems(compound.get(key)); + } else if (value instanceof ListNBT) { + ListNBT list = (ListNBT) value; for (int i = 0; i < list.size(); i++) migrateItems(list.get(i)); } } diff --git a/src/main/java/zone/moddev/mc/baseminerals/recipe/SharedCrushingSerializer.java b/src/main/java/zone/moddev/mc/baseminerals/recipe/SharedCrushingSerializer.java index 2ba4e59..e418c04 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/recipe/SharedCrushingSerializer.java +++ b/src/main/java/zone/moddev/mc/baseminerals/recipe/SharedCrushingSerializer.java @@ -4,15 +4,26 @@ import com.google.gson.JsonSyntaxException; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.IRecipeSerializer; -import net.minecraft.item.crafting.RecipeSerializers; +import net.minecraft.item.crafting.RecipeManager; import net.minecraft.network.PacketBuffer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.ModList; +import net.minecraftforge.event.RegistryEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.registries.ForgeRegistryEntry; import zone.moddev.mc.baseminerals.BaseMinerals; /** Selects a crushing type when data packs load. The selected type handles recipe sync. */ -public final class SharedCrushingSerializer implements IRecipeSerializer { +@Mod.EventBusSubscriber(modid = BaseMinerals.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD) +public final class SharedCrushingSerializer extends ForgeRegistryEntry> implements IRecipeSerializer> { private static final ResourceLocation NAME = new ResourceLocation(BaseMinerals.MOD_ID, "shared_crushing"); + public SharedCrushingSerializer() { setRegistryName(NAME); } + + @SubscribeEvent + public static void register(RegistryEvent.Register> event) { + event.getRegistry().register(new SharedCrushingSerializer()); + } @Override public IRecipe read(ResourceLocation id, JsonObject json) { @@ -29,7 +40,7 @@ public IRecipe read(ResourceLocation id, JsonObject json) { shared.addProperty("type", host + ":crushing"); shared.add("ingredient", json.get("ingredient")); shared.add("result", json.get("result")); - return RecipeSerializers.deserialize(id, shared); + return RecipeManager.deserializeRecipe(id, shared); } @Override @@ -42,8 +53,4 @@ public void write(PacketBuffer buffer, IRecipe recipe) { throw new UnsupportedOperationException("Shared crushing uses the selected mod's serializer for sync"); } - @Override - public ResourceLocation getName() { - return NAME; - } } diff --git a/src/main/java/zone/moddev/mc/baseminerals/trade/MineralTrades.java b/src/main/java/zone/moddev/mc/baseminerals/trade/MineralTrades.java index 6685a31..f4f5ab9 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/trade/MineralTrades.java +++ b/src/main/java/zone/moddev/mc/baseminerals/trade/MineralTrades.java @@ -1,26 +1,30 @@ package zone.moddev.mc.baseminerals.trade; -import net.minecraft.init.Items; +import net.minecraft.entity.merchant.villager.VillagerProfession; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.item.MerchantOffer; import net.minecraft.util.ResourceLocation; -import net.minecraft.village.MerchantRecipe; -import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession; +import net.minecraftforge.event.village.VillagerTradesEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; import net.minecraftforge.registries.ForgeRegistries; +import zone.moddev.mc.baseminerals.BaseMinerals; -/** The old shared library offered one ingot for four or five emeralds at smith level two. */ +/** Carries the level-two ingot offers to the three native smith professions. */ +@Mod.EventBusSubscriber(modid = BaseMinerals.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE) public final class MineralTrades { private MineralTrades() {} - - public static void register() { - VillagerProfession smith = ForgeRegistries.VILLAGER_PROFESSIONS.getValue( - new ResourceLocation("minecraft", "smith")); - for (int career = 1; career <= 3; career++) { - for (String material : new String[] {"lithium", "silicon"}) { - Item ingot = ForgeRegistries.ITEMS.getValue(new ResourceLocation("baseminerals", material + "_ingot")); - smith.getCareer(career).addTrade(2, (merchant, recipes, random) -> recipes.add( - new MerchantRecipe(new ItemStack(Items.EMERALD, 4 + random.nextInt(2)), new ItemStack(ingot)))); - } + @SubscribeEvent + public static void register(VillagerTradesEvent event) { + VillagerProfession type = event.getType(); + if (type != VillagerProfession.ARMORER && type != VillagerProfession.WEAPONSMITH + && type != VillagerProfession.TOOLSMITH) return; + for (String material : new String[] {"lithium", "silicon"}) { + Item ingot = ForgeRegistries.ITEMS.getValue(new ResourceLocation("baseminerals", material + "_ingot")); + event.getTrades().get(2).add((merchant, random) -> new MerchantOffer( + new ItemStack(Items.EMERALD, 4 + random.nextInt(2)), new ItemStack(ingot), 12, 5, 0.05F)); } } } diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index de1c8f8..ddf15a4 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -1,5 +1,5 @@ modLoader="javafml" -loaderVersion="[25,)" +loaderVersion="[28,)" license="LGPL-2.1" [[mods]] @@ -13,20 +13,27 @@ description="Adds mineral ores, blocks, powders, alloys and molten minerals." [[dependencies.baseminerals]] modId="minecraft" mandatory=true -versionRange="[1.13.2]" +versionRange="[1.14.4]" ordering="NONE" side="BOTH" [[dependencies.baseminerals]] modId="orespawn" mandatory=true -versionRange="[4.1.7.113021,5.0.0)" +versionRange="[4.1.7.114041,5.0.0)" ordering="AFTER" side="BOTH" [[dependencies.baseminerals]] modId="basemetals" mandatory=false -versionRange="[3.0.3.113021,4.0.0)" +versionRange="[3.0.2.114041,4.0.0)" +ordering="AFTER" +side="BOTH" + +[[dependencies.baseminerals]] +modId="modernmetals" +mandatory=false +versionRange="[3.0.0.114041,4.0.0)" ordering="AFTER" side="BOTH" diff --git a/src/main/resources/assets/baseminerals/models/block/lithium_molten.json b/src/main/resources/assets/baseminerals/models/block/lithium_molten.json index 294aa9c..fab5b80 100644 --- a/src/main/resources/assets/baseminerals/models/block/lithium_molten.json +++ b/src/main/resources/assets/baseminerals/models/block/lithium_molten.json @@ -1,5 +1,5 @@ { "textures": { - "particle": "baseminerals:blocks/molten_metal_still" + "particle": "baseminerals:block/molten_metal_still" } } diff --git a/src/main/resources/assets/baseminerals/models/block/silicon_molten.json b/src/main/resources/assets/baseminerals/models/block/silicon_molten.json index 294aa9c..fab5b80 100644 --- a/src/main/resources/assets/baseminerals/models/block/silicon_molten.json +++ b/src/main/resources/assets/baseminerals/models/block/silicon_molten.json @@ -1,5 +1,5 @@ { "textures": { - "particle": "baseminerals:blocks/molten_metal_still" + "particle": "baseminerals:block/molten_metal_still" } } diff --git a/src/main/resources/assets/baseminerals/models/item/lithium.json b/src/main/resources/assets/baseminerals/models/item/lithium.json index a36bdad..50e0cea 100644 --- a/src/main/resources/assets/baseminerals/models/item/lithium.json +++ b/src/main/resources/assets/baseminerals/models/item/lithium.json @@ -1,6 +1,6 @@ { "parent": "minecraft:item/generated", "textures": { - "layer0": "baseminerals:blocks/molten_metal_still" + "layer0": "baseminerals:block/molten_metal_still" } } diff --git a/src/main/resources/assets/baseminerals/models/item/lithium_bucket.json b/src/main/resources/assets/baseminerals/models/item/lithium_bucket.json index 12449e6..845f45a 100644 --- a/src/main/resources/assets/baseminerals/models/item/lithium_bucket.json +++ b/src/main/resources/assets/baseminerals/models/item/lithium_bucket.json @@ -1,6 +1,8 @@ { - "parent": "minecraft:item/generated", + "parent": "item/generated", "textures": { - "layer0": "minecraft:item/lava_bucket" + "layer0": "minecraft:item/bucket", + "layer1": "baseminerals:items/bucket_fluid", + "layer2": "baseminerals:items/bucket_overlay" } } diff --git a/src/main/resources/assets/baseminerals/models/item/silicon.json b/src/main/resources/assets/baseminerals/models/item/silicon.json index a36bdad..50e0cea 100644 --- a/src/main/resources/assets/baseminerals/models/item/silicon.json +++ b/src/main/resources/assets/baseminerals/models/item/silicon.json @@ -1,6 +1,6 @@ { "parent": "minecraft:item/generated", "textures": { - "layer0": "baseminerals:blocks/molten_metal_still" + "layer0": "baseminerals:block/molten_metal_still" } } diff --git a/src/main/resources/assets/baseminerals/models/item/silicon_bucket.json b/src/main/resources/assets/baseminerals/models/item/silicon_bucket.json index 12449e6..845f45a 100644 --- a/src/main/resources/assets/baseminerals/models/item/silicon_bucket.json +++ b/src/main/resources/assets/baseminerals/models/item/silicon_bucket.json @@ -1,6 +1,8 @@ { - "parent": "minecraft:item/generated", + "parent": "item/generated", "textures": { - "layer0": "minecraft:item/lava_bucket" + "layer0": "minecraft:item/bucket", + "layer1": "baseminerals:items/bucket_fluid", + "layer2": "baseminerals:items/bucket_overlay" } } diff --git a/src/main/resources/assets/baseminerals/textures/blocks/molten_metal_flow.png b/src/main/resources/assets/baseminerals/textures/block/molten_metal_flow.png similarity index 100% rename from src/main/resources/assets/baseminerals/textures/blocks/molten_metal_flow.png rename to src/main/resources/assets/baseminerals/textures/block/molten_metal_flow.png diff --git a/src/main/resources/assets/baseminerals/textures/blocks/molten_metal_flow.png.mcmeta b/src/main/resources/assets/baseminerals/textures/block/molten_metal_flow.png.mcmeta old mode 100755 new mode 100644 similarity index 100% rename from src/main/resources/assets/baseminerals/textures/blocks/molten_metal_flow.png.mcmeta rename to src/main/resources/assets/baseminerals/textures/block/molten_metal_flow.png.mcmeta diff --git a/src/main/resources/assets/baseminerals/textures/blocks/molten_metal_still.png b/src/main/resources/assets/baseminerals/textures/block/molten_metal_still.png similarity index 100% rename from src/main/resources/assets/baseminerals/textures/blocks/molten_metal_still.png rename to src/main/resources/assets/baseminerals/textures/block/molten_metal_still.png diff --git a/src/main/resources/assets/baseminerals/textures/blocks/molten_metal_still.png.mcmeta b/src/main/resources/assets/baseminerals/textures/block/molten_metal_still.png.mcmeta old mode 100755 new mode 100644 similarity index 100% rename from src/main/resources/assets/baseminerals/textures/blocks/molten_metal_still.png.mcmeta rename to src/main/resources/assets/baseminerals/textures/block/molten_metal_still.png.mcmeta diff --git a/src/main/resources/assets/baseminerals/textures/items/bucket_fluid.png b/src/main/resources/assets/baseminerals/textures/items/bucket_fluid.png new file mode 100644 index 0000000000000000000000000000000000000000..1899e092713eaac8fda28776a99bdaae523d9c1f GIT binary patch literal 163 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|SkfJR9T^xl z_H+M9WCij$3p^r=85sBugD~Uq{1qucK?_e8#}Etua;UHsXTO+?zkP@+PdCys%k)~>zsMZTN?&t)`2 zzTIYWRypd@Lc{ya5i8uE{R`kY$joq6;>a3BS54lfC2I^9$gnV+;dvgm%b1DbLY`og z|N8lkkA!+9^>(Rp3nsjE>Yo>Q%h7Z}Nn<(hzu)3!I!Dx({V;e8bPfZ9r>mdKI;Vst E02tCn(EtDd literal 0 HcmV?d00001 diff --git a/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js b/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js index 0d7ac05..fd5137e 100644 --- a/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js +++ b/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js @@ -6,8 +6,8 @@ var LabelNode = Java.type('org.objectweb.asm.tree.LabelNode'); var MethodInsnNode = Java.type('org.objectweb.asm.tree.MethodInsnNode'); var VarInsnNode = Java.type('org.objectweb.asm.tree.VarInsnNode'); var UPGRADE = 'zone/moddev/mc/baseminerals/migration/LegacyWorldUpgrade'; -var NBT = 'Lnet/minecraft/nbt/NBTTagCompound;'; -var FIX_ARGS = '(Lcom/mojang/datafixers/DataFixer;Lcom/mojang/datafixers/DSL$TypeReference;' + NBT; +var NBT = 'Lnet/minecraft/nbt/CompoundNBT;'; +var FIX_ARGS = '(Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/util/datafix/DefaultTypeReferences;' + NBT; function call(name, descriptor) { return new MethodInsnNode(Opcodes.INVOKESTATIC, UPGRADE, name, descriptor, false); @@ -27,44 +27,10 @@ function isNbtRead(insn) { && previous.desc.endsWith(')' + NBT); } +var FieldInsnNode = Java.type('org.objectweb.asm.tree.FieldInsnNode'); +var MethodNode = Java.type('org.objectweb.asm.tree.MethodNode'); function initializeCoreMod() { return { - 'baseminerals_forge25_leaves_fixer': { - 'target': { 'type': 'CLASS', 'name': 'net.minecraft.util.datafix.fixes.LeavesFix$Section' }, - 'transformer': function(classNode) { - var patched = false; - for (var i = 0; i < classNode.methods.size(); ++i) { - var method = classNode.methods.get(i); - if (method.desc !== '(Lcom/mojang/datafixers/Typed;)Lcom/mojang/datafixers/Typed;') continue; - for (var instruction = method.instructions.getFirst(); instruction !== null; - instruction = instruction.getNext()) { - // Some Forge installations already contain the corrected erased overload. - if (instruction.getOpcode() === Opcodes.INVOKEVIRTUAL - && instruction.owner === 'com/mojang/datafixers/Typed' && instruction.name === 'set' - && instruction.desc === '(Lcom/mojang/datafixers/OpticFinder;' + - 'Ljava/lang/Object;)Lcom/mojang/datafixers/Typed;') { - patched = true; - continue; - } - if (instruction.getOpcode() !== Opcodes.CHECKCAST - || instruction.desc !== 'com/mojang/datafixers/Typed') continue; - var call = instruction.getNext(); - while (call !== null && call.getOpcode() < 0) call = call.getNext(); - if (call === null || call.getOpcode() !== Opcodes.INVOKEVIRTUAL - || call.owner !== 'com/mojang/datafixers/Typed' || call.name !== 'set' - || call.desc !== '(Lcom/mojang/datafixers/OpticFinder;' + - 'Lcom/mojang/datafixers/Typed;)Lcom/mojang/datafixers/Typed;') continue; - method.instructions.remove(instruction); - call.desc = '(Lcom/mojang/datafixers/OpticFinder;' + - 'Ljava/lang/Object;)Lcom/mojang/datafixers/Typed;'; - patched = true; - break; - } - } - if (!patched) throw new Error('Base Minerals could not repair the Forge 25 leaves data fixer'); - return classNode; - } - }, 'baseminerals_numeric_states': { 'target': { 'type': 'CLASS', 'name': 'net.minecraft.util.datafix.fixes.BlockStateFlatteningMap' }, 'transformer': function(node) { @@ -84,11 +50,11 @@ function initializeCoreMod() { method.instructions.insert(prefix); return node; } - throw new Error('Base Minerals could not find the Forge 25 numeric state converter'); + throw new Error('Base Minerals could not find the Forge 28 numeric state converter'); } }, 'baseminerals_save_registry': { - 'target': { 'type': 'CLASS', 'name': 'net.minecraft.world.storage.SaveFormatOld' }, + 'target': { 'type': 'CLASS', 'name': 'net.minecraft.world.storage.SaveFormat' }, 'transformer': function(node) { var descriptor = '(Ljava/io/File;Lcom/mojang/datafixers/DataFixer;' + 'Lnet/minecraft/world/storage/SaveHandler;)Lnet/minecraft/world/storage/WorldInfo;'; @@ -107,25 +73,49 @@ function initializeCoreMod() { return node; } } - throw new Error('Base Minerals could not find the Forge 25 world registry reader'); + throw new Error('Base Minerals could not find the Forge 28 world registry reader'); + } + }, + 'baseminerals_region_directory': { + target: {type: 'CLASS', name: 'net.minecraft.world.chunk.storage.RegionFileCache'}, + transformer: function(node) { + var field = null; + for (var i = 0; i < node.fields.size(); ++i) { + var candidate = node.fields.get(i); + if (candidate.desc !== 'Ljava/io/File;') continue; + if (field !== null) throw new Error('Ambiguous Forge 28 region directory'); + field = candidate; + } + if (field === null) throw new Error('Missing Forge 28 region directory'); + var getter = new MethodNode(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, + 'baseminerals$getRegionDirectory', '()Ljava/io/File;', null, null); + getter.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + getter.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, node.name, field.name, field.desc)); + getter.instructions.add(new InsnNode(Opcodes.ARETURN)); + getter.maxStack = 1; + getter.maxLocals = 1; + node.methods.add(getter); + return node; } }, 'baseminerals_chunk_upgrade': { - 'target': { 'type': 'CLASS', 'name': 'net.minecraft.world.chunk.storage.AnvilChunkLoader' }, - 'transformer': function(node) { - var descriptor = '(Lnet/minecraft/world/dimension/DimensionType;' - + 'Lnet/minecraft/world/storage/WorldSavedDataStorage;II)' + NBT; + target: {type: 'CLASS', name: 'net.minecraft.world.chunk.storage.ChunkLoader'}, + transformer: function(node) { var patched = 0; - for (var i = 0; i < node.methods.size(); i++) { + for (var i = 0; i < node.methods.size(); ++i) { var method = node.methods.get(i); - if (method.desc !== descriptor) continue; - for (var insn = method.instructions.getFirst(); insn !== null; ) { + if (method.desc !== '(Lnet/minecraft/world/dimension/DimensionType;Ljava/util/function/Supplier;' + NBT + ')' + NBT) continue; + for (var insn = method.instructions.getFirst(); insn !== null;) { var next = insn.getNext(); if (insn.getOpcode() === Opcodes.INVOKESTATIC && insn.owner === 'net/minecraft/nbt/NBTUtil') { if (insn.desc === FIX_ARGS + 'II)' + NBT) { - method.instructions.insertBefore(insn, new VarInsnNode(Opcodes.ALOAD, 0)); - method.instructions.set(insn, call('fixChunk', FIX_ARGS - + 'IILnet/minecraft/world/chunk/storage/AnvilChunkLoader;)' + NBT)); + var directory = new InsnList(); + directory.add(new VarInsnNode(Opcodes.ALOAD, 0)); + directory.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, + 'net/minecraft/world/chunk/storage/RegionFileCache', + 'baseminerals$getRegionDirectory', '()Ljava/io/File;', false)); + method.instructions.insertBefore(insn, directory); + method.instructions.set(insn, call('fixChunk', FIX_ARGS + 'IILjava/io/File;)' + NBT)); patched++; } else if (insn.desc === FIX_ARGS + 'I)' + NBT) { method.instructions.set(insn, call('finishChunk', FIX_ARGS + 'I)' + NBT)); @@ -135,7 +125,7 @@ function initializeCoreMod() { insn = next; } } - if (patched !== 2) throw new Error('Base Minerals could not wrap both Forge 25 chunk upgrades'); + if (patched !== 2) throw new Error('Base Minerals could not wrap both Forge 28 chunk upgrades'); return node; } }, @@ -149,64 +139,14 @@ function initializeCoreMod() { if (!isNbtRead(insn)) continue; var prepare = new InsnList(); prepare.add(new VarInsnNode(Opcodes.ALOAD, insn.var)); - prepare.add(call('migrateItems', '(Lnet/minecraft/nbt/INBTBase;)V')); + prepare.add(call('migrateItems', '(Lnet/minecraft/nbt/INBT;)V')); method.instructions.insert(insn, prepare); patched++; } } - if (patched === 0) throw new Error('Base Minerals could not find the Forge 25 player data reader'); + if (patched === 0) throw new Error('Base Minerals could not find the Forge 28 player data reader'); return node; } - }, - 'baseminerals_molten_mineral_renderer': { - 'target': { 'type': 'CLASS', 'name': 'net.minecraft.client.renderer.BlockFluidRenderer' }, - 'transformer': function(classNode) { - var descriptor = '(Lnet/minecraft/world/IWorldReader;Lnet/minecraft/util/math/BlockPos;' + - 'Lnet/minecraft/client/renderer/BufferBuilder;Lnet/minecraft/fluid/IFluidState;)Z'; - for (var i = 0; i < classNode.methods.size(); ++i) { - var method = classNode.methods.get(i); - if (method.desc !== descriptor) continue; - var flag = false, sprites = false, color = false; - for (var instruction = method.instructions.getFirst(); instruction !== null; - instruction = instruction.getNext()) { - if (!flag && instruction.getOpcode() === Opcodes.ISTORE && instruction.var === 5) { - var hookFlag = new InsnList(); - hookFlag.add(new VarInsnNode(Opcodes.ALOAD, 4)); - hookFlag.add(new VarInsnNode(Opcodes.ILOAD, 5)); - hookFlag.add(new MethodInsnNode(Opcodes.INVOKESTATIC, - 'zone/moddev/mc/baseminerals/client/MineralFluidRenderer', - 'useOpaqueFluidPath', '(Lnet/minecraft/fluid/IFluidState;Z)Z', false)); - hookFlag.add(new VarInsnNode(Opcodes.ISTORE, 5)); - method.instructions.insert(instruction, hookFlag); - flag = true; - } else if (!sprites && instruction.getOpcode() === Opcodes.ASTORE && instruction.var === 6) { - var hookSprites = new InsnList(); - hookSprites.add(new VarInsnNode(Opcodes.ALOAD, 4)); - hookSprites.add(new VarInsnNode(Opcodes.ALOAD, 6)); - hookSprites.add(new MethodInsnNode(Opcodes.INVOKESTATIC, - 'zone/moddev/mc/baseminerals/client/MineralFluidRenderer', - 'overrideSprites', - '(Lnet/minecraft/fluid/IFluidState;[Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;)' + - '[Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;', false)); - hookSprites.add(new VarInsnNode(Opcodes.ASTORE, 6)); - method.instructions.insert(instruction, hookSprites); - sprites = true; - } else if (!color && instruction.getOpcode() === Opcodes.ISTORE && instruction.var === 7) { - var hookColor = new InsnList(); - hookColor.add(new VarInsnNode(Opcodes.ALOAD, 4)); - hookColor.add(new VarInsnNode(Opcodes.ILOAD, 7)); - hookColor.add(new MethodInsnNode(Opcodes.INVOKESTATIC, - 'zone/moddev/mc/baseminerals/client/MineralFluidRenderer', - 'overrideColor', '(Lnet/minecraft/fluid/IFluidState;I)I', false)); - hookColor.add(new VarInsnNode(Opcodes.ISTORE, 7)); - method.instructions.insert(instruction, hookColor); - color = true; - } - } - if (!flag || !sprites || !color) throw new Error('Base Minerals could not patch the Forge 25 fluid renderer'); - } - return classNode; - } } }; } diff --git a/src/main/resources/data/basemetals/tags/blocks/crackhammer_crushable.json b/src/main/resources/data/basemetals/tags/blocks/crackhammer_crushable.json new file mode 100644 index 0000000..bce9865 --- /dev/null +++ b/src/main/resources/data/basemetals/tags/blocks/crackhammer_crushable.json @@ -0,0 +1,4 @@ +{ + "replace": false, + "values": ["#baseminerals:crackhammer_crushable"] +} diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/lithium.json b/src/main/resources/data/baseminerals/loot_tables/blocks/lithium.json new file mode 100644 index 0000000..7b59ea1 --- /dev/null +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/lithium.json @@ -0,0 +1,4 @@ +{ + "type": "minecraft:block", + "pools": [] +} diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_block.json index f58fba8..0440113 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:lithium_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_ore.json b/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_ore.json index 657a550..512a3da 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_ore.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/lithium_ore.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:lithium_ore" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/niter_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/niter_block.json index 0c7314d..808603a 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/niter_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/niter_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:niter_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/niter_ore.json b/src/main/resources/data/baseminerals/loot_tables/blocks/niter_ore.json index 4539ab1..0e8c56b 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/niter_ore.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/niter_ore.json @@ -1,12 +1,44 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", - "name": "baseminerals:niter_ore" + "type": "minecraft:alternatives", + "children": [ + { + "type": "minecraft:item", + "name": "baseminerals:niter_ore", + "conditions": [ + { + "condition": "minecraft:match_tool", + "predicate": { + "enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } + } + ] + } + } + ] + }, + { + "type": "minecraft:item", + "name": "baseminerals:niter_powder", + "functions": [ + { + "function": "baseminerals:mineral_powder_count" + }, + { + "function": "minecraft:explosion_decay" + } + ] + } + ] } ] } diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_block.json index 7cbca1b..ef7bfa1 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:phosphorus_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_ore.json b/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_ore.json index 14e4fae..0683475 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_ore.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/phosphorus_ore.json @@ -1,12 +1,44 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", - "name": "baseminerals:phosphorus_ore" + "type": "minecraft:alternatives", + "children": [ + { + "type": "minecraft:item", + "name": "baseminerals:phosphorus_ore", + "conditions": [ + { + "condition": "minecraft:match_tool", + "predicate": { + "enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } + } + ] + } + } + ] + }, + { + "type": "minecraft:item", + "name": "baseminerals:phosphorus_powder", + "functions": [ + { + "function": "baseminerals:mineral_powder_count" + }, + { + "function": "minecraft:explosion_decay" + } + ] + } + ] } ] } diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/potash_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/potash_block.json index 2b62210..77c8f61 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/potash_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/potash_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:potash_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/potash_ore.json b/src/main/resources/data/baseminerals/loot_tables/blocks/potash_ore.json index ac6bf33..2409c3e 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/potash_ore.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/potash_ore.json @@ -1,12 +1,44 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", - "name": "baseminerals:potash_ore" + "type": "minecraft:alternatives", + "children": [ + { + "type": "minecraft:item", + "name": "baseminerals:potash_ore", + "conditions": [ + { + "condition": "minecraft:match_tool", + "predicate": { + "enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } + } + ] + } + } + ] + }, + { + "type": "minecraft:item", + "name": "baseminerals:potash_powder", + "functions": [ + { + "function": "baseminerals:mineral_powder_count" + }, + { + "function": "minecraft:explosion_decay" + } + ] + } + ] } ] } diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/salt_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/salt_block.json index abd3801..3987c91 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/salt_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/salt_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:salt_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/salt_ore.json b/src/main/resources/data/baseminerals/loot_tables/blocks/salt_ore.json index ee7e74f..0aadbd0 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/salt_ore.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/salt_ore.json @@ -1,12 +1,44 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", - "name": "baseminerals:salt_ore" + "type": "minecraft:alternatives", + "children": [ + { + "type": "minecraft:item", + "name": "baseminerals:salt_ore", + "conditions": [ + { + "condition": "minecraft:match_tool", + "predicate": { + "enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } + } + ] + } + } + ] + }, + { + "type": "minecraft:item", + "name": "baseminerals:salt_powder", + "functions": [ + { + "function": "baseminerals:mineral_powder_count" + }, + { + "function": "minecraft:explosion_decay" + } + ] + } + ] } ] } diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_block.json index edeb7f0..a209ee1 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:saltpeter_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_ore.json b/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_ore.json index 539fa9a..8c012cd 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_ore.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/saltpeter_ore.json @@ -1,12 +1,44 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", - "name": "baseminerals:saltpeter_ore" + "type": "minecraft:alternatives", + "children": [ + { + "type": "minecraft:item", + "name": "baseminerals:saltpeter_ore", + "conditions": [ + { + "condition": "minecraft:match_tool", + "predicate": { + "enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } + } + ] + } + } + ] + }, + { + "type": "minecraft:item", + "name": "baseminerals:saltpeter_powder", + "functions": [ + { + "function": "baseminerals:mineral_powder_count" + }, + { + "function": "minecraft:explosion_decay" + } + ] + } + ] } ] } diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/silicon.json b/src/main/resources/data/baseminerals/loot_tables/blocks/silicon.json new file mode 100644 index 0000000..7b59ea1 --- /dev/null +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/silicon.json @@ -0,0 +1,4 @@ +{ + "type": "minecraft:block", + "pools": [] +} diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/silicon_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/silicon_block.json index ce7b5ec..5b7169f 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/silicon_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/silicon_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:silicon_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_block.json b/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_block.json index e02b919..ac94f26 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_block.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_block.json @@ -1,13 +1,18 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", + "type": "minecraft:item", "name": "baseminerals:sulfur_block" } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } ] } ] diff --git a/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_ore.json b/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_ore.json index b515934..f48d4fa 100644 --- a/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_ore.json +++ b/src/main/resources/data/baseminerals/loot_tables/blocks/sulfur_ore.json @@ -1,12 +1,44 @@ { + "type": "minecraft:block", "pools": [ { - "name": "block", "rolls": 1, "entries": [ { - "type": "item", - "name": "baseminerals:sulfur_ore" + "type": "minecraft:alternatives", + "children": [ + { + "type": "minecraft:item", + "name": "baseminerals:sulfur_ore", + "conditions": [ + { + "condition": "minecraft:match_tool", + "predicate": { + "enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } + } + ] + } + } + ] + }, + { + "type": "minecraft:item", + "name": "baseminerals:sulfur_powder", + "functions": [ + { + "function": "baseminerals:mineral_powder_count" + }, + { + "function": "minecraft:explosion_decay" + } + ] + } + ] } ] } diff --git a/src/main/resources/data/baseminerals/recipes/lithium_ore_blasting.json b/src/main/resources/data/baseminerals/recipes/lithium_ore_blasting.json new file mode 100644 index 0000000..08bb5db --- /dev/null +++ b/src/main/resources/data/baseminerals/recipes/lithium_ore_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": { + "item": "baseminerals:lithium_ore" + }, + "result": "baseminerals:lithium_ingot", + "experience": 0.45, + "cookingtime": 100 +} diff --git a/src/main/resources/data/baseminerals/recipes/lithium_powder_blasting.json b/src/main/resources/data/baseminerals/recipes/lithium_powder_blasting.json new file mode 100644 index 0000000..53b56f2 --- /dev/null +++ b/src/main/resources/data/baseminerals/recipes/lithium_powder_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": { + "item": "baseminerals:lithium_powder" + }, + "result": "baseminerals:lithium_ingot", + "experience": 0.45, + "cookingtime": 100 +} diff --git a/src/main/resources/data/baseminerals/recipes/lithium_smallpowder_blasting.json b/src/main/resources/data/baseminerals/recipes/lithium_smallpowder_blasting.json new file mode 100644 index 0000000..7a8eb5f --- /dev/null +++ b/src/main/resources/data/baseminerals/recipes/lithium_smallpowder_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": { + "item": "baseminerals:lithium_smallpowder" + }, + "result": "baseminerals:lithium_nugget", + "experience": 0.05, + "cookingtime": 100 +} diff --git a/src/main/resources/data/baseminerals/recipes/silicon_blend_blasting.json b/src/main/resources/data/baseminerals/recipes/silicon_blend_blasting.json new file mode 100644 index 0000000..4653850 --- /dev/null +++ b/src/main/resources/data/baseminerals/recipes/silicon_blend_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": { + "item": "baseminerals:silicon_blend" + }, + "result": "baseminerals:silicon_ingot", + "experience": 0.45, + "cookingtime": 100 +} diff --git a/src/main/resources/data/baseminerals/recipes/silicon_powder_blasting.json b/src/main/resources/data/baseminerals/recipes/silicon_powder_blasting.json new file mode 100644 index 0000000..0241f80 --- /dev/null +++ b/src/main/resources/data/baseminerals/recipes/silicon_powder_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": { + "item": "baseminerals:silicon_powder" + }, + "result": "baseminerals:silicon_ingot", + "experience": 0.45, + "cookingtime": 100 +} diff --git a/src/main/resources/data/baseminerals/recipes/silicon_smallblend_blasting.json b/src/main/resources/data/baseminerals/recipes/silicon_smallblend_blasting.json new file mode 100644 index 0000000..4893c67 --- /dev/null +++ b/src/main/resources/data/baseminerals/recipes/silicon_smallblend_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": { + "item": "baseminerals:silicon_smallblend" + }, + "result": "baseminerals:silicon_nugget", + "experience": 0.05, + "cookingtime": 100 +} diff --git a/src/main/resources/data/baseminerals/recipes/silicon_smallpowder_blasting.json b/src/main/resources/data/baseminerals/recipes/silicon_smallpowder_blasting.json new file mode 100644 index 0000000..542ceb6 --- /dev/null +++ b/src/main/resources/data/baseminerals/recipes/silicon_smallpowder_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": { + "item": "baseminerals:silicon_smallpowder" + }, + "result": "baseminerals:silicon_nugget", + "experience": 0.05, + "cookingtime": 100 +} diff --git a/src/main/resources/data/baseminerals/tags/blocks/crackhammer_crushable.json b/src/main/resources/data/baseminerals/tags/blocks/crackhammer_crushable.json new file mode 100644 index 0000000..bc02a1f --- /dev/null +++ b/src/main/resources/data/baseminerals/tags/blocks/crackhammer_crushable.json @@ -0,0 +1,20 @@ +{ + "replace": false, + "values": [ + "baseminerals:lithium_ore", + "baseminerals:niter_ore", + "baseminerals:phosphorus_ore", + "baseminerals:potash_ore", + "baseminerals:salt_ore", + "baseminerals:saltpeter_ore", + "baseminerals:sulfur_ore", + "baseminerals:lithium_block", + "baseminerals:niter_block", + "baseminerals:phosphorus_block", + "baseminerals:potash_block", + "baseminerals:salt_block", + "baseminerals:saltpeter_block", + "baseminerals:silicon_block", + "baseminerals:sulfur_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/ores.json b/src/main/resources/data/forge/tags/blocks/ores.json new file mode 100644 index 0000000..8bcacfb --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/ores.json @@ -0,0 +1,12 @@ +{ + "replace": false, + "values": [ + "#forge:ores/lithium", + "#forge:ores/niter", + "#forge:ores/phosphorus", + "#forge:ores/potash", + "#forge:ores/salt", + "#forge:ores/saltpeter", + "#forge:ores/sulfur" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks.json b/src/main/resources/data/forge/tags/blocks/storage_blocks.json new file mode 100644 index 0000000..f28f3ba --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks.json @@ -0,0 +1,13 @@ +{ + "replace": false, + "values": [ + "#forge:storage_blocks/lithium", + "#forge:storage_blocks/niter", + "#forge:storage_blocks/phosphorus", + "#forge:storage_blocks/potash", + "#forge:storage_blocks/salt", + "#forge:storage_blocks/saltpeter", + "#forge:storage_blocks/silicon", + "#forge:storage_blocks/sulfur" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/lithium.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/lithium.json new file mode 100644 index 0000000..f2b5ae6 --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/lithium.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:lithium_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/niter.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/niter.json new file mode 100644 index 0000000..b590901 --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/niter.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:niter_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/phosphorus.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/phosphorus.json new file mode 100644 index 0000000..e8e5be1 --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/phosphorus.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:phosphorus_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/potash.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/potash.json new file mode 100644 index 0000000..b904151 --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/potash.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:potash_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/salt.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/salt.json new file mode 100644 index 0000000..c5444fe --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/salt.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:salt_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/saltpeter.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/saltpeter.json new file mode 100644 index 0000000..73a8cc6 --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/saltpeter.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:saltpeter_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/silicon.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/silicon.json new file mode 100644 index 0000000..271b4e1 --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/silicon.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:silicon_block" + ] +} diff --git a/src/main/resources/data/forge/tags/blocks/storage_blocks/sulfur.json b/src/main/resources/data/forge/tags/blocks/storage_blocks/sulfur.json new file mode 100644 index 0000000..58f2cdd --- /dev/null +++ b/src/main/resources/data/forge/tags/blocks/storage_blocks/sulfur.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "baseminerals:sulfur_block" + ] +} diff --git a/src/main/resources/data/forge/tags/items/ores.json b/src/main/resources/data/forge/tags/items/ores.json new file mode 100644 index 0000000..8bcacfb --- /dev/null +++ b/src/main/resources/data/forge/tags/items/ores.json @@ -0,0 +1,12 @@ +{ + "replace": false, + "values": [ + "#forge:ores/lithium", + "#forge:ores/niter", + "#forge:ores/phosphorus", + "#forge:ores/potash", + "#forge:ores/salt", + "#forge:ores/saltpeter", + "#forge:ores/sulfur" + ] +} diff --git a/src/main/resources/data/forge/tags/items/storage_blocks.json b/src/main/resources/data/forge/tags/items/storage_blocks.json new file mode 100644 index 0000000..f28f3ba --- /dev/null +++ b/src/main/resources/data/forge/tags/items/storage_blocks.json @@ -0,0 +1,13 @@ +{ + "replace": false, + "values": [ + "#forge:storage_blocks/lithium", + "#forge:storage_blocks/niter", + "#forge:storage_blocks/phosphorus", + "#forge:storage_blocks/potash", + "#forge:storage_blocks/salt", + "#forge:storage_blocks/saltpeter", + "#forge:storage_blocks/silicon", + "#forge:storage_blocks/sulfur" + ] +} diff --git a/src/main/resources/data/modernmetals/tags/blocks/crackhammer_crushable.json b/src/main/resources/data/modernmetals/tags/blocks/crackhammer_crushable.json new file mode 100644 index 0000000..bce9865 --- /dev/null +++ b/src/main/resources/data/modernmetals/tags/blocks/crackhammer_crushable.json @@ -0,0 +1,4 @@ +{ + "replace": false, + "values": ["#baseminerals:crackhammer_crushable"] +} diff --git a/src/test/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgradeTest.java b/src/test/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgradeTest.java index da6a7dc..313f9ed 100644 --- a/src/test/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgradeTest.java +++ b/src/test/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgradeTest.java @@ -1,7 +1,7 @@ package zone.moddev.mc.baseminerals.migration; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.nbt.ListNBT; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -9,22 +9,22 @@ class LegacyWorldUpgradeTest { @Test void convertsNestedMineralBucketsAndKeepsTheRestOfTheStack() { - NBTTagCompound lithium = bucket("lithium"); - NBTTagCompound silicon = bucket("baseminerals:silicon"); - NBTTagList inventory = new NBTTagList(); + CompoundNBT lithium = bucket("lithium"); + CompoundNBT silicon = bucket("baseminerals:silicon"); + ListNBT inventory = new ListNBT(); inventory.add(lithium); inventory.add(silicon); - NBTTagCompound player = new NBTTagCompound(); - player.setTag("Inventory", inventory); + CompoundNBT player = new CompoundNBT(); + player.put("Inventory", inventory); LegacyWorldUpgrade.migrateItems(player); - NBTTagCompound afterFirstPass = player.copy(); + CompoundNBT afterFirstPass = player.copy(); LegacyWorldUpgrade.migrateItems(player); assertEquals(afterFirstPass, player); assertEquals("baseminerals:lithium_bucket", lithium.getString("id")); assertEquals("baseminerals:silicon_bucket", silicon.getString("id")); - for (NBTTagCompound stack : new NBTTagCompound[] {lithium, silicon}) { + for (CompoundNBT stack : new CompoundNBT[] {lithium, silicon}) { assertEquals(1, stack.getByte("Count")); assertEquals("Keep me", stack.getCompound("tag").getString("Custom")); assertFalse(stack.getCompound("tag").contains("FluidName", 8)); @@ -34,28 +34,28 @@ void convertsNestedMineralBucketsAndKeepsTheRestOfTheStack() { @Test void leavesOtherModsBucketsAndOrdinaryMineralItemsUntouched() { - NBTTagCompound copper = bucket("copper"); - NBTTagCompound original = copper.copy(); + CompoundNBT copper = bucket("copper"); + CompoundNBT original = copper.copy(); LegacyWorldUpgrade.migrateItems(copper); assertEquals(original, copper); - NBTTagCompound powder = new NBTTagCompound(); - powder.setString("id", "baseminerals:lithium_powder"); - powder.setByte("Count", (byte) 3); + CompoundNBT powder = new CompoundNBT(); + powder.putString("id", "baseminerals:lithium_powder"); + powder.putByte("Count", (byte) 3); original = powder.copy(); LegacyWorldUpgrade.migrateItems(powder); assertEquals(original, powder); } - private static NBTTagCompound bucket(String fluid) { - NBTTagCompound stack = new NBTTagCompound(); - stack.setString("id", "forge:bucketfilled"); - stack.setByte("Count", (byte) 1); - NBTTagCompound tag = new NBTTagCompound(); - tag.setString("FluidName", fluid); - tag.setInt("Amount", 1000); - tag.setString("Custom", "Keep me"); - stack.setTag("tag", tag); + private static CompoundNBT bucket(String fluid) { + CompoundNBT stack = new CompoundNBT(); + stack.putString("id", "forge:bucketfilled"); + stack.putByte("Count", (byte) 1); + CompoundNBT tag = new CompoundNBT(); + tag.putString("FluidName", fluid); + tag.putInt("Amount", 1000); + tag.putString("Custom", "Keep me"); + stack.put("tag", tag); return stack; } } diff --git a/tools/test_114_resources.js b/tools/test_114_resources.js new file mode 100644 index 0000000..0a762e2 --- /dev/null +++ b/tools/test_114_resources.js @@ -0,0 +1,57 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const fs = require('node:fs'); +const path = require('node:path'); +const root = path.join(__dirname, '../src/main/resources'); +const minerals = ['lithium', 'niter', 'phosphorus', 'potash', 'salt', 'saltpeter', 'silicon', 'sulfur']; +// The accepted 1.13 registry contract: eight stores, seven ores, powders, two metals and buckets. +const active = new Set(minerals.flatMap(m => [m + '_block', m + '_powder', m + '_smallpowder'])); +minerals.filter(m => m !== 'silicon').forEach(m => active.add(m + '_ore')); +for (const m of ['lithium', 'silicon']) for (const suffix of ['', '_ingot', '_nugget', '_bucket', '_molten']) active.add(m + suffix); +active.add('silicon_blend'); active.add('silicon_smallblend'); active.add('ore_overlay'); +function files(dir) { + return fs.readdirSync(dir, {withFileTypes: true}).flatMap(e => e.isDirectory() + ? files(path.join(dir, e.name)) : [path.join(dir, e.name)]); +} +test('source JSON parses and registered-content model textures resolve', () => { + let count = 0; + for (const file of files(root).filter(f => /\.(json|mcmeta)$/.test(f))) { + const value = JSON.parse(fs.readFileSync(file, 'utf8')); + count++; + if (!file.includes(path.join('assets', 'baseminerals', 'models'))) continue; + // The inherited tree also contains unused models for content never registered by this mod. + if (!active.has(path.basename(file, '.json'))) continue; + for (const texture of Object.values(value.textures || {})) { + if (!texture.startsWith('baseminerals:')) continue; + const png = path.join(root, 'assets/baseminerals/textures', texture.split(':')[1] + '.png'); + assert.ok(fs.existsSync(png), `${file} references missing ${texture}`); + } + } + assert.ok(count > 250); +}); + +test('canonical Forge block and item tags include every ore and storage block', () => { + function members(kind, id, seen = new Set()) { + assert.ok(!seen.has(id), `Tag cycle at ${id}`); + const next = new Set([...seen, id]); + const [namespace, name] = id.split(':'); + const tag = JSON.parse(fs.readFileSync(path.join(root, 'data', namespace, 'tags', kind, name + '.json'), 'utf8')); + assert.equal(tag.replace, false, `Tag must merge with companion mods: ${id}`); + return tag.values.flatMap(value => value.startsWith('#') ? members(kind, value.slice(1), next) : [value]); + } + for (const kind of ['blocks', 'items']) { + const ores = members(kind, 'forge:ores'); + const storage = members(kind, 'forge:storage_blocks'); + for (const mineral of minerals) { + if (mineral !== 'silicon') assert.ok(ores.includes(`baseminerals:${mineral}_ore`), `${kind}: ${mineral} missing from forge:ores`); + assert.ok(storage.includes(`baseminerals:${mineral}_block`), `${kind}: ${mineral} missing from forge:storage_blocks`); + } + } + for (const owner of ['basemetals', 'modernmetals']) { + const crushable = members('blocks', owner + ':crackhammer_crushable'); + for (const mineral of minerals) { + if (mineral !== 'silicon') assert.ok(crushable.includes(`baseminerals:${mineral}_ore`), `${owner}: ${mineral} ore is not hammer crushable`); + assert.ok(crushable.includes(`baseminerals:${mineral}_block`), `${owner}: ${mineral} storage is not hammer crushable`); + } + } +}); diff --git a/tools/validation/port114/ParseEclipseArguments.java b/tools/validation/port114/ParseEclipseArguments.java new file mode 100644 index 0000000..8fbb81f --- /dev/null +++ b/tools/validation/port114/ParseEclipseArguments.java @@ -0,0 +1,27 @@ +import java.io.File; +import java.lang.reflect.Method; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** Executes Eclipse's own Windows parser rather than approximating its quoting. */ +public final class ParseEclipseArguments { + public static void main(String[] args) throws Exception { + NodeList attributes = DocumentBuilderFactory.newInstance().newDocumentBuilder() + .parse(new File(args[0])).getElementsByTagName("stringAttribute"); + String program = null; + for (int i = 0; i < attributes.getLength(); i++) { + Element attribute = (Element) attributes.item(i); + if ("org.eclipse.jdt.launching.PROGRAM_ARGUMENTS".equals(attribute.getAttribute("key"))) + program = attribute.getAttribute("value"); + } + if (program == null) throw new IllegalArgumentException("Missing launch arguments"); + Method parse = Class.forName("org.eclipse.debug.core.DebugPlugin") + .getDeclaredMethod("parseArgumentsWindows", String.class, boolean.class); + parse.setAccessible(true); + for (String argument : (String[]) parse.invoke(null, program, false)) { + System.out.print(argument); + System.out.print('\0'); + } + } +} diff --git a/tools/validation/port114/client-probe/java/test/MineralClientProbe.java b/tools/validation/port114/client-probe/java/test/MineralClientProbe.java new file mode 100644 index 0000000..d67e4ec --- /dev/null +++ b/tools/validation/port114/client-probe/java/test/MineralClientProbe.java @@ -0,0 +1,250 @@ +package test; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screen.MainMenuScreen; +import net.minecraft.client.renderer.model.BakedQuad; +import net.minecraft.client.renderer.model.IBakedModel; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.BlockRenderLayer; +import net.minecraft.util.Direction; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.GameType; +import net.minecraft.world.WorldSettings; +import net.minecraft.world.WorldType; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.registries.ForgeRegistries; + +/** Explicit client gate. Normal launches and published jars exclude this mod. */ +@Mod("mineralclientprobe") +@Mod.EventBusSubscriber(modid = "mineralclientprobe", value = Dist.CLIENT) +public final class MineralClientProbe { + private static int stage, ticks, loaded, checks, items; + private static net.minecraft.server.MinecraftServer stopping; + private static final JsonObject heldMining = new JsonObject(); + private static final List heldCases = new ArrayList<>(); + private static int digIndex, digPhase, digTicks, attackTicks, allowedAttackTicks; + private static java.util.concurrent.CompletableFuture operation; + private static final net.minecraft.util.math.BlockPos DIG_POS = new net.minecraft.util.math.BlockPos(128, 180, 128); + + private static void check(boolean value, String message) { + checks++; + if (!value) throw new IllegalStateException(message); + } + + @SubscribeEvent + public static void tick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END || stage == 5) return; + Minecraft mc = Minecraft.getInstance(); + try { + if (mc.currentScreen instanceof net.minecraftforge.fml.client.gui.LoadingErrorScreen) + throw new IllegalStateException("Forge reported a loading error"); + if (++ticks > 3600) throw new IllegalStateException("Client timeout at stage " + stage); + if (stage == 0 && mc.currentScreen instanceof MainMenuScreen) { + validate(mc); + mc.launchIntegratedServer("mineral-smoke", "Base Minerals 1.14 check", + new WorldSettings(8675309L, GameType.SURVIVAL, false, false, WorldType.DEFAULT)); + stage = 1; ticks = 0; + } else if (stage == 1 && mc.world != null && mc.player != null && ++loaded > 80) { + if (!exerciseHeldMining(mc)) return; + stopping = mc.getIntegratedServer(); + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld(null); + mc.displayGuiScreen(new MainMenuScreen()); + stage = 2; ticks = 0; loaded = 0; + } else if (stage == 2 && mc.currentScreen instanceof MainMenuScreen && !stopping.getExecutionThread().isAlive()) { + mc.launchIntegratedServer("mineral-smoke", "Base Minerals 1.14 check", null); + stage = 3; ticks = 0; + } else if (stage == 3 && mc.world != null && mc.player != null && ++loaded > 80) { + stopping = mc.getIntegratedServer(); + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld(null); + mc.displayGuiScreen(new MainMenuScreen()); + stage = 4; ticks = 0; + } else if (stage == 4 && !stopping.getExecutionThread().isAlive()) { + write(true, null); stage = 5; mc.shutdown(); + } + } catch (Throwable error) { + error.printStackTrace(); write(false, error.toString()); stage = 5; mc.shutdown(); + } + } + + private static void validate(Minecraft mc) { + for (Item item : ForgeRegistries.ITEMS) { + if (!"baseminerals".equals(item.getRegistryName().getNamespace())) continue; + ItemStack stack = new ItemStack(item); + IBakedModel model = mc.getItemRenderer().getItemModelWithOverrides(stack, null, null); + check(model != mc.getModelManager().getMissingModel(), "Missing model " + item.getRegistryName()); + check(!stack.getDisplayName().getString().startsWith("item.baseminerals.") + && !stack.getDisplayName().getString().startsWith("block.baseminerals."), + "Missing translation " + item.getRegistryName()); + items++; + } + check(items == 41, "The saved item registry changed"); + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", "saltpeter", "sulfur"}) { + Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation("baseminerals", mineral + "_ore")); + check(block.getRenderLayer() == BlockRenderLayer.CUTOUT_MIPPED, "Ore cutout " + mineral); + oreModel(mc.getBlockRendererDispatcher().getModelForState(block.getDefaultState()), block, mineral); + oreModel(mc.getItemRenderer().getItemModelWithOverrides(new ItemStack(block), null, null), null, mineral); + } + for (String material : new String[] {"lithium", "silicon"}) { + ItemStack bucket = new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation("baseminerals", material + "_bucket"))); + IBakedModel model = mc.getItemRenderer().getItemModelWithOverrides(bucket, null, null); + List quads = new ArrayList<>(model.getQuads(null, null, new Random(1))); + for (Direction side : Direction.values()) quads.addAll(model.getQuads(null, side, new Random(1))); + check(quads.stream().anyMatch(q -> q.hasTintIndex() && q.getTintIndex() == 1), "Bucket fluid layer " + material); + for (BakedQuad quad : quads) check(!"missingno".equals(quad.getSprite().getName().getPath()), "Bucket sprite " + material); + check(mc.getItemColors().getColor(bucket, 1) == 0xC5C8C1, "Bucket colour " + material); + } + for (String texture : new String[] {"molten_metal_still", "molten_metal_flow"}) { + ResourceLocation id = new ResourceLocation("baseminerals", "block/" + texture); + check(mc.getTextureMap().getSprite(id).getName().equals(id), "Native molten atlas sprite " + texture); + } + if (net.minecraftforge.fml.ModList.get().isLoaded("basemetals")) { + int baseOres = 0; + for (Block block : ForgeRegistries.BLOCKS) { + if (!"basemetals".equals(block.getRegistryName().getNamespace()) || !block.getRegistryName().getPath().endsWith("_ore")) continue; + baseOreGap(mc.getBlockRendererDispatcher().getModelForState(block.getDefaultState()), block); + baseOreGap(mc.getItemRenderer().getItemModelWithOverrides(new ItemStack(block), null, null), null); + baseOres++; + } + check(baseOres == 13, "All Base Metals ore block/item overlay gaps"); + } + for (String owner : new String[] {"basemetals", "modernmetals"}) { + if (!net.minecraftforge.fml.ModList.get().isLoaded(owner)) continue; + String hammer = owner + ("basemetals".equals(owner) ? ":iron_crackhammer" : ":galvanizedsteel_crackhammer"); + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", "saltpeter", "sulfur"}) + heldCases.add(new String[] {hammer, "baseminerals:" + mineral + "_ore", "baseminerals:" + mineral + "_powder"}); + } + } + + private static void baseOreGap(IBakedModel model, Block block) { + for (Direction side : Direction.values()) { + List quads = model.getQuads(block == null ? null : block.getDefaultState(), side, new Random(42)); + check(quads.size() == 2, "Base ore layers on " + side); + boolean sawOverlay = false; + for (BakedQuad quad : quads) { + boolean overlay = quad.getSprite().getName().getPath().startsWith("block/ore_overlays/"); + sawOverlay |= overlay; + float low = overlay ? -0.05F / 16 : 0, high = overlay ? 16.05F / 16 : 1; + int[] data = quad.getVertexData(); int stride = data.length / 4; + for (int vertex = 0; vertex < 4; vertex++) { + float u = quad.getSprite().getUnInterpolatedU(Float.intBitsToFloat(data[vertex * stride + 4])); + float v = quad.getSprite().getUnInterpolatedV(Float.intBitsToFloat(data[vertex * stride + 5])); + check(u >= -0.01F && u <= 16.01F && v >= -0.01F && v <= 16.01F, "Base ore sprite UV bounds"); + for (int axis = 0; axis < 3; axis++) { + float coordinate = Float.intBitsToFloat(data[vertex * stride + axis]); + check(Math.min(Math.abs(coordinate - low), Math.abs(coordinate - high)) < 0.000001F, + "Base ore uses stale overlay spacing: " + quad.getSprite().getName() + "=" + coordinate); + } + } + } + check(sawOverlay, "Base ore lost overlay"); + } + } + + /** Runs the same client damage loop as a held left click, including real packets. */ + private static boolean exerciseHeldMining(Minecraft mc) { + if (digIndex >= heldCases.size()) return true; + String[] test = heldCases.get(digIndex); + if (++digTicks > 180) throw new IllegalStateException("Held mining timeout " + java.util.Arrays.toString(test) + " phase=" + digPhase); + if (digPhase == 0) { + mc.playerController.resetBlockRemoving(); + operation = mc.getIntegratedServer().runAsync(() -> { + net.minecraft.world.server.ServerWorld world = mc.getIntegratedServer().getWorld(net.minecraft.world.dimension.DimensionType.OVERWORLD); + net.minecraft.entity.player.ServerPlayerEntity player = mc.getIntegratedServer().getPlayerList().getPlayerByUUID(mc.player.getUniqueID()); + player.interactionManager.setGameType(GameType.SURVIVAL); + for (int x = -5; x <= 5; x++) for (int z = -5; z <= 5; z++) + world.setBlockState(DIG_POS.add(x, -1, z), net.minecraft.block.Blocks.STONE.getDefaultState(), 3); + player.connection.setPlayerLocation(128.5D, 180.0D, 125.5D, 0, 0); + world.getEntitiesWithinAABB(net.minecraft.entity.item.ItemEntity.class, + new net.minecraft.util.math.AxisAlignedBB(DIG_POS).grow(1.5D)).forEach(net.minecraft.entity.item.ItemEntity::remove); + player.inventory.currentItem = 0; + player.inventory.setInventorySlotContents(0, new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation(test[0])))); + player.sendContainerToPlayer(player.container); + world.setBlockState(DIG_POS, ForgeRegistries.BLOCKS.getValue(new ResourceLocation(test[1])).getDefaultState(), 3); + }); + digPhase = 1; + } else if (digPhase == 1 && operation.isDone()) { + operation.join(); mc.player.inventory.currentItem = 0; + if (!test[1].equals(mc.world.getBlockState(DIG_POS).getBlock().getRegistryName().toString()) + || !test[0].equals(mc.player.getHeldItemMainhand().getItem().getRegistryName().toString()) + || mc.player.getHeldItemMainhand().getDamage() != 0 || Math.abs(mc.player.posY - 180) > 0.1D) return false; + net.minecraft.block.BlockState state = mc.world.getBlockState(DIG_POS); + float speed = mc.player.getHeldItemMainhand().getDestroySpeed(state); + check(speed > 1.0F, "Client hammer tag did not sync " + test[0] + " -> " + test[1]); + // The native controller retains five hit-delay ticks between blocks. + allowedAttackTicks = (int) Math.ceil(state.getBlockHardness(mc.world, DIG_POS) * 30.0F / speed) + 6; + digPhase = 2; digTicks = 0; attackTicks = 0; + } else if (digPhase == 2) { + mc.playerController.onPlayerDamageBlock(DIG_POS, Direction.UP); + attackTicks++; + if (mc.world.isAirBlock(DIG_POS)) { digPhase = 3; digTicks = 0; } + check(attackTicks <= allowedAttackTicks, "Held hammer mining is too slow: " + test[0] + " -> " + test[1]); + } else if (digPhase == 3 && digTicks > 10) { + check(mc.world.isAirBlock(DIG_POS), "Mined ore reappeared on the client " + test[1]); + check(mc.player.getHeldItemMainhand().getDamage() == 1, "Client hammer durability did not sync " + test[1]); + operation = mc.getIntegratedServer().runAsync(() -> { + net.minecraft.world.server.ServerWorld world = mc.getIntegratedServer().getWorld(net.minecraft.world.dimension.DimensionType.OVERWORLD); + check(world.isAirBlock(DIG_POS), "Held mining left the ore on the server " + test[1]); + int count = 0; + for (net.minecraft.entity.item.ItemEntity drop : world.getEntitiesWithinAABB(net.minecraft.entity.item.ItemEntity.class, + new net.minecraft.util.math.AxisAlignedBB(DIG_POS).grow(1.5D))) { + check(test[2].equals(drop.getItem().getItem().getRegistryName().toString()), "Unexpected held mining drop " + test[1]); + count += drop.getItem().getCount(); + } + check(count == 2, "Held mining did not yield two powders " + test[1] + " count=" + count); + }); + digPhase = 4; + } else if (digPhase == 4 && operation.isDone()) { + operation.join(); heldMining.addProperty(test[0] + "/" + test[1], attackTicks); + digIndex++; digPhase = 0; digTicks = 0; + } + return false; + } + + private static void oreModel(IBakedModel model, Block block, String mineral) { + check(model.getParticleTexture().getName().toString().equals("minecraft:block/stone"), "Ore particle host " + mineral); + ResourceLocation overlay = new ResourceLocation("baseminerals", "blocks/ore_overlays/" + mineral + "_ore"); + for (Direction side : Direction.values()) { + List quads = model.getQuads(block == null ? null : block.getDefaultState(), side, new Random(42)); + check(quads.size() == 2, "Ore layers " + mineral + " " + side); + check(quads.stream().anyMatch(q -> q.getSprite().getName().toString().equals("minecraft:block/stone")), "Ore stone layer"); + check(quads.stream().anyMatch(q -> q.getSprite().getName().equals(overlay)), "Ore overlay layer"); + for (BakedQuad quad : quads) { + check(!"missingno".equals(quad.getSprite().getName().getPath()), "Missing ore sprite"); + if (!quad.getSprite().getName().equals(overlay)) continue; + boolean transparent = false, visible = false; + for (int y = 0; y < quad.getSprite().getHeight(); y++) for (int x = 0; x < quad.getSprite().getWidth(); x++) { + if (quad.getSprite().isPixelTransparent(0, x, y)) transparent = true; + else visible = true; + } + check(transparent && visible, "Ore overlay transparency " + mineral); + } + } + } + + private static void write(boolean passed, String failure) { + JsonObject result = new JsonObject(); + result.addProperty("passed", passed); result.addProperty("checks", checks); + result.addProperty("items", items); result.addProperty("worldReopened", passed); + result.add("held_mining_ticks", heldMining); + if (failure != null) result.addProperty("failure", failure); + try { + Files.write(Paths.get("client-probe.json"), new GsonBuilder().setPrettyPrinting().create().toJson(result).getBytes(StandardCharsets.UTF_8)); + } catch (java.io.IOException error) { throw new IllegalStateException(error); } + System.out.println("MINERAL_CLIENT_PROBE " + (passed ? "PASS" : "FAIL") + " checks=" + checks); + } +} diff --git a/tools/validation/port114/client-probe/resources/META-INF/mods.toml b/tools/validation/port114/client-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..89b81c6 --- /dev/null +++ b/tools/validation/port114/client-probe/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +loaderVersion="[28,)" +license="LGPL-2.1" +[[mods]] +modId="mineralclientprobe" +version="1" +displayName="Base Minerals client test" +[[dependencies.mineralclientprobe]] +modId="baseminerals" +mandatory=true +versionRange="[2.5.2.114041,)" +ordering="AFTER" +side="CLIENT" diff --git a/tools/validation/port114/client-probe/resources/pack.mcmeta b/tools/validation/port114/client-probe/resources/pack.mcmeta new file mode 100644 index 0000000..dc3bb0b --- /dev/null +++ b/tools/validation/port114/client-probe/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"pack_format":4,"description":"Isolated Base Minerals client test"}} diff --git a/tools/validation/port114/generation-probe/java/test/MineralGenerationProbe.java b/tools/validation/port114/generation-probe/java/test/MineralGenerationProbe.java new file mode 100644 index 0000000..fc5de3c --- /dev/null +++ b/tools/validation/port114/generation-probe/java/test/MineralGenerationProbe.java @@ -0,0 +1,115 @@ +package test; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.util.Map; +import java.util.TreeMap; +import net.minecraft.block.Block; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.dimension.DimensionType; +import net.minecraft.world.server.ServerWorld; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; +import net.minecraftforge.registries.ForgeRegistries; + +/** Disposable full-height census; contains no placement implementation. */ +@Mod("mineralgenerationprobe") +public final class MineralGenerationProbe { + private static final String[] ORES = {"lithium", "niter", "salt", "sulfur", "phosphorus", "potash", "saltpeter"}; + private static final int[][] HEIGHTS = {{8,47}, {16,63}, {24,79}, {4,31}, {16,63}, {8,47}, {24,79}}; + public MineralGenerationProbe() { MinecraftForge.EVENT_BUS.addListener(this::started); } + + private void started(FMLServerStartedEvent event) { + JsonObject report = new JsonObject(); + long start = System.nanoTime(); + try { + report.addProperty("seed", event.getServer().getWorld(DimensionType.OVERWORLD).getSeed()); + report.addProperty("interior_chunks_per_dimension", 256); + report.addProperty("margin_chunks", 2); + report.addProperty("min_y", 0); report.addProperty("max_y", 255); + JsonObject dimensions = new JsonObject(); + for (DimensionType type : new DimensionType[] {DimensionType.OVERWORLD, DimensionType.THE_NETHER, DimensionType.THE_END}) { + ServerWorld world = event.getServer().getWorld(type); + long begin = System.nanoTime(); + for (int x = 62; x < 82; x++) for (int z = 62; z < 82; z++) world.getChunk(x, z); + JsonObject before = census(world, type == DimensionType.OVERWORLD); + // Generate later chunks beyond the populated margin, then census the old interior again. + for (int z = 62; z < 82; z++) world.getChunk(82, z); + JsonObject after = census(world, type == DimensionType.OVERWORLD); + if (!before.equals(after)) throw new AssertionError("Later generation changed existing ores in " + type); + before.addProperty("populate_and_census_seconds", (System.nanoTime() - begin) / 1e9); + dimensions.add(DimensionType.getKey(type).toString(), before); + System.out.println("MINERAL_GENERATION_DIMENSION " + type + " " + before); + } + report.add("dimensions", dimensions); + report.addProperty("passed", true); + } catch (Throwable failure) { + report.addProperty("passed", false); + report.addProperty("failure", failure.toString()); + failure.printStackTrace(); + } finally { + report.addProperty("seconds", (System.nanoTime() - start) / 1e9); + try { + Files.write(Paths.get("generation-results.json"), new GsonBuilder().setPrettyPrinting().create() + .toJson(report).getBytes(StandardCharsets.UTF_8)); + } catch (java.io.IOException error) { throw new IllegalStateException(error); } + System.out.println("MINERAL_GENERATION_PROBE " + (report.get("passed").getAsBoolean() ? "PASS" : "FAIL")); + event.getServer().initiateShutdown(false); + } + } + + private static JsonObject census(ServerWorld world, boolean overworld) throws Exception { + Map indices = new java.util.IdentityHashMap<>(); + int[][] histogram = new int[7][256]; + for (int i = 0; i < ORES.length; i++) indices.put(ForgeRegistries.BLOCKS.getValue( + new ResourceLocation("baseminerals", ORES[i] + "_ore")), i); + TreeMap coordinates = new TreeMap<>(); + BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); + for (int cx = 64; cx < 80; cx++) for (int cz = 64; cz < 80; cz++) { + Chunk chunk = world.getChunk(cx, cz); + for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) for (int y = 0; y < 256; y++) { + pos.setPos(cx * 16 + x, y, cz * 16 + z); + Block block = chunk.getBlockState(pos).getBlock(); + Integer index = indices.get(block); + if (index == null) { + if ("baseminerals".equals(block.getRegistryName().getNamespace())) + throw new AssertionError("Undeclared generated mineral block " + block.getRegistryName()); + continue; + } + if (!overworld || y < HEIGHTS[index][0] || y > HEIGHTS[index][1]) + throw new AssertionError("Unexpected ore " + ORES[index] + " at " + pos + " in " + world.getDimension().getType()); + histogram[index][y]++; + coordinates.put(pos.getX() + "," + y + "," + pos.getZ(), ORES[index]); + } + } + JsonObject result = new JsonObject(), counts = new JsonObject(), hist = new JsonObject(); + for (int i = 0; i < ORES.length; i++) { + int count = java.util.Arrays.stream(histogram[i]).sum(); + String disabled = System.getProperty("mineralprobe.disabled", ""); + boolean expectDisabled = "all".equals(disabled) || java.util.Arrays.asList(disabled.split(",")).contains(ORES[i]); + if (overworld && (expectDisabled ? count != 0 : count == 0)) + throw new AssertionError("Unexpected count " + count + " for " + ORES[i] + "; disabled=" + expectDisabled); + counts.addProperty(ORES[i], count); + JsonObject heights = new JsonObject(); + for (int y = 0; y < 256; y++) if (histogram[i][y] != 0) heights.addProperty(String.valueOf(y), histogram[i][y]); + hist.add(ORES[i], heights); + } + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (Map.Entry entry : coordinates.entrySet()) + digest.update((entry.getKey() + "=" + entry.getValue() + "\n").getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(); + for (byte b : digest.digest()) hex.append(String.format("%02x", b & 255)); + result.add("counts", counts); result.add("height_histograms", hist); + result.addProperty("sorted_coordinate_sha256", hex.toString()); + result.addProperty("unchanged_after_later_chunks", true); + return result; + } +} diff --git a/tools/validation/port114/generation-probe/resources/META-INF/mods.toml b/tools/validation/port114/generation-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..8483d59 --- /dev/null +++ b/tools/validation/port114/generation-probe/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +loaderVersion="[28,)" +license="LGPL-3.0" +[[mods]] +modId="mineralgenerationprobe" +version="1" +displayName="Base Minerals disposable generation census" +[[dependencies.mineralgenerationprobe]] +modId="baseminerals" +mandatory=true +versionRange="[2.5.2.114041,)" +ordering="AFTER" +side="SERVER" diff --git a/tools/validation/port114/generation-probe/resources/pack.mcmeta b/tools/validation/port114/generation-probe/resources/pack.mcmeta new file mode 100644 index 0000000..8209eb1 --- /dev/null +++ b/tools/validation/port114/generation-probe/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"pack_format":4,"description":"Disposable generation probe"}} diff --git a/tools/validation/port114/mining-probe/java/test/MineralMiningProbe.java b/tools/validation/port114/mining-probe/java/test/MineralMiningProbe.java new file mode 100644 index 0000000..a403279 --- /dev/null +++ b/tools/validation/port114/mining-probe/java/test/MineralMiningProbe.java @@ -0,0 +1,370 @@ +package test; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.entity.item.ItemEntity; +import net.minecraft.entity.merchant.villager.VillagerEntity; +import net.minecraft.enchantment.Enchantments; +import net.minecraft.item.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.FurnaceRecipe; +import net.minecraft.item.crafting.AbstractCookingRecipe; +import net.minecraft.item.crafting.IRecipeType; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.inventory.Inventory; +import net.minecraft.network.PacketDirection; +import net.minecraft.network.play.ServerPlayNetHandler; +import net.minecraft.network.NetworkManager; +import net.minecraft.util.Hand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.StringTextComponent; +import net.minecraft.world.GameType; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.dimension.DimensionType; +import net.minecraft.item.MerchantOffer; +import net.minecraft.item.MerchantOffers; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.FakePlayer; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; +import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.entity.merchant.villager.VillagerProfession; +import net.minecraft.entity.merchant.villager.VillagerTrades; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.server.management.PlayerInteractionManager; +import net.minecraft.world.storage.loot.*; +import net.minecraft.world.storage.loot.conditions.ILootCondition; +import zone.moddev.mc.baseminerals.loot.MineralPowderCount; + +/** Exercises the installed jar through real survival harvesting. */ +@Mod("mineralminingprobe") +public final class MineralMiningProbe { + private static final String[] MINERALS = { + "lithium", "niter", "phosphorus", "potash", "salt", "saltpeter", "sulfur" + }; + private final List failures = new ArrayList<>(); + private final JsonObject drops = new JsonObject(); + private final JsonObject miningProgress = new JsonObject(); + private ServerWorld world; + private ServerPlayerEntity player; + private int checks; + private int harvestIndex; + + public MineralMiningProbe() { MinecraftForge.EVENT_BUS.addListener(this::started); } + + private void started(FMLServerStartedEvent event) { + world = event.getServer().getWorld(DimensionType.OVERWORLD); + player = new ServerPlayerEntity(event.getServer(), world, new GameProfile(UUID.randomUUID(), "MineralMiningProbe"), new PlayerInteractionManager(world)); + player.connection = new ServerPlayNetHandler(event.getServer(), new NetworkManager(PacketDirection.SERVERBOUND), player); + player.interactionManager.setGameType(GameType.SURVIVAL); + player.onGround = true; + try { + for (String mineral : MINERALS) { + Block ore = block(mineral + "_ore"); + boolean lithium = "lithium".equals(mineral); + for (int fortune = 0; fortune <= 3; fortune++) { + ItemStack pickaxe = new ItemStack(Items.DIAMOND_PICKAXE); + if (fortune > 0) pickaxe.addEnchantment(Enchantments.FORTUNE, fortune); + int count = harvest(ore, pickaxe, item(mineral + (lithium ? "_ore" : "_powder"))); + check(lithium ? count == 1 : count >= 2 && count <= 4 + fortune, + mineral + " Fortune " + fortune + " yielded " + count); + drops.addProperty(mineral + ":fortune" + fortune, count); + BlockState state = ore.getDefaultState(); + for (int sample = 0; sample < 256; sample++) { + Random random = new Random(sample); + int expected = lithium ? 1 : 2 + new Random(sample).nextInt(3 + fortune); + LootContext.Builder context = new LootContext.Builder(world).withRandom(random) + .withParameter(LootParameters.POSITION, BlockPos.ZERO) + .withParameter(LootParameters.BLOCK_STATE, state).withParameter(LootParameters.TOOL, pickaxe); + int actual = lithium ? 1 : new MineralPowderCount.Serializer() + .deserialize(new JsonObject(), null, new ILootCondition[0]) + .apply(new ItemStack(item(mineral + "_powder")), context.build(LootParameterSets.BLOCK)).getCount(); + check(actual == expected, mineral + " changed the uniform Fortune formula at " + fortune); + List loot = ore.getDrops(state, new LootContext.Builder(world).withRandom(new Random(sample)) + .withParameter(LootParameters.POSITION, BlockPos.ZERO).withParameter(LootParameters.TOOL, pickaxe)); + check(loot.size() == 1 && loot.get(0).getItem() == item(mineral + (lithium ? "_ore" : "_powder")) + && (lithium ? loot.get(0).getCount() == 1 : loot.get(0).getCount() >= 2 && loot.get(0).getCount() <= 4 + fortune), + mineral + " native loot changed at Fortune " + fortune); + } + } + ItemStack silk = new ItemStack(Items.DIAMOND_PICKAXE); + silk.addEnchantment(Enchantments.SILK_TOUCH, 1); + check(harvest(ore, silk, item(mineral + "_ore")) == 1, + mineral + " Silk Touch did not return one ore"); + check(harvest(ore, new ItemStack(Items.WOODEN_PICKAXE), null) == 0, + mineral + " dropped with an inadequate pickaxe"); + if (lithium) { + check(harvest(ore, new ItemStack(Items.STONE_PICKAXE), null) == 0, + "Lithium requires an iron-level pickaxe"); + } + check(ore.getExpDrop(ore.getDefaultState(), world, BlockPos.ZERO, 3, 0) == 0, + mineral + " added mining XP"); + blockProperties(ore, 5.0F, lithium ? 3.0F : 0.75F, lithium ? 2 : 1, false); + } + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", + "saltpeter", "silicon", "sulfur"}) { + Block storage = block(mineral + "_block"); + check(harvest(storage, new ItemStack(Items.DIAMOND_PICKAXE), item(mineral + "_block")) == 1, + mineral + " storage-block drop changed"); + boolean metal = "lithium".equals(mineral) || "silicon".equals(mineral); + blockProperties(storage, metal ? 16.0F : 10.0F, metal ? 4.0F : 1.0F, metal ? 2 : 1, true); + } + if (Boolean.getBoolean("mineralprobe.processing")) { + processingRecipes(); + smithOffers(); + for (String material : new String[] {"lithium", "silicon"}) { + check(block(material).getDefaultState().getLightValue() == 10, material + " lost molten-fluid light"); + moltenLifecycle(material); + } + } + for (String owner : new String[] {"basemetals", "modernmetals"}) { + if (!ModList.get().isLoaded(owner)) continue; + ResourceLocation hammerId = new ResourceLocation(owner, + "basemetals".equals(owner) ? "iron_crackhammer" : "galvanizedsteel_crackhammer"); + check(ForgeRegistries.ITEMS.containsKey(hammerId), "Missing test hammer " + hammerId); + for (String mineral : MINERALS) { + ItemStack hammer = new ItemStack(ForgeRegistries.ITEMS.getValue(hammerId)); + int count = dig(block(mineral + "_ore"), hammer, item(mineral + "_powder")); + check(count == 2 && hammer.getDamage() == 1, + owner + " hammer yielded " + count + " " + mineral + " powders, damage " + hammer.getDamage()); + } + if (Boolean.getBoolean("mineralprobe.processing")) { + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", + "saltpeter", "silicon", "sulfur"}) { + ItemStack hammer = new ItemStack(ForgeRegistries.ITEMS.getValue(hammerId)); + check(dig(block(mineral + "_block"), hammer, item(mineral + "_powder")) == 9, + owner + " hammer did not crush " + mineral + " storage block to nine powders"); + check(hammer.getDamage() == 1, owner + " storage-block crushing did not damage hammer"); + } + } + } + } catch (Throwable error) { + failures.add(error.toString()); + error.printStackTrace(); + } finally { + JsonObject report = new JsonObject(); + report.addProperty("passed", failures.isEmpty()); + report.add("mining_progress", miningProgress); + report.addProperty("checks", checks); + report.add("drops", drops); + report.add("failures", new com.google.gson.Gson().toJsonTree(failures)); + try { + Files.write(Paths.get("mining-results.json"), + new GsonBuilder().setPrettyPrinting().create().toJson(report).getBytes(StandardCharsets.UTF_8)); + } catch (java.io.IOException error) { + throw new IllegalStateException(error); + } finally { + System.out.println("MINERAL_MINING_PROBE " + (failures.isEmpty() ? "PASS" : "FAIL") + " checks=" + checks); + event.getServer().initiateShutdown(false); + } + } + } + + private void blockProperties(Block block, float hardness, float resistance, int harvestLevel, boolean beacon) { + BlockState state = block.getDefaultState(); + check(state.getBlockHardness(world, BlockPos.ZERO) == hardness, + block.getRegistryName() + " changed mining hardness"); + check(block.getExplosionResistance() == resistance, block.getRegistryName() + " changed blast resistance"); + check(state.getHarvestLevel() == harvestLevel, block.getRegistryName() + " changed harvest tier"); + check(block.isBeaconBase(state, world, BlockPos.ZERO, BlockPos.ZERO) == beacon, + block.getRegistryName() + " changed beacon support"); + } + + private void processingRecipes() { + for (String material : new String[] {"lithium", "silicon"}) { + furnace(material + "_powder", material + "_ingot", 0.45F); + furnace(material + "_smallpowder", material + "_nugget", 0.05F); + } + furnace("lithium_ore", "lithium_ingot", 0.45F); + furnace("silicon_blend", "silicon_ingot", 0.45F); + furnace("silicon_smallblend", "silicon_nugget", 0.05F); + boolean crushingLoaded = ModList.get().isLoaded("basemetals") || ModList.get().isLoaded("modernmetals"); + for (String material : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", + "saltpeter", "silicon", "sulfur"}) { + crusher(material + "_block", material + "_powder", 9, crushingLoaded); + } + for (String material : new String[] {"lithium", "silicon"}) { + crusher(material + "_ingot", material + "_powder", 1, crushingLoaded); + crusher(material + "_nugget", material + "_smallpowder", 1, crushingLoaded); + } + } + + private void smithOffers() { + for (VillagerProfession profession : new VillagerProfession[] {VillagerProfession.ARMORER, + VillagerProfession.TOOLSMITH, VillagerProfession.WEAPONSMITH}) { + for (int seed = 0; seed < 32; seed++) { + MerchantOffers offers = new MerchantOffers(); + for (VillagerTrades.ITrade trade : VillagerTrades.field_221239_a.get(profession).get(2)) { + if (trade.getClass().getName().startsWith("zone.moddev.mc.baseminerals.trade.")) + offers.add(trade.getOffer(null, new Random(seed))); + } + for (String material : new String[] {"lithium", "silicon"}) { + int matches = 0; + for (MerchantOffer offer : offers) { + if (offer.func_222206_f().getItem() != item(material + "_ingot")) continue; + matches++; + check(offer.func_222206_f().getCount() == 1 && offer.func_222218_a().getItem() == Items.EMERALD + && offer.func_222218_a().getCount() >= 4 && offer.func_222218_a().getCount() <= 5 + && offer.func_222214_i() == 12 && offer.func_222210_n() == 5, + material + " smith offer, restocking or experience changed"); + } + check(matches == 1, profession + " has " + matches + " " + material + " offers"); + } + } + } + } + + private void furnace(String input, String output, float xp) { + cooking(input, output, xp, IRecipeType.SMELTING, 200); + cooking(input, output, xp, IRecipeType.BLASTING, 100); + } + + private void cooking(String input, String output, float xp, IRecipeType type, int ticks) { + Inventory inventory = new Inventory(1); + inventory.setInventorySlotContents(0, new ItemStack(item(input))); + List matches = new ArrayList<>(); + for (IRecipe recipe : world.getRecipeManager().getRecipes()) { + if (recipe.getType() == type && recipe.matches(inventory, world)) matches.add(recipe); + } + check(matches.size() == 1, input + " has " + matches.size() + " furnace recipes"); + for (IRecipe recipe : matches) { + ItemStack result = recipe.getRecipeOutput(); + check(result.getItem() == item(output) && result.getCount() == 1, input + " smelts to " + result); + check(((AbstractCookingRecipe) recipe).getExperience() == xp, input + " changed cooking XP"); + check(((AbstractCookingRecipe) recipe).getCookTime() == ticks, input + " changed cooking time"); + } + } + + private void crusher(String input, String output, int count, boolean enabled) { + Inventory inventory = new Inventory(1); + inventory.setInventorySlotContents(0, new ItemStack(item(input))); + List matches = new ArrayList<>(); + for (IRecipe recipe : world.getRecipeManager().getRecipes()) { + if ("crushing".equals(recipe.getSerializer().getRegistryName().getPath()) && recipe.matches(inventory, world)) { + matches.add(recipe); + } + } + check(matches.size() == (enabled ? 1 : 0), input + " has " + matches.size() + " crushing recipes"); + for (IRecipe recipe : matches) { + check(recipe.getRecipeOutput().getItem() == item(output) && recipe.getRecipeOutput().getCount() == count, + input + " crushes to " + recipe.getRecipeOutput()); + } + } + + private void moltenLifecycle(String material) { + net.minecraft.item.BucketItem bucket = (net.minecraft.item.BucketItem) item(material + "_bucket"); + net.minecraft.fluid.Fluid fluid = bucket.getFluid(); + net.minecraftforge.fluids.FluidAttributes attributes = fluid.getAttributes(); + check(fluid.getRegistryName().equals(new ResourceLocation("baseminerals", material)), "Source fluid identity " + material); + check(attributes.getColor() == 0xFFC5C8C1 && attributes.getLuminosity() == 10 + && attributes.getDensity() == 2000 && attributes.getViscosity() == 10000 + && attributes.getTemperature() == 330, "Molten attributes " + material); + check(!fluid.isIn(net.minecraft.tags.FluidTags.LAVA), "Molten fluid became vanilla lava " + material); + BlockPos pos = new BlockPos(128, 240, "lithium".equals(material) ? 144 : 160); + for (int x = -5; x <= 5; x++) for (int z = -5; z <= 5; z++) { + world.setBlockState(pos.add(x, -1, z), net.minecraft.block.Blocks.STONE.getDefaultState(), 2); + world.setBlockState(pos.add(x, 0, z), net.minecraft.block.Blocks.AIR.getDefaultState(), 2); + } + check(bucket.tryPlaceContainedLiquid(player, world, pos, null), "Native bucket placement " + material); + check(world.getBlockState(pos).getBlock() == block(material) && world.getFluidState(pos).isSource(), + "Bucket placed the wrong source " + material); + world.getFluidState(pos).tick(world, pos); + boolean flowed = false; + for (net.minecraft.util.Direction side : net.minecraft.util.Direction.Plane.HORIZONTAL) { + net.minecraft.fluid.IFluidState adjacent = world.getFluidState(pos.offset(side)); + if (fluid.isEquivalentTo(adjacent.getFluid()) && !adjacent.isSource()) flowed = true; + } + check(flowed, "Molten source did not flow " + material); + // A newly constructed ServerPlayerEntity has 60 ticks of native spawn + // damage immunity. Use an ordinary creature to exercise actual contact. + net.minecraft.entity.passive.PigEntity creature = net.minecraft.entity.EntityType.PIG.create(world); + creature.setPosition(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5); + float health = creature.getHealth(); + block(material).onEntityCollision(world.getBlockState(pos), world, pos, creature); + check(creature.getHealth() == health && !creature.isBurning(), "Molten heat escaped its surface " + material); + creature.setPosition(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5); + block(material).onEntityCollision(world.getBlockState(pos), world, pos, creature); + check(creature.getHealth() == health - 4.0F && creature.isBurning(), + "Molten contact lost heat " + material + " health=" + creature.getHealth() + " burning=" + creature.isBurning()); + creature.remove(); + net.minecraft.fluid.Fluid picked = ((net.minecraft.block.IBucketPickupHandler) block(material)) + .pickupFluid(world, pos, world.getBlockState(pos)); + check(picked == fluid && world.isAirBlock(pos) && picked.getFilledBucket() == bucket, + "Native pickup lost fluid or bucket identity " + material); + } + + private int harvest(Block block, ItemStack tool, Item expected) { + return harvest(block, tool, expected, false); + } + + private int dig(Block block, ItemStack tool, Item expected) { + return harvest(block, tool, expected, true); + } + + private int harvest(Block block, ItemStack tool, Item expected, boolean normalDigging) { + int index = harvestIndex++; + BlockPos pos = new BlockPos(128 + (index % 16) * 3, 180 + (index / 16) * 4, 128); + AxisAlignedBB area = new AxisAlignedBB(pos).grow(0.45); + world.getEntitiesWithinAABB(ItemEntity.class, area).forEach(ItemEntity::remove); + world.setBlockState(pos, block.getDefaultState(), 3); + player.setHeldItem(Hand.MAIN_HAND, tool); + if (normalDigging) { + player.setPosition(pos.getX() + 0.5D, pos.getY(), pos.getZ() + 2.5D); + player.onGround = true; + BlockState state = world.getBlockState(pos); + float speed = tool.getDestroySpeed(state); + check(speed > 1.0F, "Hammer uses untagged mining speed for " + block.getRegistryName()); + float progress = state.getPlayerRelativeBlockHardness(player, world, pos); + int ticks = progress > 0 ? (int) Math.ceil(1.0F / progress) : 400; + int expectedTicks = (int) Math.ceil(state.getBlockHardness(world, pos) * 30.0F / speed); + check(state.canHarvestBlock(world, pos, player) && ticks <= expectedTicks + 1, + "Hammer progress differs from its native speed for " + block.getRegistryName() + ": " + ticks + " vs " + expectedTicks); + JsonObject timing = new JsonObject(); + timing.addProperty("speed", speed); timing.addProperty("ticks", ticks); + timing.addProperty("progress_per_tick", progress); + miningProgress.add(tool.getItem().getRegistryName() + "/" + block.getRegistryName(), timing); + player.interactionManager.func_225416_a(pos, net.minecraft.network.play.client.CPlayerDiggingPacket.Action.START_DESTROY_BLOCK, + net.minecraft.util.Direction.UP, 256); + for (int tick = 0; tick <= Math.min(ticks, 400); tick++) player.interactionManager.tick(); + player.interactionManager.func_225416_a(pos, net.minecraft.network.play.client.CPlayerDiggingPacket.Action.STOP_DESTROY_BLOCK, + net.minecraft.util.Direction.UP, 256); + check(world.isAirBlock(pos), "Normal digging did not remove " + block.getRegistryName()); + } else player.interactionManager.tryHarvestBlock(pos); + int count = 0; + for (ItemEntity drop : world.getEntitiesWithinAABB(ItemEntity.class, area)) { + check(drop.getItem().getItem() == expected, + block.getRegistryName() + " dropped " + drop.getItem().getItem().getRegistryName()); + count += drop.getItem().getCount(); + drop.remove(); + } + world.removeBlock(pos, false); + return count; + } + + private static Block block(String name) { + return ForgeRegistries.BLOCKS.getValue(new ResourceLocation("baseminerals", name)); + } + + private static Item item(String name) { + return ForgeRegistries.ITEMS.getValue(new ResourceLocation("baseminerals", name)); + } + + private void check(boolean condition, String detail) { + checks++; + if (!condition) failures.add(detail); + } +} diff --git a/tools/validation/port114/mining-probe/resources/META-INF/mods.toml b/tools/validation/port114/mining-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..e723cc5 --- /dev/null +++ b/tools/validation/port114/mining-probe/resources/META-INF/mods.toml @@ -0,0 +1,12 @@ +modLoader="javafml" +loaderVersion="[25,)" +[[mods]] +modId="mineralminingprobe" +version="1" +displayName="Base Minerals mining checks" +[[dependencies.mineralminingprobe]] +modId="baseminerals" +mandatory=true +versionRange="[2.5.1.114041,)" +ordering="AFTER" +side="BOTH" diff --git a/tools/validation/port114/mining-probe/resources/pack.mcmeta b/tools/validation/port114/mining-probe/resources/pack.mcmeta new file mode 100644 index 0000000..d583eef --- /dev/null +++ b/tools/validation/port114/mining-probe/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"pack_format":4,"description":"Base Minerals mining test fixture"}} diff --git a/tools/validation/port114/requirements.txt b/tools/validation/port114/requirements.txt new file mode 100644 index 0000000..96972e7 --- /dev/null +++ b/tools/validation/port114/requirements.txt @@ -0,0 +1 @@ +nbtlib==2.0.4 diff --git a/tools/validation/port114/run_forge.py b/tools/validation/port114/run_forge.py new file mode 100644 index 0000000..42e0265 --- /dev/null +++ b/tools/validation/port114/run_forge.py @@ -0,0 +1,125 @@ +"""Start a packaged Forge world in a disposable directory and save it after boot.""" +import argparse +import json +import hashlib +from pathlib import Path +import queue +import shutil +import subprocess +import threading +import time + +LAUNCHER = 'forge-1.14.4-28.2.26.jar' + + +def prepare(runtime, target, mods, source=None): + if source and target.resolve().is_relative_to(source.resolve()): + raise ValueError('Disposable output must be outside the source world') + target.mkdir(parents=True) + launcher = runtime.resolve() / LAUNCHER + assert launcher.is_file() and (runtime / 'libraries').is_dir(), 'Incomplete official Forge runtime' + (target / 'forge-runtime.json').write_text(json.dumps(dict(launcher=str(launcher), + sha256=hashlib.sha256(launcher.read_bytes()).hexdigest()), indent=2)) + (target / 'mods').mkdir() + for mod in mods: + shutil.copy2(mod, target / 'mods' / mod.name) + if source: + shutil.copytree(source, target / 'world') + (target / 'eula.txt').write_text('eula=true\n') + (target / 'server.properties').write_text( + 'level-name=world\nlevel-seed=8675309\nonline-mode=false\nserver-ip=127.0.0.1\n' + 'server-port=0\nview-distance=3\nmax-tick-time=0\n' + ) + + +def run(java, target, phase, upgrade=False): + command = [str(java), '-Xms256M', '-Xmx2G'] + if upgrade: + command.append('-Dbaseminerals.debugUpgrade=true') + command.extend(['-jar', json.loads((target / 'forge-runtime.json').read_text())['launcher'], 'nogui']) + if upgrade: + command.append('--forceUpgrade') + log = target / (phase + '-console.log') + messages = queue.Queue() + with log.open('w', encoding='utf-8') as stream: + process = subprocess.Popen(command, cwd=target, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, encoding='utf-8', errors='replace') + + def collect(): + for line in process.stdout: + stream.write(line) + stream.flush() + messages.put(line) + messages.put(None) + + thread = threading.Thread(target=collect, daemon=True) + thread.start() + deadline = time.monotonic() + 480 + started = False + query_lines = [] + try: + while time.monotonic() < deadline: + try: + line = messages.get(timeout=1) + except queue.Empty: + continue + if line is None: + break + query_lines.append(line.strip()) + if 'Run the command /fml confirm' in line: + prompt = '\n'.join(query_lines[-24:]) + # Only the retired vanilla registry and the six vanilla + # sign/dye renames are expected across Forge 25 -> 28. + # Never blanket-confirm unknown mod content. + names = sorted(s for s in query_lines[-24:] if s.startswith('minecraft:') and ' ' not in s) + registry = ('There are 1 missing registries in this save.' in prompt + and names == ['minecraft:villagerprofessions']) + renames = ('There are 6 missing entries in this save.' in prompt and names == sorted([ + 'minecraft:sign', 'minecraft:wall_sign', 'minecraft:sign', 'minecraft:rose_red', + 'minecraft:cactus_green', 'minecraft:dandelion_yellow'])) + assert registry or renames, prompt + process.stdin.write('fml confirm\n') + process.stdin.flush() + receipt = target / (phase + '-registry-confirmation.json') + confirmations = json.loads(receipt.read_text()) if receipt.exists() else [] + confirmations.append(dict(prompt=prompt, confirmed=names)) + receipt.write_text(json.dumps(confirmations, indent=2)) + if 'Done (' in line and 'For help, type' in line: + started = True + process.stdin.write('stop\n') + process.stdin.flush() + break + if 'Encountered an unexpected exception' in line: + break + if not started: + raise RuntimeError(f'Forge never reached a playable world. See {log}') + if process.wait(timeout=120): + raise RuntimeError(f'Forge shutdown failed. See {log}') + finally: + if process.poll() is None: + process.kill() + process.wait() + thread.join(timeout=10) + text = log.read_text(encoding='utf-8') + failures = ('Encountered an unexpected exception', 'Error occurred applying transform of coremod', + "Couldn't read loot table baseminerals:", "Couldn't parse loot table baseminerals:", 'Parsing error loading recipe baseminerals:') + if any(failure in text for failure in failures): + raise RuntimeError(f'Forge reported a migration or resource error. See {log}') + print(f'{target.name} {phase} PASS', flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('java', 'runtime', 'output'): + parser.add_argument('--' + name, required=True, type=Path) + parser.add_argument('--mods', required=True, type=Path, nargs='+') + parser.add_argument('--source', type=Path) + parser.add_argument('--force-upgrade', action='store_true') + args = parser.parse_args() + prepare(args.runtime, args.output, args.mods, args.source) + run(args.java, args.output, 'first', args.force_upgrade) + run(args.java, args.output, 'reload', args.force_upgrade) + + +if __name__ == '__main__': + main() diff --git a/tools/validation/port114/verify_census.py b/tools/validation/port114/verify_census.py new file mode 100644 index 0000000..82886cb --- /dev/null +++ b/tools/validation/port114/verify_census.py @@ -0,0 +1,74 @@ +"""Run the full-height generation probe, then compare a saved-world reload.""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +from run_forge import prepare + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('java', 'runtime', 'output', 'probe'): + parser.add_argument('--' + name, required=True, type=Path) + parser.add_argument('--mods', required=True, nargs='+', type=Path) + parser.add_argument('--seed', required=True, type=int) + parser.add_argument('--compare', type=Path, help='Independent same-seed generation report') + parser.add_argument('--provider-override', type=Path) + parser.add_argument('--world-profile', type=Path) + parser.add_argument('--disabled', default='', help='Expected disabled minerals, comma-separated, or all') + args = parser.parse_args() + jars = [*args.mods, args.probe] + prepare(args.runtime, args.output, jars) + (args.output / 'input-jars.json').write_text(json.dumps({ + p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in jars}, indent=2)) + properties = args.output / 'server.properties' + properties.write_text(properties.read_text().replace('level-seed=8675309', 'level-seed=' + str(args.seed))) + for source, relative in ((args.provider_override, 'config/baseminerals-orespawn.json'), + (args.world_profile, 'world/serverconfig/orespawn-worldgen.json')): + if source: + destination = args.output / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + if args.seed == 0: + # DedicatedServer replaces a textual zero with a random seed. An empty, + # explicitly seeded save exercises actual seed zero without editing chunks. + from nbtlib import File, Compound, String, Long, Int, Byte + world = args.output / 'world' + world.mkdir(exist_ok=True) + initial = File({'Data': Compound({'RandomSeed': Long(0), 'LevelName': String('world'), + 'DataVersion': Int(1976), 'version': Int(19133), 'GameType': Int(0), + 'generatorName': String('default'), 'generatorVersion': Int(1), 'MapFeatures': Byte(1), + 'initialized': Byte(0), 'allowCommands': Byte(1), + 'Version': Compound({'Id': Int(1976), 'Name': String('1.14.4'), 'Snapshot': Byte(0)})})}) + initial.save(world / 'level.dat', gzipped=True) + (args.output / 'seed-zero-fixture.json').write_text(json.dumps(dict( + description='Empty native save; explicit RandomSeed=0; no pre-generated chunks', + sha256=hashlib.sha256((world / 'level.dat').read_bytes()).hexdigest()), indent=2)) + reports = [] + for phase in ('fresh', 'reload'): + with (args.output / (phase + '-console.log')).open('wb') as stream: + result = subprocess.run([str(args.java), '-Xmx3G', '-Dmineralprobe.disabled=' + args.disabled, '-jar', + json.loads((args.output / 'forge-runtime.json').read_text())['launcher'], 'nogui'], + cwd=args.output, stdout=stream, stderr=subprocess.STDOUT, timeout=900) + report = json.loads((args.output / 'generation-results.json').read_text()) + shutil.copy2(args.output / 'generation-results.json', args.output / (phase + '-results.json')) + assert result.returncode == 0 and report['passed'] and report['seed'] == args.seed, report + text = (args.output / (phase + '-console.log')).read_text(errors='replace') + unexpected = [line for line in text.splitlines() if ('/ERROR]' in line or '/FATAL]' in line) + and 'Forge config just got changed on the file system!' not in line] + assert not unexpected, unexpected + reports.append(report) + print(args.output.name, phase, 'PASS', round(report['seconds'], 2), 'seconds', flush=True) + def digests(report): + return {key: value['sorted_coordinate_sha256'] for key, value in report['dimensions'].items()} + assert digests(reports[0]) == digests(reports[1]), 'Saved ores changed on reload' + if args.compare: + assert digests(reports[0]) == digests(json.loads(args.compare.read_text())), 'Independent generation differs' + (args.output / 'qualification.json').write_text(json.dumps(dict(passed=True, seed=args.seed, + reload_unchanged=True, repeated_generation_matches=bool(args.compare)), indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/validation/port114/verify_client.py b/tools/validation/port114/verify_client.py new file mode 100644 index 0000000..00893cb --- /dev/null +++ b/tools/validation/port114/verify_client.py @@ -0,0 +1,67 @@ +"""Run a generated Eclipse profile with the isolated client save/reopen probe. + +The Eclipse DebugPlugin parser must be available in --parser-classpath. +No player run directory or save is used. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +from xml.etree import ElementTree as ET + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for key in ('java', 'parser-java', 'project', 'launch', 'probe', 'output'): + parser.add_argument('--' + key, required=True, type=Path) + parser.add_argument('--parser-classpath', required=True) + parser.add_argument('--mapped-mods', type=Path) + args = parser.parse_args() + args.output.mkdir(parents=True) + mods = args.output / 'mods' + mods.mkdir() + shutil.copy2(args.probe, mods / args.probe.name) + if args.mapped_mods: + for jar in args.mapped_mods.glob('*.jar'): + shutil.copy2(jar, mods / jar.name) + launch = ET.parse(args.launch).getroot() + attrs = {e.attrib['key']: e.attrib['value'] for e in launch.findall('stringAttribute')} + cp = [e.attrib['path'] for e in ET.parse(args.project / '.classpath').getroot().findall('classpathentry') + if e.attrib.get('kind') == 'lib'] + for entry in launch.findall('listAttribute/listEntry'): + value = ET.fromstring(entry.attrib['value']).attrib + if 'externalArchive' in value: + cp.append(value['externalArchive']) + cp = list(dict.fromkeys(cp)) + assert all(Path(p).is_file() for p in cp), 'Missing Eclipse classpath entry' + parsed = subprocess.check_output([args.parser_java, '-cp', args.parser_classpath, + 'ParseEclipseArguments', args.launch]).decode().strip('\0').split('\0') + env = os.environ.copy() + env.update({e.attrib['key']: e.attrib['value'] for e in launch.findall('mapAttribute/mapEntry')}) + inputs = dict(launch=str(args.launch), arguments=parsed, classpath=cp, + staged_mod_classes=env['MOD_CLASSES'], mods={ + p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in mods.glob('*.jar')}) + main_jar = args.project / 'build/libs/BaseMinerals-2.5.2.114041.jar' + inputs['candidate_sha256'] = hashlib.sha256(main_jar.read_bytes()).hexdigest() + (args.output / 'inputs.json').write_text(json.dumps(inputs, indent=2)) + (args.output / 'options.txt').write_text('pauseOnLostFocus:false\nrenderDistance:4\nmaxFps:60\n') + with (args.output / 'console.log').open('wb') as stream: + result = subprocess.run([args.java, '-Xmx2500m', '-cp', os.pathsep.join(cp), + attrs['org.eclipse.jdt.launching.MAIN_TYPE'], *parsed], cwd=args.output, env=env, + stdout=stream, stderr=subprocess.STDOUT, timeout=240, + creationflags=subprocess.CREATE_NO_WINDOW) + report = json.loads((args.output / 'client-probe.json').read_text()) + log = (args.output / 'console.log').read_text(errors='replace') + unexpected = [line for line in log.splitlines() if ('/ERROR]' in line or '/FATAL]' in line) + and not any(allowed in line for allowed in ('Received empty payload on channel fml:handshake', + 'Forge config just got changed on the file system!'))] + assert not unexpected, unexpected + assert result.returncode == 0 and report['passed'] and report['worldReopened'], report + print(args.output.name, 'PASS', report['checks'], 'checks; fresh world and save/reopen', flush=True) + + +if __name__ == '__main__': + main() diff --git a/tools/validation/port114/verify_generation.py b/tools/validation/port114/verify_generation.py new file mode 100644 index 0000000..5828763 --- /dev/null +++ b/tools/validation/port114/verify_generation.py @@ -0,0 +1,41 @@ +"""Census the new world after first boot and reload in packaged Forge.""" +import argparse +from collections import Counter +import json +from pathlib import Path + +from run_forge import prepare, run +from verify_upgrade import census + +HEIGHTS = { + 'lithium': (8, 47), 'niter': (16, 63), 'salt': (24, 79), 'sulfur': (4, 31), + 'phosphorus': (16, 63), 'potash': (8, 47), 'saltpeter': (24, 79), +} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('java', 'runtime', 'output'): + parser.add_argument('--' + name, required=True, type=Path) + parser.add_argument('--mods', required=True, nargs='+', type=Path) + args = parser.parse_args() + prepare(args.runtime, args.output, args.mods) + world = args.output / 'world' + run(args.java, args.output, 'first') + chunks, blocks, _ = census(world, {}) + histograms = {f'baseminerals:{name}_ore': Counter() for name in HEIGHTS} + for (dimension, x, y, z), (name, props) in blocks.items(): + assert dimension == '.' and name in histograms, (dimension, x, y, z, name) + minimum, maximum = HEIGHTS[name.split(':')[1].removesuffix('_ore')] + assert minimum <= y <= maximum, (name, y) + histograms[name][y] += 1 + assert all(histograms.values()), 'One or more mineral ores did not generate' + run(args.java, args.output, 'reload') + assert census(world, {}, chunks)[1] == blocks, 'Mineral coordinates changed on reload' + summary = {'chunks': len(chunks), 'blocks': len(blocks), 'height_histograms': histograms} + (args.output / 'generation.json').write_text(json.dumps(summary, indent=2)) + print('Fresh generation and reload PASS', {k: sum(v.values()) for k, v in histograms.items()}) + + +if __name__ == '__main__': + main() diff --git a/tools/validation/port114/verify_mining.py b/tools/validation/port114/verify_mining.py new file mode 100644 index 0000000..a41c9a7 --- /dev/null +++ b/tools/validation/port114/verify_mining.py @@ -0,0 +1,39 @@ +"""Run the isolated survival-mining probe against a packaged Base Minerals jar.""" +import argparse +import hashlib +import json +from pathlib import Path +import subprocess + +from run_forge import LAUNCHER, prepare + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("java", "runtime", "output", "probe"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--mods", nargs="+", type=Path, required=True) + parser.add_argument("--processing", action="store_true") + args = parser.parse_args() + jars = [*args.mods, args.probe] + prepare(args.runtime, args.output, jars) + (args.output / "input-jars.json").write_text(json.dumps({ + jar.name: hashlib.sha256(jar.read_bytes()).hexdigest() for jar in jars + }, indent=2)) + with (args.output / "console.log").open("wb") as stream: + command = [str(args.java), "-Xmx2G"] + if args.processing: + command.append("-Dmineralprobe.processing=true") + result = subprocess.run([*command, "-jar", json.loads((args.output / "forge-runtime.json").read_text())["launcher"], "nogui"], + cwd=args.output, stdout=stream, stderr=subprocess.STDOUT, timeout=240) + report = json.loads((args.output / "mining-results.json").read_text()) + log = (args.output / "console.log").read_text(encoding="utf-8", errors="replace") + for failure in ("Encountered an unexpected exception", "Error occurred applying transform of coremod", + "Couldn't read loot table baseminerals:", "Parsing error loading recipe baseminerals:"): + assert failure not in log, f"Forge startup error: {failure}" + print(args.output.name, "PASS" if report["passed"] else "FAIL", report["checks"], "checks", flush=True) + assert result.returncode == 0 and report["passed"], report["failures"][:12] + + +if __name__ == "__main__": + main() diff --git a/tools/validation/port114/verify_named_upgrade.py b/tools/validation/port114/verify_named_upgrade.py new file mode 100644 index 0000000..3c4922c --- /dev/null +++ b/tools/validation/port114/verify_named_upgrade.py @@ -0,0 +1,37 @@ +"""Check an already flattened 1.13 save without modifying its original fixture.""" +import argparse +import json +from pathlib import Path +from run_forge import prepare, run +from verify_upgrade import census, compare, digest, fingerprint, saved_mineral_rules + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('java', 'runtime', 'source', 'output'): + parser.add_argument('--' + name, required=True, type=Path) + parser.add_argument('--mods', required=True, nargs='+', type=Path) + args = parser.parse_args() + original = fingerprint(args.source) + before = census(args.source, {}) + assert len(before[1]) > 1000 and len(before[2]) > 0, 'Insufficient named source coverage' + rules = saved_mineral_rules(args.source) + prepare(args.runtime, args.output, args.mods, args.source) + (args.output / 'sources.json').write_text(json.dumps(dict(source=str(args.source), + fingerprint=original, jars={p.name: digest(p) for p in args.mods}), indent=2)) + result = {} + try: + for phase in ('natural-open', 'first', 'reload'): + run(args.java, args.output, phase, upgrade=phase != 'natural-open') + result[phase] = compare(before, census(args.output / 'world', {}, before[0], + require_flattened=phase != 'natural-open')) + assert saved_mineral_rules(args.output / 'world') == rules, 'Saved mineral rules changed' + result[phase]['saved_rules'] = len(rules) + (args.output / 'results.json').write_text(json.dumps(result, indent=2)) + print(args.output.name, phase, 'PASS', result[phase], flush=True) + finally: + assert fingerprint(args.source) == original, 'Original named source changed' + + +if __name__ == '__main__': + main() diff --git a/tools/validation/port114/verify_upgrade.py b/tools/validation/port114/verify_upgrade.py new file mode 100644 index 0000000..1f89b0c --- /dev/null +++ b/tools/validation/port114/verify_upgrade.py @@ -0,0 +1,275 @@ +"""Check mineral states and tagged inventories across the real Forge 1.14 upgrade.""" +import argparse +from collections import Counter +from hashlib import sha256 +from io import BytesIO +import json +from pathlib import Path +import struct +import zlib + +import nbtlib +from nbtlib import Byte, ByteArray, Compound, Int, List, Short, String +import numpy as np + +from run_forge import prepare, run + +MOD = 'baseminerals:' +SECTOR = 4096 +PROBE_CHUNK = (64, 64) + + +def digest(path): + return sha256(path.read_bytes()).hexdigest() + + +def fingerprint(world): + return {p.relative_to(world).as_posix(): digest(p) for p in sorted(world.rglob('*')) if p.is_file()} + + +def saved_mineral_rules(world): + path = world / 'serverconfig/orespawn-worldgen.json' + if not path.is_file(): + return {} + ores = json.loads(path.read_text(encoding='utf-8'))['ores'] + return {key: value for key, value in ores.items() if value.get('block', '').startswith(MOD)} + + +def legacy_registry(world, registry): + root = nbtlib.load(world / 'level.dat') + ids = root['FML']['Registries']['minecraft:' + registry]['ids'] + return {int(entry['V']): str(entry['K']) for entry in ids} + + +def chunk_data(region, slot): + offset = int.from_bytes(region[slot * 4:slot * 4 + 3], 'big') * SECTOR + length, compression = struct.unpack_from('>IB', region, offset) + if compression not in (1, 2): + raise ValueError(f'Unsupported region compression {compression}') + data = zlib.decompress(region[offset + 5:offset + 4 + length], 31 if compression == 1 else 15) + return nbtlib.File.parse(BytesIO(data)) + + +def nibble_array(tag): + raw = np.frombuffer(tag.tobytes(), dtype=np.uint8) + result = np.empty(len(raw) * 2, dtype=np.uint8) + result[::2] = raw & 15 + result[1::2] = raw >> 4 + return result + + +def legacy_section(section, ids): + blocks = np.frombuffer(section['Blocks'].tobytes(), dtype=np.uint8).astype(np.uint16) + if 'Add' in section: + blocks |= nibble_array(section['Add']).astype(np.uint16) << 8 + positions = np.flatnonzero(np.isin(blocks, list(ids))) + if not len(positions): + return + metadata = nibble_array(section['Data']) + for index in positions: + block = ids[int(blocks[index])] + properties = (('level', str(metadata[index])),) if block in (MOD + 'lithium', MOD + 'silicon') else () + yield int(index), block, properties + + +def flattened_section(section): + palette = section.get('Palette', []) + targets = {i: (str(entry['Name']), tuple(sorted((k, str(v)) for k, v in entry.get('Properties', {}).items()))) + for i, entry in enumerate(palette) if str(entry['Name']).startswith(MOD)} + if not targets: + return + bits = max(4, (len(palette) - 1).bit_length()) + words = [int(word) & ((1 << 64) - 1) for word in section.get('BlockStates', [])] + for index in range(4096): + start = index * bits + word, shift = divmod(start, 64) + value = words[word] >> shift if words else 0 + if shift + bits > 64 and words: + value |= words[word + 1] << (64 - shift) + state = targets.get(value & ((1 << bits) - 1)) + if state: + yield index, *state + + +def normalized_stack(stack, legacy): + name = str(stack['id']) + tag = stack.get('tag', Compound()).unpack() + if name == 'forge:bucketfilled': + fluid = tag.get('FluidName', '').removeprefix(MOD) + if fluid not in ('lithium', 'silicon'): + return None + name = MOD + fluid + '_bucket' + del tag['FluidName'], tag['Amount'] + if not name.startswith(MOD): + return None + display = tag.get('display', {}) + if 'Name' in display: + value = display['Name'] + display['Name'] = {'text': value} if legacy else json.loads(value) + return name, int(stack['Count']), tag + + +def census(world, ids, coverage=None, require_flattened=False): + chunks = set() + blocks = {} + chests = {} + for path in sorted(world.rglob('r.*.*.mca')): + dimension = path.parent.parent.relative_to(world).as_posix() + region = path.read_bytes() + for slot in range(1024): + if not region[slot * 4:slot * 4 + 3].strip(b'\0'): + continue + root = chunk_data(region, slot) + legacy = int(root.get('DataVersion', -1)) < 1451 + level = root['Level'] + cx, cz = int(level['xPos']), int(level['zPos']) + chunk = dimension, cx, cz + if coverage is not None and chunk not in coverage: + continue + if require_flattened: + assert int(root.get('DataVersion', -1)) >= 1976, f'Chunk did not reach 1.14.4: {chunk}' + chunks.add(chunk) + for section in level.get('Sections', []): + if 'Blocks' in section: + assert not require_flattened, f'Numeric block array survived in {chunk}' + states = legacy_section(section, ids) + else: + states = flattened_section(section) + for index, name, properties in states: + x, y, z = index & 15, (index >> 8) + int(section['Y']) * 16, (index >> 4) & 15 + blocks[dimension, 16 * cx + x, y, 16 * cz + z] = name, properties + for entity in level.get('TileEntities', []): + if 'Items' not in entity: + continue + items = {int(stack['Slot']): result for stack in entity['Items'] + if (result := normalized_stack(stack, legacy))} + if items: + chests[dimension, int(entity['x']), int(entity['y']), int(entity['z'])] = items + return chunks, blocks, chests + + +def signed(value): + return value if value < 128 else value - 256 + + +def set_nibble(array, index, value): + shift = (index & 1) * 4 + prior = int(array[index >> 1]) & 255 + array[index >> 1] = signed((prior & ~(15 << shift)) | value << shift) + + +def add_fixture(world, probe_chunk=PROBE_CHUNK): + cx, cz = probe_chunk + region_path = world / 'region' / f'r.{cx // 32}.{cz // 32}.mca' + slot = (cx & 31) + (cz & 31) * 32 + region = bytearray(region_path.read_bytes()) + chunk = chunk_data(region, slot) + level = chunk['Level'] + assert int(level['xPos']) == cx and int(level['zPos']) == cz + y = 224 + assert all(int(s['Y']) != y // 16 for s in level['Sections']) + section = Compound(Y=Byte(y // 16), Blocks=ByteArray([0] * 4096), + Data=ByteArray([0] * 2048), Add=ByteArray([0] * 2048), + BlockLight=ByteArray([0] * 2048), SkyLight=ByteArray([-1] * 2048)) + level['Sections'].append(section) + solids = sorted((name, id_) for id_, name in legacy_registry(world, 'blocks').items() if name.startswith(MOD)) + + def put(index, id_, meta=0): + section['Blocks'][index] = signed(id_ & 255) + set_nibble(section['Add'], index, id_ >> 8) + set_nibble(section['Data'], index, meta) + + for index, (name, id_) in enumerate(solids, 32): + put(index, id_) + fluid_ids = {name: id_ for name, id_ in solids if name in (MOD + 'lithium', MOD + 'silicon')} + for row, id_ in enumerate(fluid_ids.values(), 4): + for level_value in range(1, 16): + put(row * 16 + level_value, id_, level_value) + item_names = sorted(name for name in legacy_registry(world, 'items').values() if name.startswith(MOD)) + stacks = [Compound(id=String(name), Count=Byte(index % 3 + 1), Damage=Short(0), + tag=Compound(MigrationTest=String(name))) + for index, name in enumerate(item_names)] + for fluid in ('lithium', 'silicon'): + stacks.append(Compound(id=String('forge:bucketfilled'), Count=Byte(1), Damage=Short(0), + tag=Compound(FluidName=String(fluid), Amount=Int(1000), MigrationTest=String(fluid)))) + entities = List[Compound](level.get('TileEntities', [])) + level['TileEntities'] = entities + for index, start in enumerate(range(0, len(stacks), 27)): + chest_x, chest_z = index * 3 + 1, 8 + put(chest_z * 16 + chest_x, 54, 2) + inventory = List[Compound](stacks[start:start + 27]) + for slot_id, stack in enumerate(inventory): + stack['Slot'] = Byte(slot_id) + entities.append(Compound(id=String('minecraft:chest'), x=Int(cx * 16 + chest_x), + y=Int(y), z=Int(cz * 16 + chest_z), Items=inventory)) + raw = BytesIO() + chunk.write(raw) + compressed = zlib.compress(raw.getvalue()) + payload = struct.pack('>IB', len(compressed) + 1, 2) + compressed + sectors = (len(payload) + SECTOR - 1) // SECTOR + offset = len(region) // SECTOR + assert len(region) % SECTOR == 0 and sectors < 256 + region[slot * 4:slot * 4 + 4] = offset.to_bytes(3, 'big') + bytes([sectors]) + region.extend(payload.ljust(sectors * SECTOR, b'\0')) + region_path.write_bytes(region) + return len(solids), len(stacks) + + +def compare(before, after): + original_chunks, original_blocks, original_chests = before + chunks, blocks, chests = after + difference = {position: [original_blocks.get(position), blocks.get(position)] + for position in original_blocks.keys() | blocks.keys() + if original_blocks.get(position) != blocks.get(position)} + if difference: + preview = list(sorted(difference.items()))[:12] + raise AssertionError(f'{len(difference)} mineral coordinates or states changed. First changes {preview}') + assert original_chests == chests, 'Mineral chest items, counts or tags changed' + assert chunks == original_chunks, f'{len(original_chunks - chunks)} original chunks are missing' + return {'chunks': len(chunks), 'blocks': dict(sorted(Counter(b[0] for b in blocks.values()).items())), + 'chests': len(chests), 'stacks': sum(map(len, chests.values())), + 'coordinate_sha256': sha256(repr(sorted(blocks.items())).encode()).hexdigest()} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('java', 'runtime', 'output', 'source'): + parser.add_argument('--' + name, required=True, type=Path) + parser.add_argument('--mods', required=True, nargs='+', type=Path) + parser.add_argument('--probe-chunk', nargs=2, type=int, default=PROBE_CHUNK) + parser.add_argument('--minimum-blocks', type=int, default=1000) + parser.add_argument('--natural-open', action='store_true', + help='Open normally before converting the remaining unloaded chunks') + args = parser.parse_args() + before_source = fingerprint(args.source) + prepare(args.runtime, args.output, args.mods, args.source) + target = args.output / 'world' + ids = {id_: name for id_, name in legacy_registry(target, 'blocks').items() if name.startswith(MOD)} + forms = add_fixture(target, args.probe_chunk) + before = census(target, ids) + rules = saved_mineral_rules(target) + assert len(before[1]) >= args.minimum_blocks and len(ids) > 0, 'No meaningful source mineral census' + source_manifest = {'source': str(args.source), 'fingerprint': before_source, 'registry': ids, + 'added_forms': forms, 'jars': {p.name: digest(p) for p in args.mods}} + (args.output / 'sources.json').write_text(json.dumps(source_manifest, indent=2)) + result = {} + try: + if args.natural_open: + run(args.java, args.output, 'natural-open') + result['natural-open'] = compare(before, census(target, ids, before[0])) + if rules: + assert saved_mineral_rules(target) == rules, 'Saved OreSpawn mineral rules changed' + for phase in ('first', 'reload'): + run(args.java, args.output, phase, upgrade=True) + result[phase] = compare(before, census(target, ids, before[0], require_flattened=True)) + if rules: + assert saved_mineral_rules(target) == rules, 'Saved OreSpawn mineral rules changed' + result[phase]['saved_rules'] = len(rules) + print(f"{phase} census PASS {result[phase]}", flush=True) + (args.output / 'results.json').write_text(json.dumps(result, indent=2)) + finally: + assert before_source == fingerprint(args.source), 'Source fixture changed' + + +if __name__ == '__main__': + main()