From 9fdb731a5ea55c82e688d605538dbea233648ad0 Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Mon, 30 Nov 2026 15:46:42 +0000 Subject: [PATCH] Bring Base Minerals to Minecraft 1.16.5 --- .github/workflows/ci.yml | 14 +- .github/workflows/codeql-analysis.yml | 6 +- .github/workflows/deploy-release.yml | 32 +- .github/workflows/release-on-tag.yml | 6 +- .github/workflows/validate-gradle-build.yml | 6 +- CHANGELOG.txt | 12 +- README.md | 20 +- build.gradle | 47 ++- docs/BUILDING.md | 79 ++-- docs/KNOWN_ISSUES.md | 14 +- docs/MANUAL_TESTING.md | 8 +- docs/PORTING_115.md | 2 +- docs/PORTING_116.md | 48 +++ docs/RELEASING.md | 16 +- docs/WORLD_UPGRADES.md | 25 +- gradle.properties | 10 +- ...ty-115.gradle => compatibility-116.gradle} | 10 +- gradle/dependencies.json | 12 +- ...115.gradle => local-companions-116.gradle} | 4 +- ...{release-115.gradle => release-116.gradle} | 26 +- gradle/stage-legacy-dependencies.py | 10 + .../moddev/mc/baseminerals/BaseMinerals.java | 11 +- .../client/MineralFluidRenderer.java | 6 +- .../baseminerals/content/MineralContent.java | 17 +- .../content/MoltenMineralBlock.java | 12 +- .../content/MoltenMineralFluid.java | 45 +-- .../baseminerals/loot/MineralPowderCount.java | 18 +- .../migration/LegacyWorldUpgrade.java | 24 +- .../recipe/SharedCrushingSerializer.java | 8 +- src/main/resources/META-INF/mods.toml | 10 +- .../baseminerals_legacy_world_upgrade.js | 42 +- .../tags/blocks/beacon_base_blocks.json | 13 + src/main/resources/pack.mcmeta | 2 +- ...115_resources.js => test_116_resources.js} | 0 .../port116/ParseEclipseArguments.java | 27 ++ .../java/test/MineralClientProbe.java | 259 ++++++++++++ .../client-probe/resources/META-INF/mods.toml | 13 + .../client-probe/resources/pack.mcmeta | 6 + .../java/test/MineralGenerationProbe.java | 116 ++++++ .../resources/META-INF/mods.toml | 13 + .../generation-probe/resources/pack.mcmeta | 6 + .../java/test/MineralMiningProbe.java | 371 ++++++++++++++++++ .../mining-probe/resources/META-INF/mods.toml | 13 + .../mining-probe/resources/pack.mcmeta | 6 + tools/validation/port116/requirements.txt | 1 + tools/validation/port116/run_forge.py | 166 ++++++++ .../port116/test_missing_content.py | 22 ++ .../port116/test_palette_decoder.py | 34 ++ tools/validation/port116/verify_census.py | 75 ++++ tools/validation/port116/verify_client.py | 67 ++++ tools/validation/port116/verify_generation.py | 41 ++ tools/validation/port116/verify_mining.py | 39 ++ .../port116/verify_named_upgrade.py | 37 ++ tools/validation/port116/verify_upgrade.py | 280 +++++++++++++ 54 files changed, 1934 insertions(+), 273 deletions(-) create mode 100644 docs/PORTING_116.md rename gradle/{compatibility-115.gradle => compatibility-116.gradle} (93%) rename gradle/{local-companions-115.gradle => local-companions-116.gradle} (92%) rename gradle/{release-115.gradle => release-116.gradle} (93%) create mode 100644 src/main/resources/data/minecraft/tags/blocks/beacon_base_blocks.json rename tools/{test_115_resources.js => test_116_resources.js} (100%) create mode 100644 tools/validation/port116/ParseEclipseArguments.java create mode 100644 tools/validation/port116/client-probe/java/test/MineralClientProbe.java create mode 100644 tools/validation/port116/client-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port116/client-probe/resources/pack.mcmeta create mode 100644 tools/validation/port116/generation-probe/java/test/MineralGenerationProbe.java create mode 100644 tools/validation/port116/generation-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port116/generation-probe/resources/pack.mcmeta create mode 100644 tools/validation/port116/mining-probe/java/test/MineralMiningProbe.java create mode 100644 tools/validation/port116/mining-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port116/mining-probe/resources/pack.mcmeta create mode 100644 tools/validation/port116/requirements.txt create mode 100644 tools/validation/port116/run_forge.py create mode 100644 tools/validation/port116/test_missing_content.py create mode 100644 tools/validation/port116/test_palette_decoder.py create mode 100644 tools/validation/port116/verify_census.py create mode 100644 tools/validation/port116/verify_client.py create mode 100644 tools/validation/port116/verify_generation.py create mode 100644 tools/validation/port116/verify_mining.py create mode 100644 tools/validation/port116/verify_named_upgrade.py create mode 100644 tools/validation/port116/verify_upgrade.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eed1ad0..61ce11d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,16 +1,16 @@ -name: Base Minerals 1.15.2 CI +name: Base Minerals 1.16.5 CI on: push: - branches: [master-1.15.2, 'feature/**'] + branches: [master-1.16.5, 'feature/**'] pull_request: - branches: [master-1.15.2] + branches: [master-1.16.5] permissions: contents: read concurrency: - group: baseminerals-115-${{ github.workflow }}-${{ github.ref }} + group: baseminerals-116-${{ 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 verify115ReleaseArtifacts write115ReleaseChecksums genEclipseRuns eclipse \ + bash ./gradlew clean check build javadoc verify116ReleaseArtifacts write116ReleaseChecksums 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.15.2-${{ github.sha }} + name: BaseMinerals-1.16.5-${{ 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.15.2-diagnostics-${{ github.sha }} + name: BaseMinerals-1.16.5-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 d6e92c3..caa0a23 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -3,11 +3,11 @@ name: CodeQL on: push: branches: - - master-1.15.2 - - feature/baseminerals-1.15.2 + - master-1.16.5 + - feature/baseminerals-1.16.5 pull_request: branches: - - master-1.15.2 + - master-1.16.5 schedule: - cron: '47 7 * * 4' diff --git a/.github/workflows/deploy-release.yml b/.github/workflows/deploy-release.yml index 5b43bad..858c705 100644 --- a/.github/workflows/deploy-release.yml +++ b/.github/workflows/deploy-release.yml @@ -1,15 +1,15 @@ -name: Release Base Minerals 1.15.2 +name: Release Base Minerals 1.16.5 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.15.2 + description: Four-part version for Minecraft 1.16.5 required: true type: string release_commit: - description: Full SHA of the checked MMD master-1.15.2 commit + description: Full SHA of the checked MMD master-1.16.5 commit required: true type: string tested_jar_sha256: @@ -33,13 +33,13 @@ permissions: contents: read concurrency: - group: baseminerals-release-115 + group: baseminerals-release-116 cancel-in-progress: false jobs: qualify: name: Verify merged CI candidate - if: github.repository == 'MinecraftModDevelopmentMods/BaseMinerals' && github.ref == 'refs/heads/master-1.15.2' + if: github.repository == 'MinecraftModDevelopmentMods/BaseMinerals' && github.ref == 'refs/heads/master-1.16.5' 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]+\.115021$ ]] + [[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.116051$ ]] [[ "$RELEASE_SHA" =~ ^[[:xdigit:]]{40}$ ]] [[ "$TESTED_SHA" =~ ^[[:xdigit:]]{64}$ ]] test "$(git rev-parse HEAD)" = "$RELEASE_SHA" - test "$(gh api "repos/$GITHUB_REPOSITORY/branches/master-1.15.2" --jq .commit.sha)" = "$RELEASE_SHA" + test "$(gh api "repos/$GITHUB_REPOSITORY/branches/master-1.16.5" --jq .commit.sha)" = "$RELEASE_SHA" grep -Fxq "mod_version=$RELEASE_VERSION" gradle.properties - grep -Fxq 'minecraft_version=1.15.2' gradle.properties + grep -Fxq 'minecraft_version=1.16.5' gradle.properties ci_run="$(gh api --method GET "repos/$GITHUB_REPOSITORY/actions/workflows/ci.yml/runs" \ - -f branch=master-1.15.2 -f head_sha="$RELEASE_SHA" -f event=push -f status=success \ + -f branch=master-1.16.5 -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.15.2-${{ inputs.release_commit }} + name: BaseMinerals-1.16.5-${{ 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.15.2-${{ inputs.release_commit }} + name: BaseMinerals-1.16.5-${{ 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.15.2-${{ inputs.release_commit }} + name: BaseMinerals-1.16.5-${{ inputs.release_commit }} run-id: ${{ needs.qualify.outputs.ci_run }} github-token: ${{ github.token }} path: ${{ runner.temp }}/release-input @@ -192,12 +192,12 @@ jobs: with: curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} curseforge-id: '270972' - name: Base Minerals ${{ inputs.release_version }} for Minecraft 1.15.2 (Forge) + name: Base Minerals ${{ inputs.release_version }} for Minecraft 1.16.5 (Forge) version: ${{ inputs.release_version }} version-type: ${{ inputs.curseforge_release_level }} changelog-file: ${{ runner.temp }}/release-input/CHANGELOG.txt loaders: forge - game-versions: '1.15.2' + game-versions: '1.16.5' game-version-filter: none environment: client | server java: Java 8 @@ -233,7 +233,7 @@ jobs: steps: - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: - name: BaseMinerals-1.15.2-${{ inputs.release_commit }} + name: BaseMinerals-1.16.5-${{ inputs.release_commit }} run-id: ${{ needs.qualify.outputs.ci_run }} github-token: ${{ github.token }} path: ${{ runner.temp }}/release-input @@ -246,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.15.2 (Forge)" \ + --title "Base Minerals $RELEASE_VERSION for Minecraft 1.16.5 (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 a2585db..2a7da6c 100644 --- a/.github/workflows/release-on-tag.yml +++ b/.github/workflows/release-on-tag.yml @@ -1,7 +1,7 @@ -name: Validate Base Minerals 1.15.2 tag +name: Validate Base Minerals 1.16.5 tag on: push: - tags: ['*.*.*.115021'] + tags: ['*.*.*.116051'] 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.15.2' gradle.properties + grep -Fxq 'minecraft_version=1.16.5' 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 c1907e0..303cfa6 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.15.2 - - feature/baseminerals-1.15.2 + - master-1.16.5 + - feature/baseminerals-1.16.5 pull_request: branches: - - master-1.15.2 + - master-1.16.5 permissions: contents: read diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 38b4ba3..a4dfcc8 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,10 +1,18 @@ +2.5.2.116051 for Minecraft 1.16.5 + +This brings the local 1.15.2 port across to Forge 36, keeping the mineral IDs, overlays, drops, hammer tags, recipes and ore defaults. Base Metals 3.1.2.116051 remains optional. The build uses the published OreSpawn 4.1.7.116051. Modern Metals 3.0.0.116051 also supplies shared crushing when installed. + +Loot registration, fluid APIs and tool requirements now use the 1.16 equivalents. Old-world conversion follows the new level reader and player storage while keeping each save's original numeric block mapping. Keep the full save and baseminerals-legacy-registry.dat together when upgrading a copy. + +The older material settings screens and Tinkers integration remain unported. A matching Modern Metals 1.16 build is not available yet. This candidate has not been released. + 2.5.2.115021 for Minecraft 1.15.2 -This brings the released 1.14.4 build across to Forge 31, using OreSpawn 4.1.7.115021. The minerals, drops, hammer mining tags, recipes and ore defaults carry forward. Base Metals 3.0.3.115021 remains optional. +This brings the released 1.14.4 build across to Forge 31, using OreSpawn 4.1.7.115021. The minerals, drops, hammer mining tags, recipes and ore defaults carry forward. Base Metals 3.0.2.115021 remains optional. Ore and molten-fluid rendering now uses the 1.15 render-layer API. The old-world conversion follows the new chunk loader while keeping each save's own numeric registry mapping. Keep the full save and baseminerals-legacy-registry.dat together when upgrading a copy. -Modern Metals 3.0.0.115021 also supplies shared crushing when installed. +The manual Base Metals launch pins the local ore-overlay spacing and UV correction. A matching Modern Metals 1.15 build is not available yet. The older material settings screens and Tinkers integration remain unavailable. 2.5.2.114041 for Minecraft 1.14.4 diff --git a/README.md b/README.md index 9454171..5b0e877 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,14 @@ 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.15.2 and Forge 31.2.57. Install -[OreSpawn 4.1.7.115021](https://github.com/MinecraftModDevelopmentMods/OreSpawn/releases/tag/4.1.7.115021). -[Base Metals 3.0.3.115021](https://github.com/MinecraftModDevelopmentMods/BaseMetals/releases/tag/3.0.3.115021) -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.115021 or a later compatible 1.15.2 build when installing the two together. +This release is for Minecraft 1.16.5 and Forge 36.2.34. Install [OreSpawn 4.1.7.116051](https://github.com/MinecraftModDevelopmentMods/OreSpawn/releases/tag/4.1.7.116051) +on the client and server. +[Base Metals 3.1.2.116051](https://github.com/MinecraftModDevelopmentMods/BaseMetals/releases/tag/3.1.2.116051) +is optional in new worlds and supplies the Crack Hammer. Keep the matching +Base Metals installed when upgrading a world that contains its blocks or items. Base Minerals shares its ore crushing recipes with Base Metals when installed. -[Modern Metals 3.0.0.115021](https://github.com/MinecraftModDevelopmentMods/ModernMetals/releases/tag/3.0.0.115021) -also supplies shared crushing when installed. +[Modern Metals 3.0.0.116051](https://github.com/MinecraftModDevelopmentMods/ModernMetals/releases/tag/3.0.0.116051) supplies the shared crushing recipes when Base Metals is absent. Mining lithium returns one ore block. Niter, phosphorus, potash, salt, saltpeter and sulfur drop 2–4 powders, with Fortune increasing the upper @@ -26,9 +24,9 @@ are available from level-two armorers, toolsmiths and weaponsmiths. ## Upgrading a world -Copy the whole save folder before opening it on 1.15.2, including level.dat +Copy the whole save folder before opening it on 1.16.5, including level.dat and serverconfig. Start the copy with Forge, Base Minerals, OreSpawn and the -1.15.2 versions of any other mods whose content it uses. Check existing blocks +1.16.5 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 @@ -38,5 +36,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), [port decisions](docs/PORTING_115.md) +[upgrade checks](docs/WORLD_UPGRADES.md), [port decisions](docs/PORTING_116.md) and [known limits](docs/KNOWN_ISSUES.md). diff --git a/build.gradle b/build.gradle index 7cb086a..20dc405 100644 --- a/build.gradle +++ b/build.gradle @@ -40,7 +40,7 @@ def stageRunClasses = tasks.register('stageRunClasses', Sync) { } minecraft { - mappings channel: 'snapshot', version: '20200514-1.15.1' + mappings channel: 'official', version: '1.16.5' if (gradle.startParameter.offline) mavenizerArguments.add('--offline') runs { configureEach { @@ -49,10 +49,10 @@ minecraft { providers.gradleProperty('baseMineralsRunDirectory').getOrElse('run')) mods { baseminerals { source sourceSets.main } } environment 'target', name.toLowerCase().contains('client') ? 'fmluserdevclient' : 'fmluserdevserver' - environment 'MC_VERSION', '1.15.2' - environment 'MCP_VERSION', '20200515.085601' - environment 'MCP_MAPPINGS', 'snapshot_20200514-1.15.1' - environment 'FORGE_VERSION', '31.2.57' + environment 'MC_VERSION', '1.16.5' + environment 'MCP_VERSION', '20210116.111650' + environment 'MCP_MAPPINGS', 'official_1.16.5' + environment 'FORGE_VERSION', '36.2.34' environment 'FORGE_GROUP', 'net.minecraftforge' def path = modClasses.get().asFile.absolutePath environment 'MOD_CLASSES', "baseminerals%%${path}${File.pathSeparator}baseminerals%%${path}" @@ -91,11 +91,24 @@ repositories { } def specs = new JsonSlurper().parse(file('gradle/dependencies.json')) +def unpublishedDependencies = specs.findAll { it.provenance == 'unpublished-qualified-local' } +if (providers.gradleProperty('releaseBuild').map { it.toBoolean() }.orElse(false).get() + && !unpublishedDependencies.isEmpty()) { + throw new GradleException('Publication is blocked: pin the published OreSpawn 1.16.5 release first.') +} +tasks.configureEach { + if (name.startsWith('publish') || name == 'verify116PreparedReleaseArtifacts') { + doFirst { + if (!unpublishedDependencies.isEmpty()) + throw new GradleException('Publication is blocked: pin the published OreSpawn 1.16.5 release first.') + } + } +} configurations { pinnedMods { canBeConsumed = false; transitive = false } } dependencies { - implementation minecraft.dependency('net.minecraftforge:forge:1.15.2-31.2.57') + implementation minecraft.dependency('net.minecraftforge:forge:1.16.5-36.2.34') specs.each { spec -> pinnedMods spec.coordinate if (spec.runtime) implementation renamer.dependency(spec.coordinate) @@ -143,18 +156,18 @@ tasks.named('test') { useJUnitPlatform() } sourceSets { generationProbe { - java.srcDirs = ['tools/validation/port115/generation-probe/java'] - resources.srcDirs = ['tools/validation/port115/generation-probe/resources'] + java.srcDirs = ['tools/validation/port116/generation-probe/java'] + resources.srcDirs = ['tools/validation/port116/generation-probe/resources'] compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath } clientProbe { - java.srcDirs = ['tools/validation/port115/client-probe/java'] - resources.srcDirs = ['tools/validation/port115/client-probe/resources'] + java.srcDirs = ['tools/validation/port116/client-probe/java'] + resources.srcDirs = ['tools/validation/port116/client-probe/resources'] compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath } miningProbe { - java.srcDirs = ['tools/validation/port115/mining-probe/java'] - resources.srcDirs = ['tools/validation/port115/mining-probe/resources'] + java.srcDirs = ['tools/validation/port116/mining-probe/java'] + resources.srcDirs = ['tools/validation/port116/mining-probe/resources'] compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath } } @@ -198,11 +211,11 @@ tasks.register('verifyStartupRegistration', Exec) { commandLine 'node', '--test', 'tools/test_fluid_registration.js' } tasks.named('check') { dependsOn 'verifyStartupRegistration' } -tasks.register('verify115Resources', Exec) { +tasks.register('verify116Resources', Exec) { group = 'verification' - commandLine 'node', '--test', 'tools/test_115_resources.js' + commandLine 'node', '--test', 'tools/test_116_resources.js' } -tasks.named('check') { dependsOn 'verify115Resources' } +tasks.named('check') { dependsOn 'verify116Resources' } ['client', 'server'].each { run -> tasks.matching { it.name == 'run' + run.capitalize() }.configureEach { dependsOn stageRunClasses @@ -269,8 +282,8 @@ tasks.named('processResources', ProcessResources) { apply from: 'gradle/ore-models.gradle' -apply from: 'gradle/release-115.gradle' +apply from: 'gradle/release-116.gradle' apply from: 'gradle/normalize-javadoc-trees.gradle' -apply from: 'gradle/compatibility-115.gradle' +apply from: 'gradle/compatibility-116.gradle' diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 35862c4..4aa3c59 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -1,64 +1,29 @@ -# Building Base Minerals 1.15.2 +# Building the 1.16.5 candidate -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 31.2.57 with MCP snapshot 20200514-1.15.1 and MCP config -20200515.085601. +Use the nested Base Minerals 116/BaseMinerals project. The wrapper pins Gradle +9.6.1 with ForgeGradle 7.0.34, Renamer 1.1.5 and Foojay 1.0.0. Use Java 17 for +Gradle, Java 25 for Mavenizer and Java 8 for compilation and Minecraft. Keep +Eclipse and command-line launches on the same physical Gradle cache. Do not run +two builds against that cache at once. -Select one Gradle cache for Eclipse and the terminal. Stage the checksum-pinned -public OreSpawn 4.1.7.115021 and Base Metals 3.0.3.115021 jars, then build with -Java 17 as JAVA_HOME. Base Metals remains optional when playing. +Stage the published OreSpawn, Base Metals and Modern Metals jars before building. +The stager checks the SHA-256 pins in gradle/dependencies.json. -```powershell -python gradle/stage-legacy-dependencies.py .gradle/legacy-dependencies -.\gradlew.bat check build javadoc verify115ReleaseArtifacts genEclipseRuns eclipse -``` + python gradle/stage-legacy-dependencies.py .gradle/legacy-dependencies -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.115021.jar. Development output -is under build/libs-dev; sources and Javadocs are separate. + ./gradlew check build javadoc verify116ReleaseArtifacts write116ReleaseChecksums + ./gradlew genEclipseRuns eclipse -Import the inner checkout as an Eclipse Gradle project. The generated client -and server launches use Java 8 and staged main output. Gradle refresh preserves -quoted paths for directories containing spaces. Use runClient.launch alone or -runClientWithBaseMetals.launch for hammer and companion testing. The profiles -have separate run directories. Terminal runClient accepts -PwithBaseMetals=true. +Pass the exact installed JDK paths with org.gradle.java.installations.paths +and disable toolchain auto-detection/downloads when reproducing qualification. +The local evidence directory retains the commands and toolchain paths used. -The four Eclipse client profiles cover standalone, Base Metals 3.0.3.115021, Modern Metals 3.0.0.115021 and both. To use a local companion build, run `pinLocalCompanions`, then regenerate Eclipse in a separate invocation. Gradle checks the player and mapped jars and retains replaced copies under `.gradle/retired-compatibility-jars`. Release builds use the published dependencies. +The generated Eclipse launches quote paths containing spaces and stage processed +production classes/resources together. The ordinary launch excludes executable +test probes. runClientWithBaseMetals.launch uses a separate directory with its +selected mapped companion jar. The other launches cover Modern Metals on its own and both metal mods together. -## Local gameplay checks - -The tools under tools/validation/port115 use an independently installed -Forge 1.15.2-31.2.57 server directory containing its launcher and libraries. -Install tools/validation/port115/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/port115/verify_mining.py --help -python tools/validation/port115/verify_census.py --help -python tools/validation/port115/verify_upgrade.py --help -python tools/validation/port115/verify_named_upgrade.py --help -python tools/validation/port115/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 published Base Metals and with the -local model-fix candidate. 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. +Local companion support pins both player and mapped jars. After rebuilding a +sibling, run pinLocalBaseMetals and regenerate Eclipse before using that profile. +The final handoff states whether the profile uses public or local companion bytes. +Build/test probes remain separate from the production mod and are never published. diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 9d8be75..dc58def 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -1,17 +1,23 @@ -# Known limits for Minecraft 1.15.2 +# Known limits for Minecraft 1.16.5 The 1.12 material and molten-form switches in BaseMinerals.cfg and their settings 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 31. +The 1.12 Tinkers' Construct integration does not carry over to Forge 36. -OreSpawn 4.1.7.115021 writes empty dimensions or dimension_selectors objects -for some vanilla and companion-mod rules. Its published JSON schema rejects +OreSpawn 4.1.7.116051 writes empty dimensions or dimension_selectors objects +for some vanilla and companion-mod rules. Its bundled 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. +Older saves also log Forge/vanilla registry and entity-attribute changes, including +the retired biome registry, zombie-pigman names and the old Forge swim-speed, +name-tag-distance and entity-gravity attributes. The automated upgrade checks +verify Base Minerals blocks, fluid levels, stacks and rules; they do not promise +lossless conversion of every other mod's entities or attributes. + 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 index 22e5fb9..1611816 100644 --- a/docs/MANUAL_TESTING.md +++ b/docs/MANUAL_TESTING.md @@ -1,11 +1,11 @@ -# Manual testing on 1.15.2 +# Manual testing on 1.16.5 Refresh the inner BaseMinerals Gradle project in Eclipse. Start with runClientWithBaseMetals.launch for the pinned local Base Metals model fix and iron-hammer testing. runClient.launch is standalone. Rebuild the sibling, run pinLocalBaseMetals, then regenerate launches after changing that candidate. -Each profile has its own run directory. No Modern Metals 1.15 artifact is -currently available; do not use its 1.14 jar. +Each profile has its own run directory. No Modern Metals 1.16 artifact is +currently available; do not use a jar from an older Minecraft version. Use a disposable world for these checks: @@ -19,7 +19,7 @@ Use a disposable world for these checks: 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 vanilla-registry prompts when Forge 31 opens older saves. + expected vanilla-registry prompts when Forge 36 opens older saves. The older material settings screens and Tinkers integration remain unavailable, as on the released 1.13.2 branch. Change generation through OreSpawn. Automated diff --git a/docs/PORTING_115.md b/docs/PORTING_115.md index fcae612..d4116ab 100644 --- a/docs/PORTING_115.md +++ b/docs/PORTING_115.md @@ -24,7 +24,7 @@ Renamer 1.1.5 and Foojay 1.0.0 remain; Gradle uses Java 17 and Mavenizer Java 25 fixing. Keep the mapping sidecar for later unloaded chunks. Do not derive the world from a global current-save variable or a single shared numeric map. - Continue to enqueue the typed schema-5 provider through OreSpawn's public - API. Pin public OreSpawn 4.1.7.115021 and optional Base Metals 3.0.3.115021 by + API. Pin public OreSpawn 4.1.7.115021 and optional Base Metals 3.0.2.115021 by SHA-256. OreSpawn owns placement and saved-profile merging. - No matching Modern Metals 1.15 artifact or checkout was found at port start. Do not load its 1.14 jar. Keep the optional crushing bridge and future local diff --git a/docs/PORTING_116.md b/docs/PORTING_116.md new file mode 100644 index 0000000..0b26bea --- /dev/null +++ b/docs/PORTING_116.md @@ -0,0 +1,48 @@ +# Minecraft 1.16.5 port + +The source is the local 1.15.2 candidate, including the seven mineral overlays, +additive hammer tags and saved-world conversion. Its source manifest is sealed +with the local qualification receipt. The 1.15 work remains uncommitted; the Git +ancestor is released 1.14.4 e30ddcb. + +The target is Base Minerals 2.5.2.116051, Minecraft 1.16.5, Forge 36.2.34 and +official 1.16.5 mappings (MCP config 20210115.111550). Gradle 9.6.1, ForgeGradle +7.0.34, Renamer 1.1.5 and Foojay 1.0.0 remain. Gradle uses Java 17, Mavenizer +uses Java 25, and compilation/Minecraft use Java 8. Resource pack format is 6; +the vanilla target DataVersion is 2586. + +## Decisions + +- Keep all 17 block, 41 item and four fluid IDs, recipes, tags, names, properties + and bucket identities. The seven ore defaults, material IDs, stable legacy + rule IDs and standard placement channel are unchanged. There is no second + generator, terrain replacement, retrogen or new equipment. +- Use 1.16's native loot function type registry while retaining the earlier + uniform 2..4+Fortune powder formula. Lithium and Silk Touch return one ore. + Keep the shared crushing serializer and both companion hammer tags. Mark + mineral blocks as requiring the correct tool under the new block properties. +- Keep client render-layer registration, ore cutouts, molten-fluid translucency, + fluid attributes, bucket tinting and native flow/heat behaviour. Base Minerals + has no doors, trapdoors or bars to carry forward from the companion cutout fix. +- Capture the world registry before SaveFormat's new codec-based level reader + removes or converts legacy data. Wrap its compressed level reads, cache the + mapping by canonical save directory, and write the sidecar when chunks need + it. Listing a save must not write a new sidecar. Read dedicated player data + through PlayerData, and capture the three-argument ChunkLoader constructor's + directory. Keep conversion scoped to that chunk's original numeric mapping. +- Leave the new dynamic biome/dimension registries and BiomeLoadingEvent to + OreSpawn. The add-on still submits one typed ore-only provider through the + supported public API during InterModEnqueueEvent. Use the existing dimension + selector for ordinary dimensions and Nether/End exclusion. +- The build uses OreSpawn 4.1.7.116051 with optional Base Metals 3.1.2.116051 and Modern Metals 3.0.0.116051. +- The older material settings/screens and Tinkers integration remain unported. + Keep registered content for existing saves and use OreSpawn generation controls. + +References: [Forge 1.16 porting documentation](https://docs.minecraftforge.net/en/1.16.x/legacy/porting/), +the [linked 1.15–1.16 primer](https://gist.github.com/50ap5ud5/f4e70f0e8faeddcfde6b4b1df70f83b8), +[Minecraft 1.16.5 release notes](https://www.minecraft.net/en-us/article/minecraft-java-edition-1-16-5), +the exact mapped Forge 36.2.34 classes, OreSpawn's local public API/provider +documentation, and its sealed 4.1.7.116051 qualification receipt. + +The local handoff records the actual tested hashes and results. A successful +local port does not imply manual gameplay acceptance or published dependencies. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 7181919..4889883 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,18 +1,18 @@ -# Releasing Base Minerals for Minecraft 1.15.2 +# Releasing Base Minerals for Minecraft 1.16.5 Build with Java 17, Temurin 8u502-b07 for compilation and Java 25 for -Mavenizer. Run check, build, verify115ReleaseArtifacts, -write115ReleaseChecksums, genEclipseRuns and eclipse. Keep the packaged +Mavenizer. Run check, build, verify116ReleaseArtifacts, +write116ReleaseChecksums, genEclipseRuns and eclipse. Keep the packaged gameplay and saved-world checks local, then complete manual testing. -The new master-1.15.2 branch needs to be established on MMD before opening its +The new master-1.16.5 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.15.2-. Compare +BaseMinerals-1.16.5-. 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.15.2 with the release version, full merged +Run deploy-release.yml on master-1.16.5 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, @@ -27,6 +27,4 @@ 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.15.2 release. The local -Base Metals model fix must be released and repinned before the public combined -stack is accepted. No Modern Metals 1.15 artifact is currently qualified. +and keep the compatibility pins on the public Base Metals and Modern Metals releases. diff --git a/docs/WORLD_UPGRADES.md b/docs/WORLD_UPGRADES.md index 8eb814e..c917367 100644 --- a/docs/WORLD_UPGRADES.md +++ b/docs/WORLD_UPGRADES.md @@ -1,4 +1,4 @@ -# Base Minerals 1.15.2 upgrade checks +# Base Minerals 1.16.5 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,13 +14,19 @@ 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 reach the flattened 1.15.2 format -(DataVersion 2230 or later). Already flattened 1.13.2 and 1.14.4 saves are checked with +molten block. Each original chunk must reach the flattened 1.16.5 format +(DataVersion 2586 or later). Already flattened 1.13.2, 1.14.4 and 1.15.2 saves are checked with the separate named-world runner, including their inventories and saved rules. - python tools/validation/port115/verify_upgrade.py --java --runtime --source --output --mods [basemetals.jar] +The census reads each chunk using its own DataVersion. Vanilla's +BitStorageAlignFix at version 2527 changed palette entries to stop at long-word +boundaries. The test reader handles both formats, including mixed old/new chunks +during a normal first open; its synthetic fixtures cover five- through nine-bit +palettes on both sides of the transition. -Use verify_named_upgrade.py with the same arguments for a 1.13.2 or 1.14.4 source. It + python tools/validation/port116/verify_upgrade.py --java --runtime --source --output --mods [basemetals.jar] + +Use verify_named_upgrade.py with the same arguments for a 1.13.2, 1.14.4 or 1.15.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. @@ -33,8 +39,9 @@ first open before converting the remaining chunks. Use verify_census.py with 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 31 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. +Forge 36 reports retired biome/profession registries and vanilla sign, dye, +zombie-pigman, sound and memory entries when opening older saves. Dedicated +servers can continue without a confirmation prompt. The disposable runner audits +those exact known vanilla lists even when there is no prompt, and rejects unknown +missing content. Complete warning lists remain in the qualification logs. Do not use blanket confirmation on a player world; inspect its missing list. diff --git a/gradle.properties b/gradle.properties index 003d3ba..a85975a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,9 +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.15.2 -forge_version=31.2.57 -mod_version=2.5.2.115021 +minecraft_version=1.16.5 +forge_version=36.2.34 +mod_version=2.5.2.116051 -basemetals_version=3.0.3.115021 -modernmetals_version=3.0.0.115021 +basemetals_version=3.1.2.116051 +modernmetals_version=3.0.0.116051 diff --git a/gradle/compatibility-115.gradle b/gradle/compatibility-116.gradle similarity index 93% rename from gradle/compatibility-115.gradle rename to gradle/compatibility-116.gradle index b0ec0b3..f26eda2 100644 --- a/gradle/compatibility-115.gradle +++ b/gradle/compatibility-116.gradle @@ -2,7 +2,7 @@ import groovy.xml.XmlParser import groovy.xml.XmlUtil import java.security.MessageDigest -apply from: 'gradle/local-companions-115.gradle' +apply from: 'gradle/local-companions-116.gradle' def basePin = localCompanionPins.basemetals def modernPin = localCompanionPins.modernmetals @@ -39,8 +39,8 @@ tasks.register('generateCompatibilityRuns') { File modDirectory = new File(directory, 'mods') modDirectory.mkdirs() def selected = [:] - if (mods.contains('base')) selected['BaseMetals-3.0.3.115021-mapped.jar'] = configurations.baseMetalsDevelopment.singleFile - if (mods.contains('modern')) selected['ModernMetals-3.0.0.115021-mapped.jar'] = configurations.modernMetalsDevelopment.singleFile + if (mods.contains('base')) selected['BaseMetals-3.1.2.116051-mapped.jar'] = configurations.baseMetalsDevelopment.singleFile + if (mods.contains('modern')) selected['ModernMetals-3.0.0.116051-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/) && @@ -70,8 +70,8 @@ tasks.register('verifyStagedCompanions') { 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.3.115021-mapped.jar', configurations.baseMetalsDevelopment], - 'modern': ['ModernMetals-3.0.0.115021-mapped.jar', configurations.modernMetalsDevelopment]].each { kind, spec -> + ['base': ['BaseMetals-3.1.2.116051-mapped.jar', configurations.baseMetalsDevelopment], + 'modern': ['ModernMetals-3.0.0.116051-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}") } diff --git a/gradle/dependencies.json b/gradle/dependencies.json index 00a95f4..4428ae9 100644 --- a/gradle/dependencies.json +++ b/gradle/dependencies.json @@ -1,23 +1,23 @@ [ { "id": "orespawn", - "coordinate": "zone.moddev.mc.orespawn:OreSpawn:4.1.7.115021", + "coordinate": "zone.moddev.mc.orespawn:OreSpawn:4.1.7.116051", "repository": "https://maven.moddev.zone/releases", "runtime": true, - "sha256": "5CDF25E6D98560CBEF8366D6D1589B66E99A386859E5D659ACBB2B806FCF8F3D" + "sha256": "310022CCDA2C6A4D118F94C72838ACC8020C2F594F2E93754DC19D2644B8E9FC" }, { "id": "basemetals", - "coordinate": "zone.moddev.mc.basemetals:BaseMetals:3.0.3.115021", + "coordinate": "zone.moddev.mc.basemetals:BaseMetals:3.1.2.116051", "repository": "https://maven.moddev.zone/releases", "runtime": false, - "sha256": "5C7CF937C10D1F131E2716D6242B1B56EEBE051CF8F1B267AA78E6B9AD6784C1" + "sha256": "1816919FEF35908AB42F5F4C32AA05E9DF3255AE9090AA83AB14F232591DA046" }, { "id": "modernmetals", - "coordinate": "zone.moddev.mc.modernmetals:ModernMetals:3.0.0.115021", + "coordinate": "zone.moddev.mc.modernmetals:ModernMetals:3.0.0.116051", "repository": "https://maven.moddev.zone/releases", "runtime": false, - "sha256": "CE6F05F9561CA9621765DC13FE63B24228ACAE2D33CE9968F8EE8F24F899AD7C" + "sha256": "3F6F869A1B385C514F538FCD03A163CE6551A484CE6EA5DCBA0BDBCD410650B3" } ] diff --git a/gradle/local-companions-115.gradle b/gradle/local-companions-116.gradle similarity index 92% rename from gradle/local-companions-115.gradle rename to gradle/local-companions-116.gradle index abc9ef3..ac8727a 100644 --- a/gradle/local-companions-115.gradle +++ b/gradle/local-companions-116.gradle @@ -5,8 +5,8 @@ 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.3.115021', checkout: '../../BaseMetals 115/BaseMetals', property: 'baseMetalsCheckout'], - modernmetals: [label: 'ModernMetals', version: '3.0.0.115021', checkout: '../../ModernMetals 115/ModernMetals', property: 'modernMetalsCheckout'] + basemetals: [label: 'BaseMetals', version: '3.1.2.116051', checkout: '../../BaseMetals 116/BaseMetals', property: 'baseMetalsCheckout'], + modernmetals: [label: 'ModernMetals', version: '3.0.0.116051', checkout: '../../ModernMetals 116/ModernMetals', property: 'modernMetalsCheckout'] ] def hash = { File jar -> MessageDigest.getInstance('SHA-256').digest(jar.bytes).encodeHex().toString() } def pins = [:] diff --git a/gradle/release-115.gradle b/gradle/release-116.gradle similarity index 93% rename from gradle/release-115.gradle rename to gradle/release-116.gradle index b1be650..0d30729 100644 --- a/gradle/release-115.gradle +++ b/gradle/release-116.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.15.2-forge-31.2.57-java-8') + 'Build-Target': 'minecraft-1.16.5-forge-36.2.34-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+\.115021/)) { + if (project.group.toString() != expectedGroup || !(project.version.toString() ==~ /\d+\.\d+\.\d+\.116051/)) { 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.15.2]"') - || !metadata.contains('versionRange="[4.1.7.115021,5.0.0)"')) { + || !metadata.contains('versionRange="[1.16.5]"') + || !metadata.contains('versionRange="[4.1.7.116051,5.0.0)"')) { throw new GradleException('Wrong or unresolved release mod metadata') } } @@ -86,14 +86,14 @@ def audit = { File directory -> } } -tasks.register('verify115ReleaseArtifacts') { +tasks.register('verify116ReleaseArtifacts') { group = 'verification' dependsOn tasks.named('assemble'), tasks.named('check') doLast { audit(layout.buildDirectory.dir('libs').get().asFile) } } -tasks.register('write115ReleaseChecksums') { +tasks.register('write116ReleaseChecksums') { group = 'verification' - dependsOn tasks.named('verify115ReleaseArtifacts') + dependsOn tasks.named('verify116ReleaseArtifacts') doLast { File output = layout.buildDirectory.file('release/SHA256SUMS').get().asFile output.parentFile.mkdirs() @@ -102,7 +102,7 @@ tasks.register('write115ReleaseChecksums') { }.join('\n') + '\n', 'UTF-8') } } -tasks.register('verify115PreparedReleaseArtifacts') { +tasks.register('verify116PreparedReleaseArtifacts') { 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.15.2, using Forge 31 and OreSpawn 4.' + description = 'Base Minerals for Minecraft 1.16.5, using Forge 36 and OreSpawn 4.' url = 'https://github.com/MinecraftModDevelopmentMods/BaseMinerals' licenses { license { @@ -181,7 +181,7 @@ publishing { } } } -tasks.register('verify115MavenCoordinates') { +tasks.register('verify116MavenCoordinates') { dependsOn 'generatePomFileForMavenJavaPublication' doLast { def pom = new XmlSlurper(false, false).parse(layout.buildDirectory.file('publications/mavenJava/pom-default.xml').get().asFile) @@ -197,8 +197,8 @@ tasks.register('verify115MavenCoordinates') { } } tasks.withType(PublishToMavenRepository).configureEach { - dependsOn 'verify115MavenCoordinates' - dependsOn preparedDirectory.isPresent() ? 'verify115PreparedReleaseArtifacts' : 'verify115ReleaseArtifacts' + dependsOn 'verify116MavenCoordinates' + dependsOn preparedDirectory.isPresent() ? 'verify116PreparedReleaseArtifacts' : 'verify116ReleaseArtifacts' doFirst { def url = providers.environmentVariable('MAVEN_UPLOAD_URL').getOrElse('') if (!url.startsWith('https://') || url.startsWith('https://invalid.invalid') @@ -209,4 +209,4 @@ tasks.withType(PublishToMavenRepository).configureEach { } } -tasks.named('check') { dependsOn 'verify115MavenCoordinates' } +tasks.named('check') { dependsOn 'verify116MavenCoordinates' } diff --git a/gradle/stage-legacy-dependencies.py b/gradle/stage-legacy-dependencies.py index 5db851e..8b42595 100644 --- a/gradle/stage-legacy-dependencies.py +++ b/gradle/stage-legacy-dependencies.py @@ -30,6 +30,7 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("destination", type=Path) parser.add_argument("--cache", type=Path, help="Existing Gradle user home; matching files are verified before reuse") + parser.add_argument("--orespawn-candidate", type=Path, help="Exact qualified local OreSpawn jar, until its release is published") args = parser.parse_args() specs = json.loads(Path(__file__).with_name("dependencies.json").read_text(encoding="utf-8")) destination = args.destination.resolve() @@ -43,6 +44,15 @@ def main(): target.parent.mkdir(parents=True, exist_ok=True) if not target.exists(): + if spec.get("provenance") == "unpublished-qualified-local": + if spec["id"] != "orespawn" or args.orespawn_candidate is None: + raise ValueError("Supply --orespawn-candidate with the qualified local jar; this dependency is not published") + data = args.orespawn_candidate.read_bytes() + if hashlib.sha256(data).hexdigest().upper() != spec["sha256"]: + raise ValueError("Local OreSpawn candidate checksum mismatch") + target.write_bytes(data) + print(spec["id"], spec["sha256"], "local/unpublished", flush=True) + continue cached = list((args.cache / "caches/modules-2/files-2.1" / group / artifact / version).glob("*/" + filename)) if args.cache else [] if cached: data = cached[0].read_bytes() diff --git a/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java b/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java index 76b1cb9..ff0e711 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java +++ b/src/main/java/zone/moddev/mc/baseminerals/BaseMinerals.java @@ -9,12 +9,15 @@ import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import zone.moddev.mc.baseminerals.client.MineralFluidRenderer; import zone.moddev.mc.baseminerals.loot.MineralPowderCount; -import net.minecraft.world.storage.loot.functions.LootFunctionManager; +import net.minecraft.loot.LootFunctionType; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.registry.Registry; import zone.moddev.mc.baseminerals.worldgen.BaseMineralsWorldgenProvider; @Mod(BaseMinerals.MOD_ID) public final class BaseMinerals { public static final String MOD_ID = "baseminerals"; + public static LootFunctionType MINERAL_POWDER_COUNT; public BaseMinerals() { DistExecutor.runWhenOn(Dist.CLIENT, () -> MineralFluidRenderer::register); @@ -23,8 +26,10 @@ public BaseMinerals() { } private void setup(FMLCommonSetupEvent event) { - DeferredWorkQueue.runLater(() -> { - LootFunctionManager.registerFunction(new MineralPowderCount.Serializer()); + event.enqueueWork(() -> { + MINERAL_POWDER_COUNT = Registry.register(Registry.LOOT_FUNCTION_TYPE, + new ResourceLocation(MOD_ID, "mineral_powder_count"), + new LootFunctionType(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 e5bf4e2..a73cd15 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java +++ b/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java @@ -19,13 +19,13 @@ private static void rendering(net.minecraftforge.fml.event.lifecycle.FMLClientSe for (net.minecraft.block.Block block : net.minecraftforge.registries.ForgeRegistries.BLOCKS) { if (!"baseminerals".equals(block.getRegistryName().getNamespace())) continue; if (block instanceof zone.moddev.mc.baseminerals.content.MoltenMineralBlock) - net.minecraft.client.renderer.RenderTypeLookup.setRenderLayer(block, net.minecraft.client.renderer.RenderType.getTranslucent()); + net.minecraft.client.renderer.RenderTypeLookup.setRenderLayer(block, net.minecraft.client.renderer.RenderType.translucent()); else if (block.getRegistryName().getPath().endsWith("_ore")) - net.minecraft.client.renderer.RenderTypeLookup.setRenderLayer(block, net.minecraft.client.renderer.RenderType.getCutoutMipped()); + net.minecraft.client.renderer.RenderTypeLookup.setRenderLayer(block, net.minecraft.client.renderer.RenderType.cutoutMipped()); } for (net.minecraft.fluid.Fluid fluid : net.minecraftforge.registries.ForgeRegistries.FLUIDS) if (MineralContent.ownsFluid(fluid)) - net.minecraft.client.renderer.RenderTypeLookup.setRenderLayer(fluid, net.minecraft.client.renderer.RenderType.getTranslucent()); + net.minecraft.client.renderer.RenderTypeLookup.setRenderLayer(fluid, net.minecraft.client.renderer.RenderType.translucent()); }); } private static void bucketColours(ColorHandlerEvent.Item event) { 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 1078160..d42274d 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java @@ -36,7 +36,7 @@ public final class MineralContent { private static final Map BLOCKS = new LinkedHashMap<>(); private static final Map MOLTEN = new LinkedHashMap<>(); private static final ItemGroup GROUP = new ItemGroup(BaseMinerals.MOD_ID) { - @Override public ItemStack createIcon() { return new ItemStack(BLOCKS.get("sulfur_ore")); } + @Override public ItemStack makeIcon() { return new ItemStack(BLOCKS.get("sulfur_ore")); } }; private MineralContent() {} @@ -66,8 +66,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 MoltenMineralBlock(molten.source, Block.Properties.create(Material.LAVA) - .doesNotBlockMovement().hardnessAndResistance(100.0F).lightValue(10).variableOpacity()); + molten.block = new MoltenMineralBlock(molten.source, Block.Properties.of(Material.LAVA) + .noCollission().strength(100.0F).lightLevel(state -> 10).dynamicShape()); putBlock(event, name, molten.block); }); } @@ -89,7 +89,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 BucketItem(molten.source, itemProperties().containerItem(Items.BUCKET).maxStackSize(1)); + molten.bucket = new BucketItem(molten.source, itemProperties().craftRemainder(Items.BUCKET).stacksTo(1)); putItem(event, name + "_bucket", molten.bucket); }); putItem(event, "silicon_blend", new Item(itemProperties())); @@ -100,7 +100,7 @@ private static void putItem(RegistryEvent.Register event, String name, Ite event.getRegistry().register(item.setRegistryName(id(name))); } - private static Item.Properties itemProperties() { return new Item.Properties().group(GROUP); } + private static Item.Properties itemProperties() { return new Item.Properties().tab(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; } @@ -131,15 +131,12 @@ private static Block.Properties properties(String material, boolean ore) { float hardness = ore ? 5.0F : metal ? 16.0F : 10.0F; // The old library stored resistance at five times Minecraft's exposed value. float resistance = (metal ? 4.0F : 1.0F) * (ore ? 0.75F : 1.0F); - return Block.Properties.create(metal && !ore ? Material.IRON : Material.ROCK) + return Block.Properties.of(metal && !ore ? Material.METAL : Material.STONE) .sound(metal && !ore ? SoundType.METAL : SoundType.STONE) - .hardnessAndResistance(hardness, resistance); + .strength(hardness, resistance).requiresCorrectToolForDrops(); } @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; - } } } diff --git a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java index bb14811..50e1724 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java @@ -12,12 +12,12 @@ /** 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().getActualHeight(world, pos)) { - entity.attackEntityFrom(DamageSource.LAVA, 4.0F); - entity.setFire(15); + @Override public void entityInside(BlockState state, World world, BlockPos pos, Entity entity) { + super.entityInside(state, world, pos, entity); + if (!world.isClientSide && entity instanceof LivingEntity && !entity.fireImmune() && !entity.isInLava() + && entity.getBoundingBox().minY < pos.getY() + state.getFluidState().getHeight(world, pos)) { + entity.hurt(DamageSource.LAVA, 4.0F); + entity.setSecondsOnFire(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 a3fc6e8..eb617b1 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java @@ -4,7 +4,7 @@ import net.minecraft.block.BlockState; import net.minecraft.fluid.FlowingFluid; import net.minecraft.fluid.Fluid; -import net.minecraft.fluid.IFluidState; +import net.minecraft.fluid.FluidState; import net.minecraft.item.Item; import net.minecraft.state.StateContainer; import net.minecraft.util.Direction; @@ -31,43 +31,44 @@ protected MoltenMineralFluid(MineralContent.Molten content) { } - @Override public Fluid getFlowingFluid() { return content.flowing; } - @Override public Fluid getStillFluid() { return content.source; } - @Override public Item getFilledBucket() { return content.bucket; } + @Override public Fluid getFlowing() { return content.flowing; } + @Override public Fluid getSource() { return content.source; } + @Override public Item getBucket() { return content.bucket; } - @Override protected boolean canSourcesMultiply() { return false; } - @Override protected void beforeReplacingBlock(IWorld world, BlockPos pos, BlockState state) { - net.minecraft.block.Block.spawnDrops(state, world.getWorld(), pos); + @Override protected boolean canConvertToSource() { return false; } + @Override protected void beforeDestroyingBlock(IWorld world, BlockPos pos, BlockState state) { + net.minecraft.block.Block.dropResources(state, world, pos, + state.hasTileEntity() ? world.getBlockEntity(pos) : null); } @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 public int getDropOff(IWorldReader world) { return 2; } + @Override public int getTickDelay(IWorldReader world) { return 30; } @Override protected float getExplosionResistance() { return 100.0F; } - @Override public boolean isEquivalentTo(Fluid fluid) { + @Override public boolean isSame(Fluid fluid) { return fluid == content.source || fluid == content.flowing; } - @Override protected boolean canDisplace(IFluidState state, net.minecraft.world.IBlockReader world, + @Override protected boolean canBeReplacedWith(FluidState state, net.minecraft.world.IBlockReader world, BlockPos pos, Fluid fluid, Direction direction) { - return direction == Direction.DOWN && !fluid.isEquivalentTo(this); + return direction == Direction.DOWN && !fluid.isSame(this); } - @Override public BlockState getBlockState(IFluidState state) { - return content.block.getDefaultState() - .with(FlowingFluidBlock.LEVEL, Integer.valueOf(getLevelFromState(state))); + @Override public BlockState createLegacyBlock(FluidState state) { + return content.block.defaultBlockState() + .setValue(FlowingFluidBlock.LEVEL, Integer.valueOf(getLegacyLevel(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_8); + @Override protected void createFluidStateDefinition(StateContainer.Builder builder) { + super.createFluidStateDefinition(builder); + builder.add(LEVEL); } - @Override public int getLevel(IFluidState state) { return state.get(LEVEL_1_8); } - @Override public boolean isSource(IFluidState state) { return false; } + @Override public int getAmount(FluidState state) { return state.getValue(LEVEL); } + @Override public boolean isSource(FluidState state) { return false; } } public static final class Source extends MoltenMineralFluid { public Source(MineralContent.Molten content) { super(content); } - @Override public int getLevel(IFluidState state) { return 8; } - @Override public boolean isSource(IFluidState state) { return true; } + @Override public int getAmount(FluidState state) { return 8; } + @Override public boolean isSource(FluidState state) { return true; } } } diff --git a/src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java b/src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java index b75fa75..177a3d4 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java +++ b/src/main/java/zone/moddev/mc/baseminerals/loot/MineralPowderCount.java @@ -6,24 +6,26 @@ 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; +import net.minecraft.loot.LootContext; +import net.minecraft.loot.LootFunction; +import net.minecraft.loot.LootParameters; +import net.minecraft.loot.LootFunctionType; +import net.minecraft.loot.conditions.ILootCondition; +import zone.moddev.mc.baseminerals.BaseMinerals; /** 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 public LootFunctionType getType() { return BaseMinerals.MINERAL_POWDER_COUNT; } - @Override protected ItemStack doApply(ItemStack stack, LootContext context) { - ItemStack tool = context.get(LootParameters.TOOL); - int fortune = tool == null ? 0 : EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, tool); + @Override protected ItemStack run(ItemStack stack, LootContext context) { + ItemStack tool = context.getParamOrNull(LootParameters.TOOL); + int fortune = tool == null ? 0 : EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_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 360067e..6cea0a5 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgrade.java +++ b/src/main/java/zone/moddev/mc/baseminerals/migration/LegacyWorldUpgrade.java @@ -2,7 +2,7 @@ import net.minecraft.util.datafix.DefaultTypeReferences; import com.mojang.datafixers.DataFixer; -import com.mojang.datafixers.Dynamic; +import com.mojang.serialization.Dynamic; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -25,7 +25,6 @@ import net.minecraft.nbt.NBTUtil; import net.minecraft.util.ResourceLocation; import net.minecraft.util.datafix.fixes.BlockStateFlatteningMap; -import net.minecraft.world.storage.SaveHandler; import net.minecraftforge.registries.ForgeRegistries; /** Supplies only this world's mineral states during the numeric chunk conversion. */ @@ -39,23 +38,24 @@ public final class LegacyWorldUpgrade { private LegacyWorldUpgrade() {} - public static void prepareWorld(CompoundNBT root, File file, SaveHandler handler) { + public static CompoundNBT readWorld(File file) throws IOException { + CompoundNBT root = CompressedStreamTools.readCompressed(file); 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()); + LOGGER.info("World read {} dataVersion={} root={}", file, + root.getCompound("Data").getInt("DataVersion"), root.getAllKeys()); } ListNBT minerals = mineralIds(root); - if (minerals.isEmpty()) return; + if (minerals.isEmpty()) return root; try { Path directory = file.getCanonicalFile().getParentFile().toPath(); // Force Upgrade reads WorldInfo without a SaveHandler and can rewrite level.dat // before the upgrade thread sees its first chunk. Remember the original read. DISCOVERED.put(directory, minerals); - if (handler != null) persistRegistry(directory, minerals); } catch (IOException e) { throw new IllegalStateException("Could not preserve the old Base Minerals registry from " + file, e); } + return root; } private static ListNBT mineralIds(CompoundNBT root) { @@ -67,7 +67,7 @@ private static ListNBT mineralIds(CompoundNBT root) { if (id.getString("K").startsWith("baseminerals:")) minerals.add(id.copy()); } if (Boolean.getBoolean("baseminerals.debugUpgrade")) { - LOGGER.info("Registry scan {} block IDs, {} mineral IDs (root {})", ids.size(), minerals.size(), root.keySet()); + LOGGER.info("Registry scan {} block IDs, {} mineral IDs (root {})", ids.size(), minerals.size(), root.getAllKeys()); } return minerals; } @@ -178,9 +178,9 @@ private static Map[]> bake(ListNBT ids) { Block block = ForgeRegistries.BLOCKS.getValue(name); Dynamic[] entries = new Dynamic[16]; for (int meta = 0; meta < entries.length; meta++) { - BlockState state = block.getDefaultState(); - if (block instanceof FlowingFluidBlock) state = state.with(FlowingFluidBlock.LEVEL, meta); - entries[meta] = BlockStateFlatteningMap.makeDynamic(NBTUtil.writeBlockState(state).toString()); + BlockState state = block.defaultBlockState(); + if (block instanceof FlowingFluidBlock) state = state.setValue(FlowingFluidBlock.LEVEL, meta); + entries[meta] = BlockStateFlatteningMap.parse(NBTUtil.writeBlockState(state).toString()); } result.put(numeric, entries); } @@ -202,7 +202,7 @@ public static void migrateItems(INBT value) { if (tag.isEmpty()) compound.remove("tag"); } } - for (String key : new ArrayList<>(compound.keySet())) migrateItems(compound.get(key)); + for (String key : new ArrayList<>(compound.getAllKeys())) 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 e418c04..0f6b877 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/recipe/SharedCrushingSerializer.java +++ b/src/main/java/zone/moddev/mc/baseminerals/recipe/SharedCrushingSerializer.java @@ -26,7 +26,7 @@ public static void register(RegistryEvent.Register> event) } @Override - public IRecipe read(ResourceLocation id, JsonObject json) { + public IRecipe fromJson(ResourceLocation id, JsonObject json) { ModList mods = ModList.get(); String host; if (mods.isLoaded("basemetals")) { @@ -40,16 +40,16 @@ 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 RecipeManager.deserializeRecipe(id, shared); + return RecipeManager.fromJson(id, shared); } @Override - public IRecipe read(ResourceLocation id, PacketBuffer buffer) { + public IRecipe fromNetwork(ResourceLocation id, PacketBuffer buffer) { throw new UnsupportedOperationException("Shared crushing uses the selected mod's serializer for sync"); } @Override - public void write(PacketBuffer buffer, IRecipe recipe) { + public void toNetwork(PacketBuffer buffer, IRecipe recipe) { throw new UnsupportedOperationException("Shared crushing uses the selected mod's serializer for sync"); } diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index fb8d5d1..082cf06 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -1,5 +1,5 @@ modLoader="javafml" -loaderVersion="[31,)" +loaderVersion="[36,)" license="LGPL-2.1" [[mods]] @@ -13,27 +13,27 @@ description="Adds mineral ores, blocks, powders, alloys and molten minerals." [[dependencies.baseminerals]] modId="minecraft" mandatory=true -versionRange="[1.15.2]" +versionRange="[1.16.5]" ordering="NONE" side="BOTH" [[dependencies.baseminerals]] modId="orespawn" mandatory=true -versionRange="[4.1.7.115021,5.0.0)" +versionRange="[4.1.7.116051,5.0.0)" ordering="AFTER" side="BOTH" [[dependencies.baseminerals]] modId="basemetals" mandatory=false -versionRange="[3.0.3.115021,4.0.0)" +versionRange="[3.1.2.116051,4.0.0)" ordering="AFTER" side="BOTH" [[dependencies.baseminerals]] modId="modernmetals" mandatory=false -versionRange="[3.0.0.115021,4.0.0)" +versionRange="[3.0.0.116051,4.0.0)" ordering="AFTER" side="BOTH" diff --git a/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js b/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js index 54591d5..8a55dd1 100644 --- a/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js +++ b/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js @@ -34,7 +34,7 @@ function initializeCoreMod() { 'baseminerals_numeric_states': { 'target': { 'type': 'CLASS', 'name': 'net.minecraft.util.datafix.fixes.BlockStateFlatteningMap' }, 'transformer': function(node) { - var descriptor = '(I)Lcom/mojang/datafixers/Dynamic;'; + var descriptor = '(I)Lcom/mojang/serialization/Dynamic;'; for (var i = 0; i < node.methods.size(); i++) { var method = node.methods.get(i); if (method.desc !== descriptor) continue; @@ -50,30 +50,28 @@ function initializeCoreMod() { method.instructions.insert(prefix); return node; } - throw new Error('Base Minerals could not find the Forge 31 numeric state converter'); + throw new Error('Base Minerals could not find the Forge 36 numeric state converter'); } }, 'baseminerals_save_registry': { '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;'; + var patched = 0; 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; insn = insn.getNext()) { - if (!isNbtRead(insn)) continue; - var prepare = new InsnList(); - prepare.add(new VarInsnNode(Opcodes.ALOAD, insn.var)); - prepare.add(new VarInsnNode(Opcodes.ALOAD, 0)); - prepare.add(new VarInsnNode(Opcodes.ALOAD, 2)); - prepare.add(call('prepareWorld', '(' + NBT - + 'Ljava/io/File;Lnet/minecraft/world/storage/SaveHandler;)V')); - method.instructions.insert(insn, prepare); - return node; + for (var insn = method.instructions.getFirst(); insn !== null;) { + var next = insn.getNext(); + if (insn.getOpcode() === Opcodes.INVOKESTATIC + && insn.owner === 'net/minecraft/nbt/CompressedStreamTools' + && insn.desc === '(Ljava/io/File;)' + NBT) { + method.instructions.set(insn, call('readWorld', insn.desc)); + patched++; + } + insn = next; } } - throw new Error('Base Minerals could not find the Forge 31 world registry reader'); + if (patched === 0) throw new Error('Base Minerals could not wrap the Forge 36 world registry readers'); + return node; } }, 'baseminerals_region_directory': { @@ -85,7 +83,7 @@ function initializeCoreMod() { var patched = 0; for (var i = 0; i < node.methods.size(); ++i) { var method = node.methods.get(i); - if (method.name !== '' || method.desc !== '(Ljava/io/File;Lcom/mojang/datafixers/DataFixer;)V') continue; + if (method.name !== '' || method.desc !== '(Ljava/io/File;Lcom/mojang/datafixers/DataFixer;Z)V') continue; for (var insn = method.instructions.getFirst(); insn !== null; insn = insn.getNext()) { if (insn.getOpcode() !== Opcodes.RETURN) continue; var capture = new InsnList(); @@ -96,7 +94,7 @@ function initializeCoreMod() { patched++; } } - if (patched !== 1) throw new Error('Base Minerals could not capture the Forge 31 chunk directory'); + if (patched !== 1) throw new Error('Base Minerals could not capture the Forge 36 chunk 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)); @@ -113,7 +111,7 @@ function initializeCoreMod() { var patched = 0; for (var i = 0; i < node.methods.size(); ++i) { var method = node.methods.get(i); - if (method.desc !== '(Lnet/minecraft/world/dimension/DimensionType;Ljava/util/function/Supplier;' + NBT + ')' + NBT) continue; + if (method.desc !== '(Lnet/minecraft/util/RegistryKey;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') { @@ -134,12 +132,12 @@ function initializeCoreMod() { insn = next; } } - if (patched !== 2) throw new Error('Base Minerals could not wrap both Forge 31 chunk upgrades'); + if (patched !== 2) throw new Error('Base Minerals could not wrap both Forge 36 chunk upgrades'); return node; } }, 'baseminerals_player_upgrade': { - 'target': { 'type': 'CLASS', 'name': 'net.minecraft.world.storage.SaveHandler' }, + 'target': { 'type': 'CLASS', 'name': 'net.minecraft.world.storage.PlayerData' }, 'transformer': function(node) { var patched = 0; for (var i = 0; i < node.methods.size(); i++) { @@ -153,7 +151,7 @@ function initializeCoreMod() { patched++; } } - if (patched === 0) throw new Error('Base Minerals could not find the Forge 31 player data reader'); + if (patched === 0) throw new Error('Base Minerals could not find the Forge 36 player data reader'); return node; } } diff --git a/src/main/resources/data/minecraft/tags/blocks/beacon_base_blocks.json b/src/main/resources/data/minecraft/tags/blocks/beacon_base_blocks.json new file mode 100644 index 0000000..a8817c4 --- /dev/null +++ b/src/main/resources/data/minecraft/tags/blocks/beacon_base_blocks.json @@ -0,0 +1,13 @@ +{ + "replace": false, + "values": [ + "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/pack.mcmeta b/src/main/resources/pack.mcmeta index ff17d4c..ae359b7 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -1,6 +1,6 @@ { "pack": { - "pack_format": 5, + "pack_format": 6, "description": "Base Minerals" } } diff --git a/tools/test_115_resources.js b/tools/test_116_resources.js similarity index 100% rename from tools/test_115_resources.js rename to tools/test_116_resources.js diff --git a/tools/validation/port116/ParseEclipseArguments.java b/tools/validation/port116/ParseEclipseArguments.java new file mode 100644 index 0000000..8fbb81f --- /dev/null +++ b/tools/validation/port116/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/port116/client-probe/java/test/MineralClientProbe.java b/tools/validation/port116/client-probe/java/test/MineralClientProbe.java new file mode 100644 index 0000000..33e7b59 --- /dev/null +++ b/tools/validation/port116/client-probe/java/test/MineralClientProbe.java @@ -0,0 +1,259 @@ +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.client.renderer.RenderType; +import net.minecraft.client.renderer.RenderTypeLookup; +import net.minecraft.util.Direction; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.GameType; +import net.minecraft.world.WorldSettings; +import net.minecraft.world.World; +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.screen instanceof net.minecraftforge.fml.client.gui.screen.LoadingErrorScreen) + throw new IllegalStateException("Forge reported a loading error"); + if (++ticks > 3600) throw new IllegalStateException("Client timeout at stage " + stage); + if (stage == 0 && mc.screen instanceof MainMenuScreen) { + validate(mc); + net.minecraft.util.registry.DynamicRegistries.Impl registries = net.minecraft.util.registry.DynamicRegistries.builtin(); + net.minecraft.world.gen.settings.DimensionGeneratorSettings generator = net.minecraft.world.gen.settings.DimensionGeneratorSettings.makeDefault( + registries.registryOrThrow(net.minecraft.util.registry.Registry.DIMENSION_TYPE_REGISTRY), + registries.registryOrThrow(net.minecraft.util.registry.Registry.BIOME_REGISTRY), + registries.registryOrThrow(net.minecraft.util.registry.Registry.NOISE_GENERATOR_SETTINGS_REGISTRY)) + .withSeed(false, java.util.OptionalLong.of(8675309L)); + WorldSettings settings = new WorldSettings("Base Minerals 1.16 check", GameType.SURVIVAL, + false, net.minecraft.world.Difficulty.NORMAL, true, new net.minecraft.world.GameRules(), + net.minecraft.util.datafix.codec.DatapackCodec.DEFAULT); + mc.createLevel("mineral-smoke", settings, registries, generator); + stage = 1; ticks = 0; + } else if (stage == 1 && mc.level != null && mc.player != null && ++loaded > 80) { + if (!exerciseHeldMining(mc)) return; + stopping = mc.getSingleplayerServer(); + mc.level.disconnect(); + mc.clearLevel(); + mc.setScreen(new MainMenuScreen()); + stage = 2; ticks = 0; loaded = 0; + } else if (stage == 2 && mc.screen instanceof MainMenuScreen && !stopping.getRunningThread().isAlive()) { + mc.loadLevel("mineral-smoke"); + stage = 3; ticks = 0; + } else if (stage == 3 && mc.level != null && mc.player != null && ++loaded > 80) { + stopping = mc.getSingleplayerServer(); + mc.level.disconnect(); + mc.clearLevel(); + mc.setScreen(new MainMenuScreen()); + stage = 4; ticks = 0; + } else if (stage == 4 && !stopping.getRunningThread().isAlive()) { + write(true, null); stage = 5; mc.stop(); + } + } catch (Throwable error) { + error.printStackTrace(); write(false, error.toString()); stage = 5; mc.stop(); + } + } + + 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().getModel(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(RenderTypeLookup.canRenderInLayer(block.defaultBlockState(), RenderType.cutoutMipped()), "Ore cutout " + mineral); + oreModel(mc.getBlockRenderer().getBlockModel(block.defaultBlockState()), block, mineral); + oreModel(mc.getItemRenderer().getModel(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().getModel(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.isTinted() && 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.getTextureAtlas(net.minecraft.client.renderer.texture.AtlasTexture.LOCATION_BLOCKS).apply(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.getBlockRenderer().getBlockModel(block.defaultBlockState()), block); + baseOreGap(mc.getItemRenderer().getModel(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.defaultBlockState(), 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.getVertices(); int stride = data.length / 4; + for (int vertex = 0; vertex < 4; vertex++) { + float u = (Float.intBitsToFloat(data[vertex * stride + 4]) - quad.getSprite().getU0()) * 16.0F / (quad.getSprite().getU1() - quad.getSprite().getU0()); + float v = (Float.intBitsToFloat(data[vertex * stride + 5]) - quad.getSprite().getV0()) * 16.0F / (quad.getSprite().getV1() - quad.getSprite().getV0()); + 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.gameMode.stopDestroyBlock(); + operation = mc.getSingleplayerServer().submit(() -> { + net.minecraft.world.server.ServerWorld world = mc.getSingleplayerServer().getLevel(World.OVERWORLD); + net.minecraft.entity.player.ServerPlayerEntity player = mc.getSingleplayerServer().getPlayerList().getPlayer(mc.player.getUUID()); + player.gameMode.setGameModeForPlayer(GameType.SURVIVAL); + for (int x = -5; x <= 5; x++) for (int z = -5; z <= 5; z++) + world.setBlock(DIG_POS.offset(x, -1, z), net.minecraft.block.Blocks.STONE.defaultBlockState(), 3); + player.connection.teleport(128.5D, 180.0D, 125.5D, 0, 0); + world.getEntitiesOfClass(net.minecraft.entity.item.ItemEntity.class, + new net.minecraft.util.math.AxisAlignedBB(DIG_POS).inflate(1.5D)).forEach(net.minecraft.entity.item.ItemEntity::remove); + player.inventory.selected = 0; + player.inventory.setItem(0, new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation(test[0])))); + player.initMenu(); + world.setBlock(DIG_POS, ForgeRegistries.BLOCKS.getValue(new ResourceLocation(test[1])).defaultBlockState(), 3); + }); + digPhase = 1; + } else if (digPhase == 1 && operation.isDone()) { + operation.join(); mc.player.inventory.selected = 0; + if (!test[1].equals(mc.level.getBlockState(DIG_POS).getBlock().getRegistryName().toString()) + || !test[0].equals(mc.player.getMainHandItem().getItem().getRegistryName().toString()) + || mc.player.getMainHandItem().getDamageValue() != 0 || Math.abs(mc.player.getY() - 180) > 0.1D) return false; + net.minecraft.block.BlockState state = mc.level.getBlockState(DIG_POS); + float speed = mc.player.getMainHandItem().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.getDestroySpeed(mc.level, DIG_POS) * 30.0F / speed) + 6; + digPhase = 2; digTicks = 0; attackTicks = 0; + } else if (digPhase == 2) { + mc.gameMode.continueDestroyBlock(DIG_POS, Direction.UP); + attackTicks++; + if (mc.level.isEmptyBlock(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.level.isEmptyBlock(DIG_POS), "Mined ore reappeared on the client " + test[1]); + check(mc.player.getMainHandItem().getDamageValue() == 1, "Client hammer durability did not sync " + test[1]); + operation = mc.getSingleplayerServer().submit(() -> { + net.minecraft.world.server.ServerWorld world = mc.getSingleplayerServer().getLevel(World.OVERWORLD); + check(world.isEmptyBlock(DIG_POS), "Held mining left the ore on the server " + test[1]); + int count = 0; + for (net.minecraft.entity.item.ItemEntity drop : world.getEntitiesOfClass(net.minecraft.entity.item.ItemEntity.class, + new net.minecraft.util.math.AxisAlignedBB(DIG_POS).inflate(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.getParticleIcon().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.defaultBlockState(), 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().isTransparent(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/port116/client-probe/resources/META-INF/mods.toml b/tools/validation/port116/client-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..78d39fe --- /dev/null +++ b/tools/validation/port116/client-probe/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +loaderVersion="[36,)" +license="LGPL-2.1" +[[mods]] +modId="mineralclientprobe" +version="1" +displayName="Base Minerals client test" +[[dependencies.mineralclientprobe]] +modId="baseminerals" +mandatory=true +versionRange="[2.5.2.116051,)" +ordering="AFTER" +side="CLIENT" diff --git a/tools/validation/port116/client-probe/resources/pack.mcmeta b/tools/validation/port116/client-probe/resources/pack.mcmeta new file mode 100644 index 0000000..dc2753e --- /dev/null +++ b/tools/validation/port116/client-probe/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 6, + "description": "Disposable qualification probe" + } +} diff --git a/tools/validation/port116/generation-probe/java/test/MineralGenerationProbe.java b/tools/validation/port116/generation-probe/java/test/MineralGenerationProbe.java new file mode 100644 index 0000000..ce1a80b --- /dev/null +++ b/tools/validation/port116/generation-probe/java/test/MineralGenerationProbe.java @@ -0,0 +1,116 @@ +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.World; +import net.minecraft.util.RegistryKey; +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().getLevel(World.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 (RegistryKey type : java.util.Arrays.asList(World.OVERWORLD, World.NETHER, World.END)) { + ServerWorld world = event.getServer().getLevel(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 == World.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 == World.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(type.location().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().halt(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.Mutable pos = new BlockPos.Mutable(); + 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.set(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.dimension().location()); + 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/port116/generation-probe/resources/META-INF/mods.toml b/tools/validation/port116/generation-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..56ce13f --- /dev/null +++ b/tools/validation/port116/generation-probe/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +loaderVersion="[36,)" +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.116051,)" +ordering="AFTER" +side="SERVER" diff --git a/tools/validation/port116/generation-probe/resources/pack.mcmeta b/tools/validation/port116/generation-probe/resources/pack.mcmeta new file mode 100644 index 0000000..dc2753e --- /dev/null +++ b/tools/validation/port116/generation-probe/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 6, + "description": "Disposable qualification probe" + } +} diff --git a/tools/validation/port116/mining-probe/java/test/MineralMiningProbe.java b/tools/validation/port116/mining-probe/java/test/MineralMiningProbe.java new file mode 100644 index 0000000..239c21e --- /dev/null +++ b/tools/validation/port116/mining-probe/java/test/MineralMiningProbe.java @@ -0,0 +1,371 @@ +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.World; +import net.minecraft.util.RegistryKey; +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.loot.*; +import net.minecraft.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().getLevel(World.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.gameMode.setGameModeForPlayer(GameType.SURVIVAL); + player.setOnGround(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.enchant(Enchantments.BLOCK_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.defaultBlockState(); + 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.ORIGIN, net.minecraft.util.math.vector.Vector3d.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.create(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.ORIGIN, net.minecraft.util.math.vector.Vector3d.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.enchant(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.defaultBlockState(), 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).defaultBlockState().getLightEmission() == 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.getDamageValue() == 1, + owner + " hammer yielded " + count + " " + mineral + " powders, damage " + hammer.getDamageValue()); + } + 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.getDamageValue() == 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().halt(false); + } + } + } + + private void blockProperties(Block block, float hardness, float resistance, int harvestLevel, boolean beacon) { + BlockState state = block.defaultBlockState(); + check(state.getDestroySpeed(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(state.is(net.minecraft.tags.BlockTags.BEACON_BASE_BLOCKS) == 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.TRADES.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.getResult().getItem() != item(material + "_ingot")) continue; + matches++; + check(offer.getResult().getCount() == 1 && offer.getBaseCostA().getItem() == Items.EMERALD + && offer.getBaseCostA().getCount() >= 4 && offer.getBaseCostA().getCount() <= 5 + && offer.getMaxUses() == 12 && offer.getXp() == 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.setItem(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.getResultItem(); + check(result.getItem() == item(output) && result.getCount() == 1, input + " smelts to " + result); + check(((AbstractCookingRecipe) recipe).getExperience() == xp, input + " changed cooking XP"); + check(((AbstractCookingRecipe) recipe).getCookingTime() == ticks, input + " changed cooking time"); + } + } + + private void crusher(String input, String output, int count, boolean enabled) { + Inventory inventory = new Inventory(1); + inventory.setItem(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.getResultItem().getItem() == item(output) && recipe.getResultItem().getCount() == count, + input + " crushes to " + recipe.getResultItem()); + } + } + + 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.is(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.setBlock(pos.offset(x, -1, z), net.minecraft.block.Blocks.STONE.defaultBlockState(), 2); + world.setBlock(pos.offset(x, 0, z), net.minecraft.block.Blocks.AIR.defaultBlockState(), 2); + } + check(bucket.emptyBucket(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.FluidState adjacent = world.getFluidState(pos.relative(side)); + if (fluid.isSame(adjacent.getType()) && !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.setPos(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5); + float health = creature.getHealth(); + block(material).entityInside(world.getBlockState(pos), world, pos, creature); + check(creature.getHealth() == health && !creature.isOnFire(), "Molten heat escaped its surface " + material); + creature.setPos(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5); + block(material).entityInside(world.getBlockState(pos), world, pos, creature); + check(creature.getHealth() == health - 4.0F && creature.isOnFire(), + "Molten contact lost heat " + material + " health=" + creature.getHealth() + " burning=" + creature.isOnFire()); + creature.remove(); + net.minecraft.fluid.Fluid picked = ((net.minecraft.block.IBucketPickupHandler) block(material)) + .takeLiquid(world, pos, world.getBlockState(pos)); + check(picked == fluid && world.isEmptyBlock(pos) && picked.getBucket() == 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).inflate(0.45); + world.getEntitiesOfClass(ItemEntity.class, area).forEach(ItemEntity::remove); + world.setBlock(pos, block.defaultBlockState(), 3); + player.setItemInHand(Hand.MAIN_HAND, tool); + if (normalDigging) { + player.setPos(pos.getX() + 0.5D, pos.getY(), pos.getZ() + 2.5D); + player.setOnGround(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.getDestroyProgress(player, world, pos); + int ticks = progress > 0 ? (int) Math.ceil(1.0F / progress) : 400; + int expectedTicks = (int) Math.ceil(state.getDestroySpeed(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.gameMode.handleBlockBreakAction(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.gameMode.tick(); + player.gameMode.handleBlockBreakAction(pos, net.minecraft.network.play.client.CPlayerDiggingPacket.Action.STOP_DESTROY_BLOCK, + net.minecraft.util.Direction.UP, 256); + check(world.isEmptyBlock(pos), "Normal digging did not remove " + block.getRegistryName()); + } else player.gameMode.destroyBlock(pos); + int count = 0; + for (ItemEntity drop : world.getEntitiesOfClass(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/port116/mining-probe/resources/META-INF/mods.toml b/tools/validation/port116/mining-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..de7a4cc --- /dev/null +++ b/tools/validation/port116/mining-probe/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +license="LGPL-2.1" +loaderVersion="[25,)" +[[mods]] +modId="mineralminingprobe" +version="1" +displayName="Base Minerals mining checks" +[[dependencies.mineralminingprobe]] +modId="baseminerals" +mandatory=true +versionRange="[2.5.1.116051,)" +ordering="AFTER" +side="BOTH" diff --git a/tools/validation/port116/mining-probe/resources/pack.mcmeta b/tools/validation/port116/mining-probe/resources/pack.mcmeta new file mode 100644 index 0000000..dc2753e --- /dev/null +++ b/tools/validation/port116/mining-probe/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 6, + "description": "Disposable qualification probe" + } +} diff --git a/tools/validation/port116/requirements.txt b/tools/validation/port116/requirements.txt new file mode 100644 index 0000000..96972e7 --- /dev/null +++ b/tools/validation/port116/requirements.txt @@ -0,0 +1 @@ +nbtlib==2.0.4 diff --git a/tools/validation/port116/run_forge.py b/tools/validation/port116/run_forge.py new file mode 100644 index 0000000..c61597a --- /dev/null +++ b/tools/validation/port116/run_forge.py @@ -0,0 +1,166 @@ +"""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 re +import shutil +import subprocess +import threading +import time + +LAUNCHER = 'forge-1.16.5-36.2.34.jar' + + +def audit_missing_content(text): + """Forge 36 can continue without a prompt; still reject unknown missing IDs.""" + allowed = { + 'minecraft:block': {'minecraft:sign', 'minecraft:wall_sign'}, + 'minecraft:item': {'minecraft:sign', 'minecraft:rose_red', 'minecraft:cactus_green', + 'minecraft:dandelion_yellow', 'minecraft:zombie_pigman_spawn_egg'}, + 'minecraft:entity_type': {'minecraft:zombie_pigman'}, + 'minecraft:memory_module_type': {'minecraft:golem_last_seen_time', 'minecraft:opened_doors'}, + 'minecraft:sound_event': {'minecraft:entity.zombie_pigman.' + suffix for suffix in + ['ambient', 'angry', 'death', 'hurt']} | {'minecraft:music.nether'}, + } + registries = {'minecraft:biome', 'minecraft:biomes', 'minecraft:villagerprofessions'} + lines = re.sub(r'\x1b\[[0-9;]*m', '', text).splitlines() + receipt = [] + for i, line in enumerate(lines): + if 'Unidentified mapping from registry ' in line: + registry = line.split('Unidentified mapping from registry ', 1)[1].strip() + names = [] + for following in lines[i+1:]: + match = re.fullmatch(r'\s*(\S+): \d+\s*', following) + if not match: + break + names.append(match[1]) + assert registry in allowed and names and set(names) <= allowed[registry], (registry, names) + receipt.append(dict(registry=registry, names=names)) + elif 'GameData/REGISTRIES' in line and 'Missing Registries:' in line: + names = [] + for following in lines[i+1:]: + name = following.strip() + if not re.fullmatch(r'[a-z0-9_.-]+:[a-z0-9_/.-]+', name): + break + names.append(name) + assert names and set(names) <= registries, names + receipt.append(dict(missing_registries=names)) + return receipt + + +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 or "Confirm with '/fml confirm'" in line: + prompt = '\n'.join(query_lines[-48:]) + # Only the retired vanilla registry and the six vanilla + # sign/dye renames are expected when Forge 36 opens old saves. + # Never blanket-confirm unknown mod content. + names = sorted(s for s in query_lines[-48:] 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)) + query_lines.clear() + 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') + (target / (phase + '-missing-content-audit.json')).write_text( + json.dumps(audit_missing_content(text), indent=2)) + 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/port116/test_missing_content.py b/tools/validation/port116/test_missing_content.py new file mode 100644 index 0000000..7181f88 --- /dev/null +++ b/tools/validation/port116/test_missing_content.py @@ -0,0 +1,22 @@ +import unittest +from run_forge import audit_missing_content + + +class MissingContentTest(unittest.TestCase): + def test_native_vanilla_renames_are_audited_without_a_prompt(self): + log = '[main/ERROR] [ne.mi.re.GameData/REGISTRIES]: Unidentified mapping from registry minecraft:item\n\tminecraft:zombie_pigman_spawn_egg: 754\n\n' + self.assertEqual(['minecraft:zombie_pigman_spawn_egg'], audit_missing_content(log)[0]['names']) + + def test_mod_content_in_a_vanilla_registry_is_rejected(self): + log = '[main/ERROR] [ne.mi.re.GameData/REGISTRIES]: Unidentified mapping from registry minecraft:item\n\tbaseminerals:salt_ore: 754\n\n' + with self.assertRaises(AssertionError): + audit_missing_content(log) + + def test_unknown_removed_registries_are_rejected(self): + log = '[main/WARN] [ne.mi.re.GameData/REGISTRIES]: Missing Registries:\nothermod:materials\n\n' + with self.assertRaises(AssertionError): + audit_missing_content(log) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/validation/port116/test_palette_decoder.py b/tools/validation/port116/test_palette_decoder.py new file mode 100644 index 0000000..c350f6f --- /dev/null +++ b/tools/validation/port116/test_palette_decoder.py @@ -0,0 +1,34 @@ +"""Cross-boundary palette fixtures for the 1.16 BitStorageAlignFix transition.""" +import unittest +from nbtlib import LongArray +from verify_upgrade import flattened_section + + +class PaletteDecoderTest(unittest.TestCase): + def test_compact_and_aligned_five_through_nine_bit_palettes(self): + for bits in range(5, 10): + palette = [{'Name': 'minecraft:stone'} for _ in range(1 << bits)] + palette[1] = {'Name': 'baseminerals:salt_ore'} + palette[-1] = {'Name': 'baseminerals:lithium', 'Properties': {'level': '7'}} + values = [1 if i % 13 == 12 else (len(palette)-1 if i % 37 == 9 else 0) + for i in range(4096)] + expected = [(i, palette[v]['Name'], (('level', '7'),) if v == len(palette)-1 else ()) + for i, v in enumerate(values) if v] + for aligned, version in [(False, 2526), (True, 2527), (True, 2586)]: + # Build each wire-format word from a reversed bit string. The oracle + # above uses logical entries, independent of the production decoder. + batches = [values[i:i + 64//bits] for i in range(0, 4096, 64//bits)] if aligned else [values] + words = [] + for batch in batches: + packed = ''.join(format(value, '0%db' % bits) for value in reversed(batch)) + integer = int(packed, 2) + for shift in range(0, len(batch) * bits, 64): + word = (integer >> shift) & ((1 << 64)-1) + words.append(word if word < (1 << 63) else word - (1 << 64)) + section = {'Palette': palette, 'BlockStates': LongArray(words)} + with self.subTest(bits=bits, data_version=version): + self.assertEqual(expected, list(flattened_section(section, version))) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/validation/port116/verify_census.py b/tools/validation/port116/verify_census.py new file mode 100644 index 0000000..3df2c78 --- /dev/null +++ b/tools/validation/port116/verify_census.py @@ -0,0 +1,75 @@ +"""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 empty 1.15.2 save is upgraded by vanilla DFU before any + # chunks are generated. This retains exact seed zero on the native 1.16 engine. + 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(2230), '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(2230), 'Name': String('1.15.2'), '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/port116/verify_client.py b/tools/validation/port116/verify_client.py new file mode 100644 index 0000000..fad1f4d --- /dev/null +++ b/tools/validation/port116/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.116051.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/port116/verify_generation.py b/tools/validation/port116/verify_generation.py new file mode 100644 index 0000000..5828763 --- /dev/null +++ b/tools/validation/port116/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/port116/verify_mining.py b/tools/validation/port116/verify_mining.py new file mode 100644 index 0000000..a41c9a7 --- /dev/null +++ b/tools/validation/port116/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/port116/verify_named_upgrade.py b/tools/validation/port116/verify_named_upgrade.py new file mode 100644 index 0000000..96068c9 --- /dev/null +++ b/tools/validation/port116/verify_named_upgrade.py @@ -0,0 +1,37 @@ +"""Check an already flattened source 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/port116/verify_upgrade.py b/tools/validation/port116/verify_upgrade.py new file mode 100644 index 0000000..bee8107 --- /dev/null +++ b/tools/validation/port116/verify_upgrade.py @@ -0,0 +1,280 @@ +"""Check mineral states and tagged inventories across the real Forge 1.16.5 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, data_version=2230): + 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): + if data_version >= 2527: + # Vanilla BitStorageAlignFix (2527): entries no longer cross long boundaries. + word, entry = divmod(index, 64 // bits) + shift = entry * bits + else: + 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)) >= 2586, f'Chunk did not reach 1.16.5: {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, int(root.get('DataVersion', -1))) + 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()