From 08d48a9fb57cde10ab35eca86970ee1eccd04190 Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Tue, 24 Nov 2026 17:39:32 +0000 Subject: [PATCH] Bring Base Minerals to Minecraft 1.15.2 --- .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 | 8 + README.md | 19 +- build.gradle | 34 +- docs/BUILDING.md | 66 +--- docs/KNOWN_ISSUES.md | 15 +- docs/MANUAL_TESTING.md | 14 +- docs/PORTING_115.md | 42 ++ docs/RELEASING.md | 17 +- docs/WORLD_UPGRADES.md | 12 +- gradle.properties | 10 +- ...ty-114.gradle => compatibility-115.gradle} | 12 +- gradle/dependencies.json | 12 +- ...114.gradle => local-companions-115.gradle} | 4 +- ...{release-114.gradle => release-115.gradle} | 29 +- .../client/MineralFluidRenderer.java | 15 + .../baseminerals/content/MineralContent.java | 5 - .../content/MoltenMineralBlock.java | 2 +- .../content/MoltenMineralFluid.java | 5 +- src/main/resources/META-INF/mods.toml | 10 +- .../baseminerals_legacy_world_upgrade.js | 41 +- src/main/resources/pack.mcmeta | 2 +- ...114_resources.js => test_115_resources.js} | 0 .../port115/ParseEclipseArguments.java | 27 ++ .../java/test/MineralClientProbe.java | 251 ++++++++++++ .../client-probe/resources/META-INF/mods.toml | 13 + .../client-probe/resources/pack.mcmeta | 6 + .../java/test/MineralGenerationProbe.java | 115 ++++++ .../resources/META-INF/mods.toml | 13 + .../generation-probe/resources/pack.mcmeta | 6 + .../java/test/MineralMiningProbe.java | 370 ++++++++++++++++++ .../mining-probe/resources/META-INF/mods.toml | 12 + .../mining-probe/resources/pack.mcmeta | 6 + tools/validation/port115/requirements.txt | 1 + tools/validation/port115/run_forge.py | 126 ++++++ tools/validation/port115/verify_census.py | 74 ++++ tools/validation/port115/verify_client.py | 67 ++++ tools/validation/port115/verify_generation.py | 41 ++ tools/validation/port115/verify_mining.py | 39 ++ .../port115/verify_named_upgrade.py | 37 ++ tools/validation/port115/verify_upgrade.py | 275 +++++++++++++ 45 files changed, 1715 insertions(+), 202 deletions(-) create mode 100644 docs/PORTING_115.md rename gradle/{compatibility-114.gradle => compatibility-115.gradle} (92%) rename gradle/{local-companions-114.gradle => local-companions-115.gradle} (92%) rename gradle/{release-114.gradle => release-115.gradle} (93%) rename tools/{test_114_resources.js => test_115_resources.js} (100%) create mode 100644 tools/validation/port115/ParseEclipseArguments.java create mode 100644 tools/validation/port115/client-probe/java/test/MineralClientProbe.java create mode 100644 tools/validation/port115/client-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port115/client-probe/resources/pack.mcmeta create mode 100644 tools/validation/port115/generation-probe/java/test/MineralGenerationProbe.java create mode 100644 tools/validation/port115/generation-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port115/generation-probe/resources/pack.mcmeta create mode 100644 tools/validation/port115/mining-probe/java/test/MineralMiningProbe.java create mode 100644 tools/validation/port115/mining-probe/resources/META-INF/mods.toml create mode 100644 tools/validation/port115/mining-probe/resources/pack.mcmeta create mode 100644 tools/validation/port115/requirements.txt create mode 100644 tools/validation/port115/run_forge.py create mode 100644 tools/validation/port115/verify_census.py create mode 100644 tools/validation/port115/verify_client.py create mode 100644 tools/validation/port115/verify_generation.py create mode 100644 tools/validation/port115/verify_mining.py create mode 100644 tools/validation/port115/verify_named_upgrade.py create mode 100644 tools/validation/port115/verify_upgrade.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ce513f..eed1ad0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,16 +1,16 @@ -name: Base Minerals 1.14.4 CI +name: Base Minerals 1.15.2 CI on: push: - branches: [master-1.14.4, 'feature/**'] + branches: [master-1.15.2, 'feature/**'] pull_request: - branches: [master-1.14.4] + branches: [master-1.15.2] permissions: contents: read concurrency: - group: baseminerals-114-${{ github.workflow }}-${{ github.ref }} + group: baseminerals-115-${{ 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 verify114ReleaseArtifacts write114ReleaseChecksums genEclipseRuns eclipse \ + bash ./gradlew clean check build javadoc verify115ReleaseArtifacts write115ReleaseChecksums 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.14.4-${{ github.sha }} + name: BaseMinerals-1.15.2-${{ 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.14.4-diagnostics-${{ github.sha }} + name: BaseMinerals-1.15.2-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 e91eb28..d6e92c3 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -3,11 +3,11 @@ name: CodeQL on: push: branches: - - master-1.14.4 - - feature/baseminerals-1.14.4 + - master-1.15.2 + - feature/baseminerals-1.15.2 pull_request: branches: - - master-1.14.4 + - master-1.15.2 schedule: - cron: '47 7 * * 4' diff --git a/.github/workflows/deploy-release.yml b/.github/workflows/deploy-release.yml index 51dd0c8..5b43bad 100644 --- a/.github/workflows/deploy-release.yml +++ b/.github/workflows/deploy-release.yml @@ -1,15 +1,15 @@ -name: Release Base Minerals 1.14.4 +name: Release Base Minerals 1.15.2 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.14.4 + description: Four-part version for Minecraft 1.15.2 required: true type: string release_commit: - description: Full SHA of the checked MMD master-1.14.4 commit + description: Full SHA of the checked MMD master-1.15.2 commit required: true type: string tested_jar_sha256: @@ -33,13 +33,13 @@ permissions: contents: read concurrency: - group: baseminerals-release-114 + group: baseminerals-release-115 cancel-in-progress: false jobs: qualify: name: Verify merged CI candidate - if: github.repository == 'MinecraftModDevelopmentMods/BaseMinerals' && github.ref == 'refs/heads/master-1.14.4' + if: github.repository == 'MinecraftModDevelopmentMods/BaseMinerals' && github.ref == 'refs/heads/master-1.15.2' 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]+\.114041$ ]] + [[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.115021$ ]] [[ "$RELEASE_SHA" =~ ^[[:xdigit:]]{40}$ ]] [[ "$TESTED_SHA" =~ ^[[:xdigit:]]{64}$ ]] test "$(git rev-parse HEAD)" = "$RELEASE_SHA" - test "$(gh api "repos/$GITHUB_REPOSITORY/branches/master-1.14.4" --jq .commit.sha)" = "$RELEASE_SHA" + test "$(gh api "repos/$GITHUB_REPOSITORY/branches/master-1.15.2" --jq .commit.sha)" = "$RELEASE_SHA" grep -Fxq "mod_version=$RELEASE_VERSION" gradle.properties - grep -Fxq 'minecraft_version=1.14.4' gradle.properties + grep -Fxq 'minecraft_version=1.15.2' gradle.properties ci_run="$(gh api --method GET "repos/$GITHUB_REPOSITORY/actions/workflows/ci.yml/runs" \ - -f branch=master-1.14.4 -f head_sha="$RELEASE_SHA" -f event=push -f status=success \ + -f branch=master-1.15.2 -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.14.4-${{ inputs.release_commit }} + name: BaseMinerals-1.15.2-${{ 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.14.4-${{ inputs.release_commit }} + name: BaseMinerals-1.15.2-${{ 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.14.4-${{ inputs.release_commit }} + name: BaseMinerals-1.15.2-${{ 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.14.4 (Forge) + name: Base Minerals ${{ inputs.release_version }} for Minecraft 1.15.2 (Forge) version: ${{ inputs.release_version }} version-type: ${{ inputs.curseforge_release_level }} changelog-file: ${{ runner.temp }}/release-input/CHANGELOG.txt loaders: forge - game-versions: '1.14.4' + game-versions: '1.15.2' 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.14.4-${{ inputs.release_commit }} + name: BaseMinerals-1.15.2-${{ 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.14.4 (Forge)" \ + --title "Base Minerals $RELEASE_VERSION for Minecraft 1.15.2 (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 a935640..a2585db 100644 --- a/.github/workflows/release-on-tag.yml +++ b/.github/workflows/release-on-tag.yml @@ -1,7 +1,7 @@ -name: Validate Base Minerals 1.14.4 tag +name: Validate Base Minerals 1.15.2 tag on: push: - tags: ['*.*.*.114041'] + tags: ['*.*.*.115021'] 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.14.4' gradle.properties + grep -Fxq 'minecraft_version=1.15.2' 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 cf7fcd4..c1907e0 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.14.4 - - feature/baseminerals-1.14.4 + - master-1.15.2 + - feature/baseminerals-1.15.2 pull_request: branches: - - master-1.14.4 + - master-1.15.2 permissions: contents: read diff --git a/CHANGELOG.txt b/CHANGELOG.txt index e717c0a..38b4ba3 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,11 @@ +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. + +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. + 2.5.2.114041 for Minecraft 1.14.4 This brings the released 1.13.2 build across to Forge 28, using OreSpawn 4.1.7.114041. The mineral IDs, ore depths and deposit shapes stay the same, and saved ore settings carry forward. diff --git a/README.md b/README.md index 0f99699..9454171 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,16 @@ 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.14.4 and Forge 28.2.26. Install -[OreSpawn 4.1.7.114041](https://github.com/MinecraftModDevelopmentMods/OreSpawn/releases/tag/4.1.7.114041). -[Base Metals 3.0.2.114041](https://github.com/MinecraftModDevelopmentMods/BaseMetals/releases/tag/3.0.2.114041) +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.2.114041 or a later compatible 1.14.4 build when installing the two together. +Use 3.0.3.115021 or a later compatible 1.15.2 build when installing the two together. Base Minerals shares its ore crushing recipes with Base Metals when installed. -If Base Metals is absent, -[Modern Metals 3.0.0.114041](https://github.com/MinecraftModDevelopmentMods/ModernMetals/releases/tag/3.0.0.114041) -crackhammers can crush the ores instead. Both metal mods remain optional. +[Modern Metals 3.0.0.115021](https://github.com/MinecraftModDevelopmentMods/ModernMetals/releases/tag/3.0.0.115021) +also supplies shared crushing when installed. Mining lithium returns one ore block. Niter, phosphorus, potash, salt, saltpeter and sulfur drop 2–4 powders, with Fortune increasing the upper @@ -27,9 +26,9 @@ are available from level-two armorers, toolsmiths and weaponsmiths. ## Upgrading a world -Copy the whole save folder before opening it on 1.14.4, including level.dat +Copy the whole save folder before opening it on 1.15.2, including level.dat and serverconfig. Start the copy with Forge, Base Minerals, OreSpawn and the -1.14.4 versions of any other mods whose content it uses. Check existing blocks +1.15.2 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 @@ -39,5 +38,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_114.md) +[upgrade checks](docs/WORLD_UPGRADES.md), [port decisions](docs/PORTING_115.md) and [known limits](docs/KNOWN_ISSUES.md). diff --git a/build.gradle b/build.gradle index 6c965c2..7cb086a 100644 --- a/build.gradle +++ b/build.gradle @@ -40,7 +40,7 @@ def stageRunClasses = tasks.register('stageRunClasses', Sync) { } minecraft { - mappings channel: 'snapshot', version: '20190719-1.14.3' + mappings channel: 'snapshot', version: '20200514-1.15.1' 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.14.4' - environment 'MCP_VERSION', '20190829.143755' - environment 'MCP_MAPPINGS', 'snapshot_20190719-1.14.3' - environment 'FORGE_VERSION', '28.2.26' + 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 'FORGE_GROUP', 'net.minecraftforge' def path = modClasses.get().asFile.absolutePath environment 'MOD_CLASSES', "baseminerals%%${path}${File.pathSeparator}baseminerals%%${path}" @@ -95,7 +95,7 @@ configurations { pinnedMods { canBeConsumed = false; transitive = false } } dependencies { - implementation minecraft.dependency('net.minecraftforge:forge:1.14.4-28.2.26') + implementation minecraft.dependency('net.minecraftforge:forge:1.15.2-31.2.57') specs.each { spec -> pinnedMods spec.coordinate if (spec.runtime) implementation renamer.dependency(spec.coordinate) @@ -143,18 +143,18 @@ tasks.named('test') { useJUnitPlatform() } sourceSets { generationProbe { - java.srcDirs = ['tools/validation/port114/generation-probe/java'] - resources.srcDirs = ['tools/validation/port114/generation-probe/resources'] + java.srcDirs = ['tools/validation/port115/generation-probe/java'] + resources.srcDirs = ['tools/validation/port115/generation-probe/resources'] compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath } clientProbe { - java.srcDirs = ['tools/validation/port114/client-probe/java'] - resources.srcDirs = ['tools/validation/port114/client-probe/resources'] + java.srcDirs = ['tools/validation/port115/client-probe/java'] + resources.srcDirs = ['tools/validation/port115/client-probe/resources'] compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath } miningProbe { - java.srcDirs = ['tools/validation/port114/mining-probe/java'] - resources.srcDirs = ['tools/validation/port114/mining-probe/resources'] + java.srcDirs = ['tools/validation/port115/mining-probe/java'] + resources.srcDirs = ['tools/validation/port115/mining-probe/resources'] compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath } } @@ -198,11 +198,11 @@ tasks.register('verifyStartupRegistration', Exec) { commandLine 'node', '--test', 'tools/test_fluid_registration.js' } tasks.named('check') { dependsOn 'verifyStartupRegistration' } -tasks.register('verify114Resources', Exec) { +tasks.register('verify115Resources', Exec) { group = 'verification' - commandLine 'node', '--test', 'tools/test_114_resources.js' + commandLine 'node', '--test', 'tools/test_115_resources.js' } -tasks.named('check') { dependsOn 'verify114Resources' } +tasks.named('check') { dependsOn 'verify115Resources' } ['client', 'server'].each { run -> tasks.matching { it.name == 'run' + run.capitalize() }.configureEach { dependsOn stageRunClasses @@ -269,8 +269,8 @@ tasks.named('processResources', ProcessResources) { apply from: 'gradle/ore-models.gradle' -apply from: 'gradle/release-114.gradle' +apply from: 'gradle/release-115.gradle' apply from: 'gradle/normalize-javadoc-trees.gradle' -apply from: 'gradle/compatibility-114.gradle' +apply from: 'gradle/compatibility-115.gradle' diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 2a2c9b8..35862c4 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -1,78 +1,54 @@ -# Building Base Minerals 1.14.4 +# Building Base Minerals 1.15.2 Use Java 17 for Gradle, Java 25 for Mavenizer, and Java 8 for compilation and Minecraft. The wrapper uses Gradle 9.6.1, ForgeGradle 7.0.34 and Renamer 1.1.5. -The target is Forge 28.2.26 with MCP snapshot 20190719-1.14.3 and MCP config -20190829.143755. +The target is Forge 31.2.57 with MCP snapshot 20200514-1.15.1 and MCP config +20200515.085601. Select one Gradle cache for Eclipse and the terminal. Stage the checksum-pinned -public OreSpawn 4.1.7.114041, Base Metals 3.0.2.114041 and Modern Metals -3.0.0.114041 jars, then build with Java 17 as JAVA_HOME. Both metal mods remain -optional when playing. +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. ```powershell python gradle/stage-legacy-dependencies.py .gradle/legacy-dependencies -.\gradlew.bat check build javadoc verify114ReleaseArtifacts genEclipseRuns eclipse +.\gradlew.bat check build javadoc verify115ReleaseArtifacts genEclipseRuns eclipse ``` Set org.gradle.java.installations.paths to the three JDK directories when toolchain discovery is disabled. In this workspace GRADLE_USER_HOME is D:/BaseMetals/.gradle-verify-cache. Add --offline to rebuild from the same cache. -The player jar is build/libs/BaseMinerals-2.5.2.114041.jar. Development output +The player jar is build/libs/BaseMinerals-2.5.2.115021.jar. Development output is under build/libs-dev; sources and Javadocs are separate. Import the inner checkout as an Eclipse Gradle project. The generated client and server launches use Java 8 and staged main output. Gradle refresh preserves -quoted paths for directories containing spaces. Use runClient.launch alone, -runClientWithBaseMetals.launch, runClientWithModernMetals.launch or -runClientWithBoth.launch. The four profiles use separate run directories and -the pinned public metal jars by default. Terminal runClient accepts --PwithBaseMetals=true and -PwithModernMetals=true. +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. -To test the current local Base Metals and Modern Metals fixes, build those -sibling checkouts, then run these as separate commands: - -```powershell -.\gradlew.bat pinLocalCompanions -.\gradlew.bat check genEclipseRuns eclipse -``` - -The ignored local-basemetals.json and local-modernmetals.json files pin both -player and mapped jars by SHA-256. Gradle checks the source hashes and the exact -copies staged in each profile. Old managed companion copies are retained under -.gradle/retired-compatibility-jars; worlds, settings and unrelated mods are kept. -After rebuilding either sibling, repin it with pinLocalBaseMetals or -pinLocalModernMetals, then regenerate the launches. - -With the local pins present, runClientWithBaseMetals.launch and -runClientWithBoth.launch load the fixed local Base Metals build. The latter -also loads the pinned local Modern Metals build. runClientWithModernMetals.launch -uses Modern Metals alone. Terminal runClient accepts -PwithBaseMetals=true and --PwithModernMetals=true. Use -PuseLocalBaseMetals=false to test the published -Base Metals baseline. Release builds (-PreleaseBuild=true) select published -dependencies and reject explicitly enabled local overrides. +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. ## Local gameplay checks -The tools under tools/validation/port114 use an independently installed -Forge 1.14.4-28.2.26 server directory containing its launcher and libraries. -Install tools/validation/port114/requirements.txt for the Anvil/NBT checks. +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/port114/verify_mining.py --help -python tools/validation/port114/verify_census.py --help -python tools/validation/port114/verify_upgrade.py --help -python tools/validation/port114/verify_named_upgrade.py --help -python tools/validation/port114/verify_client.py --help +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 Base Metals, with Modern Metals and -with both. Hammer checks use the native start/tick/stop digging path and assert +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. diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 7f5eca7..9d8be75 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -1,20 +1,11 @@ -# Known limits for Minecraft 1.14.4 +# Known limits for Minecraft 1.15.2 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 28. +The 1.12 Tinkers' Construct integration does not carry over to Forge 31. -Modern Metals 1.14 is currently tested using a frozen local candidate. Its -compatibility launch is available after staging that fixture; this does not -make Modern Metals a published or required dependency. - -The development profiles also pin the locally fixed Base Metals bars and ore -overlays. That jar has the same version as the published build but a different -hash. Publish those companion fixes and update the public pins before treating -the local combined profile as release-dependency qualification. - -OreSpawn 4.1.7.114041 writes empty dimensions or dimension_selectors objects +OreSpawn 4.1.7.115021 writes empty dimensions or dimension_selectors objects for some vanilla and companion-mod rules. Its published JSON schema rejects those empty objects, although the engine loads and runs them. The Base Minerals rules validate against that schema. This needs an OreSpawn serialization/schema diff --git a/docs/MANUAL_TESTING.md b/docs/MANUAL_TESTING.md index 9ac064e..22e5fb9 100644 --- a/docs/MANUAL_TESTING.md +++ b/docs/MANUAL_TESTING.md @@ -1,11 +1,11 @@ -# Manual testing on 1.14.4 +# Manual testing on 1.15.2 Refresh the inner BaseMinerals Gradle project in Eclipse. Start with -runClientWithBoth.launch to load the pinned local Base Metals and Modern Metals -fixes. Run pinLocalCompanions and regenerate launches after rebuilding those -siblings. runClient.launch is standalone; -runClientWithBaseMetals.launch and runClientWithModernMetals.launch test the -two companions separately. Each profile has its own run directory. +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. 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 Forge 25 vanilla-registry prompts. + expected vanilla-registry prompts when Forge 31 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 new file mode 100644 index 0000000..fcae612 --- /dev/null +++ b/docs/PORTING_115.md @@ -0,0 +1,42 @@ +# Minecraft 1.15.2 port + +The baseline is released Base Minerals 2.5.2.114041, MMD merge e30ddcb. +The target is 2.5.2.115021, Forge 31.2.57, MCP snapshot 20200514-1.15.1 +(config 20200515.085601), Java 8. Gradle 9.6.1/ForgeGradle 7.0.34, +Renamer 1.1.5 and Foojay 1.0.0 remain; Gradle uses Java 17 and Mavenizer Java 25. + +## Decisions + +- Keep all 17 block, 41 item and four fluid IDs, native recipes/loot, translations, + bucket identities, material properties and the exact Fortune powder formula. + Keep the seven ore defaults and their stable OreSpawn rule/material/channel + IDs. No new minerals, terrain, retrogen, equipment or content-mode policy. +- Retain the additive hammer whitelist contributions and canonical Forge tags. + Qualification must exercise normal mining progress and actual client/server + removal, drops and durability, including salt with the iron Crack Hammer. +- Register ore and molten render layers in client setup through Forge 31's + RenderTypeLookup. Keep the overlays, native fluid attributes, bucket layers + and colour handlers. Resource pack format is 5. No Forge blockstate extension + or legacy render-layer method is carried forward. +- Forge 31's ChunkLoader owns an IOWorker instead of extending RegionFileCache. + Capture that loader's constructor directory in its own injected field/getter + and use it to locate the world-specific numeric mineral registry during data + 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 + 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 + pin support, but qualify the currently available standalone/Base Metals paths. +- The existing material-settings screen and Tinkers limitations remain. This + port does not introduce substitutes for integrations absent on the target. + +References: [Forge 1.15 porting notes](https://docs.minecraftforge.net/en/1.15.x/legacy/porting/), +the [linked rendering primer](https://gist.github.com/williewillus/30d7e3f775fe93c503bddf054ef3f93e), +[Minecraft 1.15.2 release notes](https://www.minecraft.net/en-us/article/minecraft-java-edition-1-15-2), +the exact mapped Forge 31.2.57 classes, and +[OreSpawn's public 4.1.7.115021 release](https://github.com/MinecraftModDevelopmentMods/OreSpawn/releases/tag/4.1.7.115021). + +The local receipt records the tested artifact hashes, actual gates and any +remaining limits. Manual acceptance and publication are separate steps. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index a68ffd0..7181919 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,18 +1,18 @@ -# Releasing Base Minerals for Minecraft 1.14.4 +# Releasing Base Minerals for Minecraft 1.15.2 Build with Java 17, Temurin 8u502-b07 for compilation and Java 25 for -Mavenizer. Run check, build, verify114ReleaseArtifacts, -write114ReleaseChecksums, genEclipseRuns and eclipse. Keep the packaged +Mavenizer. Run check, build, verify115ReleaseArtifacts, +write115ReleaseChecksums, genEclipseRuns and eclipse. Keep the packaged gameplay and saved-world checks local, then complete manual testing. -The new master-1.14.4 branch needs to be established on MMD before opening its +The new master-1.15.2 branch needs to be established on MMD before opening its first port PR. After manual acceptance, open a PR from the fork to that branch. After merging, wait for the successful push CI run and download -BaseMinerals-1.14.4-. Compare +BaseMinerals-1.15.2-. 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.14.4 with the release version, full merged +Run deploy-release.yml on master-1.15.2 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,5 +27,6 @@ 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.14.4 release. The local Modern -Metals fixture must not be uploaded or bundled with Base Minerals. +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. diff --git a/docs/WORLD_UPGRADES.md b/docs/WORLD_UPGRADES.md index 2c5ac21..8eb814e 100644 --- a/docs/WORLD_UPGRADES.md +++ b/docs/WORLD_UPGRADES.md @@ -1,4 +1,4 @@ -# Base Minerals 1.14.4 upgrade checks +# Base Minerals 1.15.2 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,13 @@ 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.14.4 format -(DataVersion 1976 or later). Already flattened 1.13.2 saves are checked with +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 the separate named-world runner, including their inventories and saved rules. - python tools/validation/port114/verify_upgrade.py --java --runtime --source --output --mods [basemetals.jar] + python tools/validation/port115/verify_upgrade.py --java --runtime --source --output --mods [basemetals.jar] -Use verify_named_upgrade.py with the same arguments for a 1.13.2 source. It +Use verify_named_upgrade.py with the same arguments for a 1.13.2 or 1.14.4 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,7 +33,7 @@ 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 28 may ask for confirmation when opening a Forge 25 world because the +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. diff --git a/gradle.properties b/gradle.properties index 450a2e9..003d3ba 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.14.4 -forge_version=28.2.26 -mod_version=2.5.2.114041 +minecraft_version=1.15.2 +forge_version=31.2.57 +mod_version=2.5.2.115021 -basemetals_version=3.0.2.114041 -modernmetals_version=3.0.0.114041 +basemetals_version=3.0.3.115021 +modernmetals_version=3.0.0.115021 diff --git a/gradle/compatibility-114.gradle b/gradle/compatibility-115.gradle similarity index 92% rename from gradle/compatibility-114.gradle rename to gradle/compatibility-115.gradle index b7d02d2..b0ec0b3 100644 --- a/gradle/compatibility-114.gradle +++ b/gradle/compatibility-115.gradle @@ -2,7 +2,7 @@ import groovy.xml.XmlParser import groovy.xml.XmlUtil import java.security.MessageDigest -apply from: 'gradle/local-companions-114.gradle' +apply from: 'gradle/local-companions-115.gradle' def basePin = localCompanionPins.basemetals def modernPin = localCompanionPins.modernmetals @@ -12,7 +12,7 @@ def published = new groovy.json.JsonSlurper().parse(file('gradle/dependencies.js def haveModern = modernPin.enabled || published.modernmetals != null configurations { baseMetalsDevelopment; modernMetalsDevelopment } def mappedBase = basePin.enabled ? files(file(basePin.pin.mappedJar)) : renamer.dependency(published.basemetals.coordinate) -def mappedModern = modernPin.enabled ? files(file(modernPin.pin.mappedJar)) : renamer.dependency(published.modernmetals.coordinate) +def mappedModern = modernPin.enabled ? files(file(modernPin.pin.mappedJar)) : (published.modernmetals ? renamer.dependency(published.modernmetals.coordinate) : null) dependencies { baseMetalsDevelopment mappedBase if (withBase.get()) runtimeOnly mappedBase @@ -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.2.114041-mapped.jar'] = configurations.baseMetalsDevelopment.singleFile - if (mods.contains('modern')) selected['ModernMetals-3.0.0.114041-mapped.jar'] = configurations.modernMetalsDevelopment.singleFile + 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 // 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.2.114041-mapped.jar', configurations.baseMetalsDevelopment], - 'modern': ['ModernMetals-3.0.0.114041-mapped.jar', configurations.modernMetalsDevelopment]].each { kind, spec -> + ['base': ['BaseMetals-3.0.3.115021-mapped.jar', configurations.baseMetalsDevelopment], + 'modern': ['ModernMetals-3.0.0.115021-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 098fddd..00a95f4 100644 --- a/gradle/dependencies.json +++ b/gradle/dependencies.json @@ -1,23 +1,23 @@ [ { "id": "orespawn", - "coordinate": "zone.moddev.mc.orespawn:OreSpawn:4.1.7.114041", + "coordinate": "zone.moddev.mc.orespawn:OreSpawn:4.1.7.115021", "repository": "https://maven.moddev.zone/releases", "runtime": true, - "sha256": "C6171543240D43CD6273601D537D46A8F8C8A8B5992B258827E2F6F713AB7D44" + "sha256": "5CDF25E6D98560CBEF8366D6D1589B66E99A386859E5D659ACBB2B806FCF8F3D" }, { "id": "basemetals", - "coordinate": "zone.moddev.mc.basemetals:BaseMetals:3.0.2.114041", + "coordinate": "zone.moddev.mc.basemetals:BaseMetals:3.0.3.115021", "repository": "https://maven.moddev.zone/releases", "runtime": false, - "sha256": "11C0C4A6FE26B22EE794EA76CD6E0F1C5B65FB03540F9E8E0C52425CFEFB062B" + "sha256": "5C7CF937C10D1F131E2716D6242B1B56EEBE051CF8F1B267AA78E6B9AD6784C1" }, { "id": "modernmetals", - "coordinate": "zone.moddev.mc.modernmetals:ModernMetals:3.0.0.114041", + "coordinate": "zone.moddev.mc.modernmetals:ModernMetals:3.0.0.115021", "repository": "https://maven.moddev.zone/releases", "runtime": false, - "sha256": "22942EBC37BE76D940EA6EFCA53DA6E47085D72EAD95D348DE70D7526389683B" + "sha256": "CE6F05F9561CA9621765DC13FE63B24228ACAE2D33CE9968F8EE8F24F899AD7C" } ] diff --git a/gradle/local-companions-114.gradle b/gradle/local-companions-115.gradle similarity index 92% rename from gradle/local-companions-114.gradle rename to gradle/local-companions-115.gradle index 2314626..abc9ef3 100644 --- a/gradle/local-companions-114.gradle +++ b/gradle/local-companions-115.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.2.114041', checkout: '../../BaseMetals 114/BaseMetals', property: 'baseMetalsCheckout'], - modernmetals: [label: 'ModernMetals', version: '3.0.0.114041', checkout: '../../ModernMetals 114/ModernMetals', property: 'modernMetalsCheckout'] + 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'] ] def hash = { File jar -> MessageDigest.getInstance('SHA-256').digest(jar.bytes).encodeHex().toString() } def pins = [:] diff --git a/gradle/release-114.gradle b/gradle/release-115.gradle similarity index 93% rename from gradle/release-114.gradle rename to gradle/release-115.gradle index 7d38455..b1be650 100644 --- a/gradle/release-114.gradle +++ b/gradle/release-115.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.14.4-forge-28.2.26-java-8') + 'Build-Target': 'minecraft-1.15.2-forge-31.2.57-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+\.114041/)) { + if (project.group.toString() != expectedGroup || !(project.version.toString() ==~ /\d+\.\d+\.\d+\.115021/)) { 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.14.4]"') - || !metadata.contains('versionRange="[4.1.7.114041,5.0.0)"')) { + || !metadata.contains('versionRange="[1.15.2]"') + || !metadata.contains('versionRange="[4.1.7.115021,5.0.0)"')) { throw new GradleException('Wrong or unresolved release mod metadata') } } @@ -86,14 +86,14 @@ def audit = { File directory -> } } -tasks.register('verify114ReleaseArtifacts') { +tasks.register('verify115ReleaseArtifacts') { group = 'verification' dependsOn tasks.named('assemble'), tasks.named('check') doLast { audit(layout.buildDirectory.dir('libs').get().asFile) } } -tasks.register('write114ReleaseChecksums') { +tasks.register('write115ReleaseChecksums') { group = 'verification' - dependsOn tasks.named('verify114ReleaseArtifacts') + dependsOn tasks.named('verify115ReleaseArtifacts') doLast { File output = layout.buildDirectory.file('release/SHA256SUMS').get().asFile output.parentFile.mkdirs() @@ -102,7 +102,7 @@ tasks.register('write114ReleaseChecksums') { }.join('\n') + '\n', 'UTF-8') } } -tasks.register('verify114PreparedReleaseArtifacts') { +tasks.register('verify115PreparedReleaseArtifacts') { 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.14.4, using Forge 28 and OreSpawn 4.' + description = 'Base Minerals for Minecraft 1.15.2, using Forge 31 and OreSpawn 4.' url = 'https://github.com/MinecraftModDevelopmentMods/BaseMinerals' licenses { license { @@ -159,13 +159,14 @@ publishing { def dependency = asNode().appendNode('dependencies').appendNode('dependency') dependency.appendNode('groupId', 'zone.moddev.mc.basemetals') dependency.appendNode('artifactId', 'BaseMetals') - dependency.appendNode('version', '3.0.2.114041') + dependency.appendNode('version', project.basemetals_version.toString()) dependency.appendNode('optional', 'true') def modern = dependency.parent().appendNode('dependency') modern.appendNode('groupId', 'zone.moddev.mc.modernmetals') modern.appendNode('artifactId', 'ModernMetals') modern.appendNode('version', project.modernmetals_version.toString()) modern.appendNode('optional', 'true') + } } } @@ -180,7 +181,7 @@ publishing { } } } -tasks.register('verify114MavenCoordinates') { +tasks.register('verify115MavenCoordinates') { dependsOn 'generatePomFileForMavenJavaPublication' doLast { def pom = new XmlSlurper(false, false).parse(layout.buildDirectory.file('publications/mavenJava/pom-default.xml').get().asFile) @@ -196,8 +197,8 @@ tasks.register('verify114MavenCoordinates') { } } tasks.withType(PublishToMavenRepository).configureEach { - dependsOn 'verify114MavenCoordinates' - dependsOn preparedDirectory.isPresent() ? 'verify114PreparedReleaseArtifacts' : 'verify114ReleaseArtifacts' + dependsOn 'verify115MavenCoordinates' + dependsOn preparedDirectory.isPresent() ? 'verify115PreparedReleaseArtifacts' : 'verify115ReleaseArtifacts' doFirst { def url = providers.environmentVariable('MAVEN_UPLOAD_URL').getOrElse('') if (!url.startsWith('https://') || url.startsWith('https://invalid.invalid') @@ -208,4 +209,4 @@ tasks.withType(PublishToMavenRepository).configureEach { } } -tasks.named('check') { dependsOn 'verify114MavenCoordinates' } +tasks.named('check') { dependsOn 'verify115MavenCoordinates' } 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 4486aa9..e5bf4e2 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java +++ b/src/main/java/zone/moddev/mc/baseminerals/client/MineralFluidRenderer.java @@ -12,6 +12,21 @@ public final class MineralFluidRenderer { private MineralFluidRenderer() {} public static void register() { FMLJavaModLoadingContext.get().getModEventBus().addListener(MineralFluidRenderer::bucketColours); + FMLJavaModLoadingContext.get().getModEventBus().addListener(MineralFluidRenderer::rendering); + } + private static void rendering(net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent event) { + net.minecraftforge.fml.DeferredWorkQueue.runLater(() -> { + 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()); + else if (block.getRegistryName().getPath().endsWith("_ore")) + net.minecraft.client.renderer.RenderTypeLookup.setRenderLayer(block, net.minecraft.client.renderer.RenderType.getCutoutMipped()); + } + 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()); + }); } private static void bucketColours(ColorHandlerEvent.Item event) { for (String material : new String[] {"lithium", "silicon"}) { 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 d8052dc..1078160 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MineralContent.java @@ -15,7 +15,6 @@ import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; -import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IWorldReader; @@ -142,9 +141,5 @@ private static Block.Properties properties(String material, boolean ore) { @Override public boolean isBeaconBase(BlockState state, IWorldReader world, BlockPos pos, BlockPos beacon) { return !ore; } - @Override @OnlyIn(Dist.CLIENT) - public BlockRenderLayer getRenderLayer() { - return ore ? BlockRenderLayer.CUTOUT_MIPPED : BlockRenderLayer.SOLID; - } } } 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 e4f4d5a..bb14811 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralBlock.java @@ -15,7 +15,7 @@ public final class MoltenMineralBlock extends FlowingFluidBlock { @Override public void onEntityCollision(BlockState state, World world, BlockPos pos, Entity entity) { super.onEntityCollision(state, world, pos, entity); if (!world.isRemote && entity instanceof LivingEntity && !entity.isImmuneToFire() && !entity.isInLava() - && entity.getBoundingBox().minY < pos.getY() + state.getFluidState().func_215679_a(world, pos)) { + && entity.getBoundingBox().minY < pos.getY() + state.getFluidState().getActualHeight(world, pos)) { entity.attackEntityFrom(DamageSource.LAVA, 4.0F); entity.setFire(15); } diff --git a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java index ca9bdc2..a3fc6e8 100644 --- a/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java +++ b/src/main/java/zone/moddev/mc/baseminerals/content/MoltenMineralFluid.java @@ -7,7 +7,6 @@ import net.minecraft.fluid.IFluidState; import net.minecraft.item.Item; import net.minecraft.state.StateContainer; -import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IWorld; @@ -36,8 +35,6 @@ protected MoltenMineralFluid(MineralContent.Molten content) { @Override public Fluid getStillFluid() { return content.source; } @Override public Item getFilledBucket() { return content.bucket; } - @Override @OnlyIn(Dist.CLIENT) - public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.TRANSLUCENT; } @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); @@ -49,7 +46,7 @@ protected MoltenMineralFluid(MineralContent.Molten content) { @Override public boolean isEquivalentTo(Fluid fluid) { return fluid == content.source || fluid == content.flowing; } - @Override protected boolean func_215665_a(IFluidState state, net.minecraft.world.IBlockReader world, + @Override protected boolean canDisplace(IFluidState state, net.minecraft.world.IBlockReader world, BlockPos pos, Fluid fluid, Direction direction) { return direction == Direction.DOWN && !fluid.isEquivalentTo(this); } diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index ddf15a4..fb8d5d1 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -1,5 +1,5 @@ modLoader="javafml" -loaderVersion="[28,)" +loaderVersion="[31,)" 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.14.4]" +versionRange="[1.15.2]" ordering="NONE" side="BOTH" [[dependencies.baseminerals]] modId="orespawn" mandatory=true -versionRange="[4.1.7.114041,5.0.0)" +versionRange="[4.1.7.115021,5.0.0)" ordering="AFTER" side="BOTH" [[dependencies.baseminerals]] modId="basemetals" mandatory=false -versionRange="[3.0.2.114041,4.0.0)" +versionRange="[3.0.3.115021,4.0.0)" ordering="AFTER" side="BOTH" [[dependencies.baseminerals]] modId="modernmetals" mandatory=false -versionRange="[3.0.0.114041,4.0.0)" +versionRange="[3.0.0.115021,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 fd5137e..54591d5 100644 --- a/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js +++ b/src/main/resources/coremods/baseminerals_legacy_world_upgrade.js @@ -50,7 +50,7 @@ function initializeCoreMod() { method.instructions.insert(prefix); return node; } - throw new Error('Base Minerals could not find the Forge 28 numeric state converter'); + throw new Error('Base Minerals could not find the Forge 31 numeric state converter'); } }, 'baseminerals_save_registry': { @@ -73,27 +73,36 @@ function initializeCoreMod() { return node; } } - throw new Error('Base Minerals could not find the Forge 28 world registry reader'); + throw new Error('Base Minerals could not find the Forge 31 world registry reader'); } }, 'baseminerals_region_directory': { - target: {type: 'CLASS', name: 'net.minecraft.world.chunk.storage.RegionFileCache'}, + target: {type: 'CLASS', name: 'net.minecraft.world.chunk.storage.ChunkLoader'}, transformer: function(node) { - var field = null; - for (var i = 0; i < node.fields.size(); ++i) { - var candidate = node.fields.get(i); - if (candidate.desc !== 'Ljava/io/File;') continue; - if (field !== null) throw new Error('Ambiguous Forge 28 region directory'); - field = candidate; + var FieldNode = Java.type('org.objectweb.asm.tree.FieldNode'); + var name = 'baseminerals$regionDirectory'; + node.fields.add(new FieldNode(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, name, 'Ljava/io/File;', null, null)); + 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; + for (var insn = method.instructions.getFirst(); insn !== null; insn = insn.getNext()) { + if (insn.getOpcode() !== Opcodes.RETURN) continue; + var capture = new InsnList(); + capture.add(new VarInsnNode(Opcodes.ALOAD, 0)); + capture.add(new VarInsnNode(Opcodes.ALOAD, 1)); + capture.add(new FieldInsnNode(Opcodes.PUTFIELD, node.name, name, 'Ljava/io/File;')); + method.instructions.insertBefore(insn, capture); + patched++; + } } - if (field === null) throw new Error('Missing Forge 28 region directory'); + if (patched !== 1) throw new Error('Base Minerals could not capture the Forge 31 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)); - getter.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, node.name, field.name, field.desc)); + getter.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, node.name, name, 'Ljava/io/File;')); getter.instructions.add(new InsnNode(Opcodes.ARETURN)); - getter.maxStack = 1; - getter.maxLocals = 1; + getter.maxStack = 1; getter.maxLocals = 1; node.methods.add(getter); return node; } @@ -112,7 +121,7 @@ function initializeCoreMod() { var directory = new InsnList(); directory.add(new VarInsnNode(Opcodes.ALOAD, 0)); directory.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, - 'net/minecraft/world/chunk/storage/RegionFileCache', + 'net/minecraft/world/chunk/storage/ChunkLoader', 'baseminerals$getRegionDirectory', '()Ljava/io/File;', false)); method.instructions.insertBefore(insn, directory); method.instructions.set(insn, call('fixChunk', FIX_ARGS + 'IILjava/io/File;)' + NBT)); @@ -125,7 +134,7 @@ function initializeCoreMod() { insn = next; } } - if (patched !== 2) throw new Error('Base Minerals could not wrap both Forge 28 chunk upgrades'); + if (patched !== 2) throw new Error('Base Minerals could not wrap both Forge 31 chunk upgrades'); return node; } }, @@ -144,7 +153,7 @@ function initializeCoreMod() { patched++; } } - if (patched === 0) throw new Error('Base Minerals could not find the Forge 28 player data reader'); + if (patched === 0) throw new Error('Base Minerals could not find the Forge 31 player data reader'); return node; } } diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta index 9d92ddc..ff17d4c 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -1,6 +1,6 @@ { "pack": { - "pack_format": 4, + "pack_format": 5, "description": "Base Minerals" } } diff --git a/tools/test_114_resources.js b/tools/test_115_resources.js similarity index 100% rename from tools/test_114_resources.js rename to tools/test_115_resources.js diff --git a/tools/validation/port115/ParseEclipseArguments.java b/tools/validation/port115/ParseEclipseArguments.java new file mode 100644 index 0000000..8fbb81f --- /dev/null +++ b/tools/validation/port115/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/port115/client-probe/java/test/MineralClientProbe.java b/tools/validation/port115/client-probe/java/test/MineralClientProbe.java new file mode 100644 index 0000000..db58d00 --- /dev/null +++ b/tools/validation/port115/client-probe/java/test/MineralClientProbe.java @@ -0,0 +1,251 @@ +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.WorldType; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.registries.ForgeRegistries; + +/** Explicit client gate. Normal launches and published jars exclude this mod. */ +@Mod("mineralclientprobe") +@Mod.EventBusSubscriber(modid = "mineralclientprobe", value = Dist.CLIENT) +public final class MineralClientProbe { + private static int stage, ticks, loaded, checks, items; + private static net.minecraft.server.MinecraftServer stopping; + private static final JsonObject heldMining = new JsonObject(); + private static final List heldCases = new ArrayList<>(); + private static int digIndex, digPhase, digTicks, attackTicks, allowedAttackTicks; + private static java.util.concurrent.CompletableFuture operation; + private static final net.minecraft.util.math.BlockPos DIG_POS = new net.minecraft.util.math.BlockPos(128, 180, 128); + + private static void check(boolean value, String message) { + checks++; + if (!value) throw new IllegalStateException(message); + } + + @SubscribeEvent + public static void tick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END || stage == 5) return; + Minecraft mc = Minecraft.getInstance(); + try { + if (mc.currentScreen instanceof net.minecraftforge.fml.client.gui.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.currentScreen instanceof MainMenuScreen) { + validate(mc); + mc.launchIntegratedServer("mineral-smoke", "Base Minerals 1.15 check", + new WorldSettings(8675309L, GameType.SURVIVAL, false, false, WorldType.DEFAULT)); + stage = 1; ticks = 0; + } else if (stage == 1 && mc.world != null && mc.player != null && ++loaded > 80) { + if (!exerciseHeldMining(mc)) return; + stopping = mc.getIntegratedServer(); + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld(null); + mc.displayGuiScreen(new MainMenuScreen()); + stage = 2; ticks = 0; loaded = 0; + } else if (stage == 2 && mc.currentScreen instanceof MainMenuScreen && !stopping.getExecutionThread().isAlive()) { + mc.launchIntegratedServer("mineral-smoke", "Base Minerals 1.15 check", null); + stage = 3; ticks = 0; + } else if (stage == 3 && mc.world != null && mc.player != null && ++loaded > 80) { + stopping = mc.getIntegratedServer(); + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld(null); + mc.displayGuiScreen(new MainMenuScreen()); + stage = 4; ticks = 0; + } else if (stage == 4 && !stopping.getExecutionThread().isAlive()) { + write(true, null); stage = 5; mc.shutdown(); + } + } catch (Throwable error) { + error.printStackTrace(); write(false, error.toString()); stage = 5; mc.shutdown(); + } + } + + private static void validate(Minecraft mc) { + for (Item item : ForgeRegistries.ITEMS) { + if (!"baseminerals".equals(item.getRegistryName().getNamespace())) continue; + ItemStack stack = new ItemStack(item); + IBakedModel model = mc.getItemRenderer().getItemModelWithOverrides(stack, null, null); + check(model != mc.getModelManager().getMissingModel(), "Missing model " + item.getRegistryName()); + check(!stack.getDisplayName().getString().startsWith("item.baseminerals.") + && !stack.getDisplayName().getString().startsWith("block.baseminerals."), + "Missing translation " + item.getRegistryName()); + items++; + } + check(items == 41, "The saved item registry changed"); + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", "saltpeter", "sulfur"}) { + Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation("baseminerals", mineral + "_ore")); + check(RenderTypeLookup.canRenderInLayer(block.getDefaultState(), RenderType.getCutoutMipped()), "Ore cutout " + mineral); + oreModel(mc.getBlockRendererDispatcher().getModelForState(block.getDefaultState()), block, mineral); + oreModel(mc.getItemRenderer().getItemModelWithOverrides(new ItemStack(block), null, null), null, mineral); + } + for (String material : new String[] {"lithium", "silicon"}) { + ItemStack bucket = new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation("baseminerals", material + "_bucket"))); + IBakedModel model = mc.getItemRenderer().getItemModelWithOverrides(bucket, null, null); + List quads = new ArrayList<>(model.getQuads(null, null, new Random(1))); + for (Direction side : Direction.values()) quads.addAll(model.getQuads(null, side, new Random(1))); + check(quads.stream().anyMatch(q -> q.hasTintIndex() && q.getTintIndex() == 1), "Bucket fluid layer " + material); + for (BakedQuad quad : quads) check(!"missingno".equals(quad.func_187508_a().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.getAtlasSpriteGetter(net.minecraft.client.renderer.texture.AtlasTexture.LOCATION_BLOCKS_TEXTURE).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.getBlockRendererDispatcher().getModelForState(block.getDefaultState()), block); + baseOreGap(mc.getItemRenderer().getItemModelWithOverrides(new ItemStack(block), null, null), null); + baseOres++; + } + check(baseOres == 13, "All Base Metals ore block/item overlay gaps"); + } + for (String owner : new String[] {"basemetals", "modernmetals"}) { + if (!net.minecraftforge.fml.ModList.get().isLoaded(owner)) continue; + String hammer = owner + ("basemetals".equals(owner) ? ":iron_crackhammer" : ":galvanizedsteel_crackhammer"); + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", "saltpeter", "sulfur"}) + heldCases.add(new String[] {hammer, "baseminerals:" + mineral + "_ore", "baseminerals:" + mineral + "_powder"}); + } + } + + private static void baseOreGap(IBakedModel model, Block block) { + for (Direction side : Direction.values()) { + List quads = model.getQuads(block == null ? null : block.getDefaultState(), side, new Random(42)); + check(quads.size() == 2, "Base ore layers on " + side); + boolean sawOverlay = false; + for (BakedQuad quad : quads) { + boolean overlay = quad.func_187508_a().getName().getPath().startsWith("block/ore_overlays/"); + sawOverlay |= overlay; + float low = overlay ? -0.05F / 16 : 0, high = overlay ? 16.05F / 16 : 1; + int[] data = quad.getVertexData(); int stride = data.length / 4; + for (int vertex = 0; vertex < 4; vertex++) { + float u = (Float.intBitsToFloat(data[vertex * stride + 4]) - quad.func_187508_a().getMinU()) * 16.0F / (quad.func_187508_a().getMaxU() - quad.func_187508_a().getMinU()); + float v = (Float.intBitsToFloat(data[vertex * stride + 5]) - quad.func_187508_a().getMinV()) * 16.0F / (quad.func_187508_a().getMaxV() - quad.func_187508_a().getMinV()); + 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.func_187508_a().getName() + "=" + coordinate); + } + } + } + check(sawOverlay, "Base ore lost overlay"); + } + } + + /** Runs the same client damage loop as a held left click, including real packets. */ + private static boolean exerciseHeldMining(Minecraft mc) { + if (digIndex >= heldCases.size()) return true; + String[] test = heldCases.get(digIndex); + if (++digTicks > 180) throw new IllegalStateException("Held mining timeout " + java.util.Arrays.toString(test) + " phase=" + digPhase); + if (digPhase == 0) { + mc.playerController.resetBlockRemoving(); + operation = mc.getIntegratedServer().runAsync(() -> { + net.minecraft.world.server.ServerWorld world = mc.getIntegratedServer().getWorld(net.minecraft.world.dimension.DimensionType.OVERWORLD); + net.minecraft.entity.player.ServerPlayerEntity player = mc.getIntegratedServer().getPlayerList().getPlayerByUUID(mc.player.getUniqueID()); + player.interactionManager.setGameType(GameType.SURVIVAL); + for (int x = -5; x <= 5; x++) for (int z = -5; z <= 5; z++) + world.setBlockState(DIG_POS.add(x, -1, z), net.minecraft.block.Blocks.STONE.getDefaultState(), 3); + player.connection.setPlayerLocation(128.5D, 180.0D, 125.5D, 0, 0); + world.getEntitiesWithinAABB(net.minecraft.entity.item.ItemEntity.class, + new net.minecraft.util.math.AxisAlignedBB(DIG_POS).grow(1.5D)).forEach(net.minecraft.entity.item.ItemEntity::remove); + player.inventory.currentItem = 0; + player.inventory.setInventorySlotContents(0, new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation(test[0])))); + player.sendContainerToPlayer(player.container); + world.setBlockState(DIG_POS, ForgeRegistries.BLOCKS.getValue(new ResourceLocation(test[1])).getDefaultState(), 3); + }); + digPhase = 1; + } else if (digPhase == 1 && operation.isDone()) { + operation.join(); mc.player.inventory.currentItem = 0; + if (!test[1].equals(mc.world.getBlockState(DIG_POS).getBlock().getRegistryName().toString()) + || !test[0].equals(mc.player.getHeldItemMainhand().getItem().getRegistryName().toString()) + || mc.player.getHeldItemMainhand().getDamage() != 0 || Math.abs(mc.player.getPosY() - 180) > 0.1D) return false; + net.minecraft.block.BlockState state = mc.world.getBlockState(DIG_POS); + float speed = mc.player.getHeldItemMainhand().getDestroySpeed(state); + check(speed > 1.0F, "Client hammer tag did not sync " + test[0] + " -> " + test[1]); + // The native controller retains five hit-delay ticks between blocks. + allowedAttackTicks = (int) Math.ceil(state.getBlockHardness(mc.world, DIG_POS) * 30.0F / speed) + 6; + digPhase = 2; digTicks = 0; attackTicks = 0; + } else if (digPhase == 2) { + mc.playerController.onPlayerDamageBlock(DIG_POS, Direction.UP); + attackTicks++; + if (mc.world.isAirBlock(DIG_POS)) { digPhase = 3; digTicks = 0; } + check(attackTicks <= allowedAttackTicks, "Held hammer mining is too slow: " + test[0] + " -> " + test[1]); + } else if (digPhase == 3 && digTicks > 10) { + check(mc.world.isAirBlock(DIG_POS), "Mined ore reappeared on the client " + test[1]); + check(mc.player.getHeldItemMainhand().getDamage() == 1, "Client hammer durability did not sync " + test[1]); + operation = mc.getIntegratedServer().runAsync(() -> { + net.minecraft.world.server.ServerWorld world = mc.getIntegratedServer().getWorld(net.minecraft.world.dimension.DimensionType.OVERWORLD); + check(world.isAirBlock(DIG_POS), "Held mining left the ore on the server " + test[1]); + int count = 0; + for (net.minecraft.entity.item.ItemEntity drop : world.getEntitiesWithinAABB(net.minecraft.entity.item.ItemEntity.class, + new net.minecraft.util.math.AxisAlignedBB(DIG_POS).grow(1.5D))) { + check(test[2].equals(drop.getItem().getItem().getRegistryName().toString()), "Unexpected held mining drop " + test[1]); + count += drop.getItem().getCount(); + } + check(count == 2, "Held mining did not yield two powders " + test[1] + " count=" + count); + }); + digPhase = 4; + } else if (digPhase == 4 && operation.isDone()) { + operation.join(); heldMining.addProperty(test[0] + "/" + test[1], attackTicks); + digIndex++; digPhase = 0; digTicks = 0; + } + return false; + } + + private static void oreModel(IBakedModel model, Block block, String mineral) { + check(model.getParticleTexture().getName().toString().equals("minecraft:block/stone"), "Ore particle host " + mineral); + ResourceLocation overlay = new ResourceLocation("baseminerals", "blocks/ore_overlays/" + mineral + "_ore"); + for (Direction side : Direction.values()) { + List quads = model.getQuads(block == null ? null : block.getDefaultState(), side, new Random(42)); + check(quads.size() == 2, "Ore layers " + mineral + " " + side); + check(quads.stream().anyMatch(q -> q.func_187508_a().getName().toString().equals("minecraft:block/stone")), "Ore stone layer"); + check(quads.stream().anyMatch(q -> q.func_187508_a().getName().equals(overlay)), "Ore overlay layer"); + for (BakedQuad quad : quads) { + check(!"missingno".equals(quad.func_187508_a().getName().getPath()), "Missing ore sprite"); + if (!quad.func_187508_a().getName().equals(overlay)) continue; + boolean transparent = false, visible = false; + for (int y = 0; y < quad.func_187508_a().getHeight(); y++) for (int x = 0; x < quad.func_187508_a().getWidth(); x++) { + if (quad.func_187508_a().isPixelTransparent(0, x, y)) transparent = true; + else visible = true; + } + check(transparent && visible, "Ore overlay transparency " + mineral); + } + } + } + + private static void write(boolean passed, String failure) { + JsonObject result = new JsonObject(); + result.addProperty("passed", passed); result.addProperty("checks", checks); + result.addProperty("items", items); result.addProperty("worldReopened", passed); + result.add("held_mining_ticks", heldMining); + if (failure != null) result.addProperty("failure", failure); + try { + Files.write(Paths.get("client-probe.json"), new GsonBuilder().setPrettyPrinting().create().toJson(result).getBytes(StandardCharsets.UTF_8)); + } catch (java.io.IOException error) { throw new IllegalStateException(error); } + System.out.println("MINERAL_CLIENT_PROBE " + (passed ? "PASS" : "FAIL") + " checks=" + checks); + } +} diff --git a/tools/validation/port115/client-probe/resources/META-INF/mods.toml b/tools/validation/port115/client-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..4d875c5 --- /dev/null +++ b/tools/validation/port115/client-probe/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +loaderVersion="[31,)" +license="LGPL-2.1" +[[mods]] +modId="mineralclientprobe" +version="1" +displayName="Base Minerals client test" +[[dependencies.mineralclientprobe]] +modId="baseminerals" +mandatory=true +versionRange="[2.5.2.115021,)" +ordering="AFTER" +side="CLIENT" diff --git a/tools/validation/port115/client-probe/resources/pack.mcmeta b/tools/validation/port115/client-probe/resources/pack.mcmeta new file mode 100644 index 0000000..763e18b --- /dev/null +++ b/tools/validation/port115/client-probe/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 5, + "description": "Disposable qualification probe" + } +} diff --git a/tools/validation/port115/generation-probe/java/test/MineralGenerationProbe.java b/tools/validation/port115/generation-probe/java/test/MineralGenerationProbe.java new file mode 100644 index 0000000..7822e29 --- /dev/null +++ b/tools/validation/port115/generation-probe/java/test/MineralGenerationProbe.java @@ -0,0 +1,115 @@ +package test; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.util.Map; +import java.util.TreeMap; +import net.minecraft.block.Block; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.dimension.DimensionType; +import net.minecraft.world.server.ServerWorld; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; +import net.minecraftforge.registries.ForgeRegistries; + +/** Disposable full-height census; contains no placement implementation. */ +@Mod("mineralgenerationprobe") +public final class MineralGenerationProbe { + private static final String[] ORES = {"lithium", "niter", "salt", "sulfur", "phosphorus", "potash", "saltpeter"}; + private static final int[][] HEIGHTS = {{8,47}, {16,63}, {24,79}, {4,31}, {16,63}, {8,47}, {24,79}}; + public MineralGenerationProbe() { MinecraftForge.EVENT_BUS.addListener(this::started); } + + private void started(FMLServerStartedEvent event) { + JsonObject report = new JsonObject(); + long start = System.nanoTime(); + try { + report.addProperty("seed", event.getServer().getWorld(DimensionType.OVERWORLD).getSeed()); + report.addProperty("interior_chunks_per_dimension", 256); + report.addProperty("margin_chunks", 2); + report.addProperty("min_y", 0); report.addProperty("max_y", 255); + JsonObject dimensions = new JsonObject(); + for (DimensionType type : new DimensionType[] {DimensionType.OVERWORLD, DimensionType.THE_NETHER, DimensionType.THE_END}) { + ServerWorld world = event.getServer().getWorld(type); + long begin = System.nanoTime(); + for (int x = 62; x < 82; x++) for (int z = 62; z < 82; z++) world.getChunk(x, z); + JsonObject before = census(world, type == DimensionType.OVERWORLD); + // Generate later chunks beyond the populated margin, then census the old interior again. + for (int z = 62; z < 82; z++) world.getChunk(82, z); + JsonObject after = census(world, type == DimensionType.OVERWORLD); + if (!before.equals(after)) throw new AssertionError("Later generation changed existing ores in " + type); + before.addProperty("populate_and_census_seconds", (System.nanoTime() - begin) / 1e9); + dimensions.add(DimensionType.getKey(type).toString(), before); + System.out.println("MINERAL_GENERATION_DIMENSION " + type + " " + before); + } + report.add("dimensions", dimensions); + report.addProperty("passed", true); + } catch (Throwable failure) { + report.addProperty("passed", false); + report.addProperty("failure", failure.toString()); + failure.printStackTrace(); + } finally { + report.addProperty("seconds", (System.nanoTime() - start) / 1e9); + try { + Files.write(Paths.get("generation-results.json"), new GsonBuilder().setPrettyPrinting().create() + .toJson(report).getBytes(StandardCharsets.UTF_8)); + } catch (java.io.IOException error) { throw new IllegalStateException(error); } + System.out.println("MINERAL_GENERATION_PROBE " + (report.get("passed").getAsBoolean() ? "PASS" : "FAIL")); + event.getServer().initiateShutdown(false); + } + } + + private static JsonObject census(ServerWorld world, boolean overworld) throws Exception { + Map indices = new java.util.IdentityHashMap<>(); + int[][] histogram = new int[7][256]; + for (int i = 0; i < ORES.length; i++) indices.put(ForgeRegistries.BLOCKS.getValue( + new ResourceLocation("baseminerals", ORES[i] + "_ore")), i); + TreeMap coordinates = new TreeMap<>(); + BlockPos.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.setPos(cx * 16 + x, y, cz * 16 + z); + Block block = chunk.getBlockState(pos).getBlock(); + Integer index = indices.get(block); + if (index == null) { + if ("baseminerals".equals(block.getRegistryName().getNamespace())) + throw new AssertionError("Undeclared generated mineral block " + block.getRegistryName()); + continue; + } + if (!overworld || y < HEIGHTS[index][0] || y > HEIGHTS[index][1]) + throw new AssertionError("Unexpected ore " + ORES[index] + " at " + pos + " in " + world.getDimension().getType()); + histogram[index][y]++; + coordinates.put(pos.getX() + "," + y + "," + pos.getZ(), ORES[index]); + } + } + JsonObject result = new JsonObject(), counts = new JsonObject(), hist = new JsonObject(); + for (int i = 0; i < ORES.length; i++) { + int count = java.util.Arrays.stream(histogram[i]).sum(); + String disabled = System.getProperty("mineralprobe.disabled", ""); + boolean expectDisabled = "all".equals(disabled) || java.util.Arrays.asList(disabled.split(",")).contains(ORES[i]); + if (overworld && (expectDisabled ? count != 0 : count == 0)) + throw new AssertionError("Unexpected count " + count + " for " + ORES[i] + "; disabled=" + expectDisabled); + counts.addProperty(ORES[i], count); + JsonObject heights = new JsonObject(); + for (int y = 0; y < 256; y++) if (histogram[i][y] != 0) heights.addProperty(String.valueOf(y), histogram[i][y]); + hist.add(ORES[i], heights); + } + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (Map.Entry entry : coordinates.entrySet()) + digest.update((entry.getKey() + "=" + entry.getValue() + "\n").getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(); + for (byte b : digest.digest()) hex.append(String.format("%02x", b & 255)); + result.add("counts", counts); result.add("height_histograms", hist); + result.addProperty("sorted_coordinate_sha256", hex.toString()); + result.addProperty("unchanged_after_later_chunks", true); + return result; + } +} diff --git a/tools/validation/port115/generation-probe/resources/META-INF/mods.toml b/tools/validation/port115/generation-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..917c0a6 --- /dev/null +++ b/tools/validation/port115/generation-probe/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +loaderVersion="[31,)" +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.115021,)" +ordering="AFTER" +side="SERVER" diff --git a/tools/validation/port115/generation-probe/resources/pack.mcmeta b/tools/validation/port115/generation-probe/resources/pack.mcmeta new file mode 100644 index 0000000..763e18b --- /dev/null +++ b/tools/validation/port115/generation-probe/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 5, + "description": "Disposable qualification probe" + } +} diff --git a/tools/validation/port115/mining-probe/java/test/MineralMiningProbe.java b/tools/validation/port115/mining-probe/java/test/MineralMiningProbe.java new file mode 100644 index 0000000..6d871bf --- /dev/null +++ b/tools/validation/port115/mining-probe/java/test/MineralMiningProbe.java @@ -0,0 +1,370 @@ +package test; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.entity.item.ItemEntity; +import net.minecraft.entity.merchant.villager.VillagerEntity; +import net.minecraft.enchantment.Enchantments; +import net.minecraft.item.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.FurnaceRecipe; +import net.minecraft.item.crafting.AbstractCookingRecipe; +import net.minecraft.item.crafting.IRecipeType; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.inventory.Inventory; +import net.minecraft.network.PacketDirection; +import net.minecraft.network.play.ServerPlayNetHandler; +import net.minecraft.network.NetworkManager; +import net.minecraft.util.Hand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.StringTextComponent; +import net.minecraft.world.GameType; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.dimension.DimensionType; +import net.minecraft.item.MerchantOffer; +import net.minecraft.item.MerchantOffers; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.FakePlayer; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; +import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.entity.merchant.villager.VillagerProfession; +import net.minecraft.entity.merchant.villager.VillagerTrades; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.server.management.PlayerInteractionManager; +import net.minecraft.world.storage.loot.*; +import net.minecraft.world.storage.loot.conditions.ILootCondition; +import zone.moddev.mc.baseminerals.loot.MineralPowderCount; + +/** Exercises the installed jar through real survival harvesting. */ +@Mod("mineralminingprobe") +public final class MineralMiningProbe { + private static final String[] MINERALS = { + "lithium", "niter", "phosphorus", "potash", "salt", "saltpeter", "sulfur" + }; + private final List failures = new ArrayList<>(); + private final JsonObject drops = new JsonObject(); + private final JsonObject miningProgress = new JsonObject(); + private ServerWorld world; + private ServerPlayerEntity player; + private int checks; + private int harvestIndex; + + public MineralMiningProbe() { MinecraftForge.EVENT_BUS.addListener(this::started); } + + private void started(FMLServerStartedEvent event) { + world = event.getServer().getWorld(DimensionType.OVERWORLD); + player = new ServerPlayerEntity(event.getServer(), world, new GameProfile(UUID.randomUUID(), "MineralMiningProbe"), new PlayerInteractionManager(world)); + player.connection = new ServerPlayNetHandler(event.getServer(), new NetworkManager(PacketDirection.SERVERBOUND), player); + player.interactionManager.setGameType(GameType.SURVIVAL); + player.onGround = true; + try { + for (String mineral : MINERALS) { + Block ore = block(mineral + "_ore"); + boolean lithium = "lithium".equals(mineral); + for (int fortune = 0; fortune <= 3; fortune++) { + ItemStack pickaxe = new ItemStack(Items.DIAMOND_PICKAXE); + if (fortune > 0) pickaxe.addEnchantment(Enchantments.FORTUNE, fortune); + int count = harvest(ore, pickaxe, item(mineral + (lithium ? "_ore" : "_powder"))); + check(lithium ? count == 1 : count >= 2 && count <= 4 + fortune, + mineral + " Fortune " + fortune + " yielded " + count); + drops.addProperty(mineral + ":fortune" + fortune, count); + BlockState state = ore.getDefaultState(); + for (int sample = 0; sample < 256; sample++) { + Random random = new Random(sample); + int expected = lithium ? 1 : 2 + new Random(sample).nextInt(3 + fortune); + LootContext.Builder context = new LootContext.Builder(world).withRandom(random) + .withParameter(LootParameters.POSITION, BlockPos.ZERO) + .withParameter(LootParameters.BLOCK_STATE, state).withParameter(LootParameters.TOOL, pickaxe); + int actual = lithium ? 1 : new MineralPowderCount.Serializer() + .deserialize(new JsonObject(), null, new ILootCondition[0]) + .apply(new ItemStack(item(mineral + "_powder")), context.build(LootParameterSets.BLOCK)).getCount(); + check(actual == expected, mineral + " changed the uniform Fortune formula at " + fortune); + List loot = ore.getDrops(state, new LootContext.Builder(world).withRandom(new Random(sample)) + .withParameter(LootParameters.POSITION, BlockPos.ZERO).withParameter(LootParameters.TOOL, pickaxe)); + check(loot.size() == 1 && loot.get(0).getItem() == item(mineral + (lithium ? "_ore" : "_powder")) + && (lithium ? loot.get(0).getCount() == 1 : loot.get(0).getCount() >= 2 && loot.get(0).getCount() <= 4 + fortune), + mineral + " native loot changed at Fortune " + fortune); + } + } + ItemStack silk = new ItemStack(Items.DIAMOND_PICKAXE); + silk.addEnchantment(Enchantments.SILK_TOUCH, 1); + check(harvest(ore, silk, item(mineral + "_ore")) == 1, + mineral + " Silk Touch did not return one ore"); + check(harvest(ore, new ItemStack(Items.WOODEN_PICKAXE), null) == 0, + mineral + " dropped with an inadequate pickaxe"); + if (lithium) { + check(harvest(ore, new ItemStack(Items.STONE_PICKAXE), null) == 0, + "Lithium requires an iron-level pickaxe"); + } + check(ore.getExpDrop(ore.getDefaultState(), world, BlockPos.ZERO, 3, 0) == 0, + mineral + " added mining XP"); + blockProperties(ore, 5.0F, lithium ? 3.0F : 0.75F, lithium ? 2 : 1, false); + } + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", + "saltpeter", "silicon", "sulfur"}) { + Block storage = block(mineral + "_block"); + check(harvest(storage, new ItemStack(Items.DIAMOND_PICKAXE), item(mineral + "_block")) == 1, + mineral + " storage-block drop changed"); + boolean metal = "lithium".equals(mineral) || "silicon".equals(mineral); + blockProperties(storage, metal ? 16.0F : 10.0F, metal ? 4.0F : 1.0F, metal ? 2 : 1, true); + } + if (Boolean.getBoolean("mineralprobe.processing")) { + processingRecipes(); + smithOffers(); + for (String material : new String[] {"lithium", "silicon"}) { + check(block(material).getDefaultState().getLightValue() == 10, material + " lost molten-fluid light"); + moltenLifecycle(material); + } + } + for (String owner : new String[] {"basemetals", "modernmetals"}) { + if (!ModList.get().isLoaded(owner)) continue; + ResourceLocation hammerId = new ResourceLocation(owner, + "basemetals".equals(owner) ? "iron_crackhammer" : "galvanizedsteel_crackhammer"); + check(ForgeRegistries.ITEMS.containsKey(hammerId), "Missing test hammer " + hammerId); + for (String mineral : MINERALS) { + ItemStack hammer = new ItemStack(ForgeRegistries.ITEMS.getValue(hammerId)); + int count = dig(block(mineral + "_ore"), hammer, item(mineral + "_powder")); + check(count == 2 && hammer.getDamage() == 1, + owner + " hammer yielded " + count + " " + mineral + " powders, damage " + hammer.getDamage()); + } + if (Boolean.getBoolean("mineralprobe.processing")) { + for (String mineral : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", + "saltpeter", "silicon", "sulfur"}) { + ItemStack hammer = new ItemStack(ForgeRegistries.ITEMS.getValue(hammerId)); + check(dig(block(mineral + "_block"), hammer, item(mineral + "_powder")) == 9, + owner + " hammer did not crush " + mineral + " storage block to nine powders"); + check(hammer.getDamage() == 1, owner + " storage-block crushing did not damage hammer"); + } + } + } + } catch (Throwable error) { + failures.add(error.toString()); + error.printStackTrace(); + } finally { + JsonObject report = new JsonObject(); + report.addProperty("passed", failures.isEmpty()); + report.add("mining_progress", miningProgress); + report.addProperty("checks", checks); + report.add("drops", drops); + report.add("failures", new com.google.gson.Gson().toJsonTree(failures)); + try { + Files.write(Paths.get("mining-results.json"), + new GsonBuilder().setPrettyPrinting().create().toJson(report).getBytes(StandardCharsets.UTF_8)); + } catch (java.io.IOException error) { + throw new IllegalStateException(error); + } finally { + System.out.println("MINERAL_MINING_PROBE " + (failures.isEmpty() ? "PASS" : "FAIL") + " checks=" + checks); + event.getServer().initiateShutdown(false); + } + } + } + + private void blockProperties(Block block, float hardness, float resistance, int harvestLevel, boolean beacon) { + BlockState state = block.getDefaultState(); + check(state.getBlockHardness(world, BlockPos.ZERO) == hardness, + block.getRegistryName() + " changed mining hardness"); + check(block.getExplosionResistance() == resistance, block.getRegistryName() + " changed blast resistance"); + check(state.getHarvestLevel() == harvestLevel, block.getRegistryName() + " changed harvest tier"); + check(block.isBeaconBase(state, world, BlockPos.ZERO, BlockPos.ZERO) == beacon, + block.getRegistryName() + " changed beacon support"); + } + + private void processingRecipes() { + for (String material : new String[] {"lithium", "silicon"}) { + furnace(material + "_powder", material + "_ingot", 0.45F); + furnace(material + "_smallpowder", material + "_nugget", 0.05F); + } + furnace("lithium_ore", "lithium_ingot", 0.45F); + furnace("silicon_blend", "silicon_ingot", 0.45F); + furnace("silicon_smallblend", "silicon_nugget", 0.05F); + boolean crushingLoaded = ModList.get().isLoaded("basemetals") || ModList.get().isLoaded("modernmetals"); + for (String material : new String[] {"lithium", "niter", "phosphorus", "potash", "salt", + "saltpeter", "silicon", "sulfur"}) { + crusher(material + "_block", material + "_powder", 9, crushingLoaded); + } + for (String material : new String[] {"lithium", "silicon"}) { + crusher(material + "_ingot", material + "_powder", 1, crushingLoaded); + crusher(material + "_nugget", material + "_smallpowder", 1, crushingLoaded); + } + } + + private void smithOffers() { + for (VillagerProfession profession : new VillagerProfession[] {VillagerProfession.ARMORER, + VillagerProfession.TOOLSMITH, VillagerProfession.WEAPONSMITH}) { + for (int seed = 0; seed < 32; seed++) { + MerchantOffers offers = new MerchantOffers(); + for (VillagerTrades.ITrade trade : VillagerTrades.VILLAGER_DEFAULT_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.getSellingStack().getItem() != item(material + "_ingot")) continue; + matches++; + check(offer.getSellingStack().getCount() == 1 && offer.getBuyingStackFirst().getItem() == Items.EMERALD + && offer.getBuyingStackFirst().getCount() >= 4 && offer.getBuyingStackFirst().getCount() <= 5 + && offer.func_222214_i() == 12 && offer.getGivenExp() == 5, + material + " smith offer, restocking or experience changed"); + } + check(matches == 1, profession + " has " + matches + " " + material + " offers"); + } + } + } + } + + private void furnace(String input, String output, float xp) { + cooking(input, output, xp, IRecipeType.SMELTING, 200); + cooking(input, output, xp, IRecipeType.BLASTING, 100); + } + + private void cooking(String input, String output, float xp, IRecipeType type, int ticks) { + Inventory inventory = new Inventory(1); + inventory.setInventorySlotContents(0, new ItemStack(item(input))); + List matches = new ArrayList<>(); + for (IRecipe recipe : world.getRecipeManager().getRecipes()) { + if (recipe.getType() == type && recipe.matches(inventory, world)) matches.add(recipe); + } + check(matches.size() == 1, input + " has " + matches.size() + " furnace recipes"); + for (IRecipe recipe : matches) { + ItemStack result = recipe.getRecipeOutput(); + check(result.getItem() == item(output) && result.getCount() == 1, input + " smelts to " + result); + check(((AbstractCookingRecipe) recipe).getExperience() == xp, input + " changed cooking XP"); + check(((AbstractCookingRecipe) recipe).getCookTime() == ticks, input + " changed cooking time"); + } + } + + private void crusher(String input, String output, int count, boolean enabled) { + Inventory inventory = new Inventory(1); + inventory.setInventorySlotContents(0, new ItemStack(item(input))); + List matches = new ArrayList<>(); + for (IRecipe recipe : world.getRecipeManager().getRecipes()) { + if ("crushing".equals(recipe.getSerializer().getRegistryName().getPath()) && recipe.matches(inventory, world)) { + matches.add(recipe); + } + } + check(matches.size() == (enabled ? 1 : 0), input + " has " + matches.size() + " crushing recipes"); + for (IRecipe recipe : matches) { + check(recipe.getRecipeOutput().getItem() == item(output) && recipe.getRecipeOutput().getCount() == count, + input + " crushes to " + recipe.getRecipeOutput()); + } + } + + private void moltenLifecycle(String material) { + net.minecraft.item.BucketItem bucket = (net.minecraft.item.BucketItem) item(material + "_bucket"); + net.minecraft.fluid.Fluid fluid = bucket.getFluid(); + net.minecraftforge.fluids.FluidAttributes attributes = fluid.getAttributes(); + check(fluid.getRegistryName().equals(new ResourceLocation("baseminerals", material)), "Source fluid identity " + material); + check(attributes.getColor() == 0xFFC5C8C1 && attributes.getLuminosity() == 10 + && attributes.getDensity() == 2000 && attributes.getViscosity() == 10000 + && attributes.getTemperature() == 330, "Molten attributes " + material); + check(!fluid.isIn(net.minecraft.tags.FluidTags.LAVA), "Molten fluid became vanilla lava " + material); + BlockPos pos = new BlockPos(128, 240, "lithium".equals(material) ? 144 : 160); + for (int x = -5; x <= 5; x++) for (int z = -5; z <= 5; z++) { + world.setBlockState(pos.add(x, -1, z), net.minecraft.block.Blocks.STONE.getDefaultState(), 2); + world.setBlockState(pos.add(x, 0, z), net.minecraft.block.Blocks.AIR.getDefaultState(), 2); + } + check(bucket.tryPlaceContainedLiquid(player, world, pos, null), "Native bucket placement " + material); + check(world.getBlockState(pos).getBlock() == block(material) && world.getFluidState(pos).isSource(), + "Bucket placed the wrong source " + material); + world.getFluidState(pos).tick(world, pos); + boolean flowed = false; + for (net.minecraft.util.Direction side : net.minecraft.util.Direction.Plane.HORIZONTAL) { + net.minecraft.fluid.IFluidState adjacent = world.getFluidState(pos.offset(side)); + if (fluid.isEquivalentTo(adjacent.getFluid()) && !adjacent.isSource()) flowed = true; + } + check(flowed, "Molten source did not flow " + material); + // A newly constructed ServerPlayerEntity has 60 ticks of native spawn + // damage immunity. Use an ordinary creature to exercise actual contact. + net.minecraft.entity.passive.PigEntity creature = net.minecraft.entity.EntityType.PIG.create(world); + creature.setPosition(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5); + float health = creature.getHealth(); + block(material).onEntityCollision(world.getBlockState(pos), world, pos, creature); + check(creature.getHealth() == health && !creature.isBurning(), "Molten heat escaped its surface " + material); + creature.setPosition(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5); + block(material).onEntityCollision(world.getBlockState(pos), world, pos, creature); + check(creature.getHealth() == health - 4.0F && creature.isBurning(), + "Molten contact lost heat " + material + " health=" + creature.getHealth() + " burning=" + creature.isBurning()); + creature.remove(); + net.minecraft.fluid.Fluid picked = ((net.minecraft.block.IBucketPickupHandler) block(material)) + .pickupFluid(world, pos, world.getBlockState(pos)); + check(picked == fluid && world.isAirBlock(pos) && picked.getFilledBucket() == bucket, + "Native pickup lost fluid or bucket identity " + material); + } + + private int harvest(Block block, ItemStack tool, Item expected) { + return harvest(block, tool, expected, false); + } + + private int dig(Block block, ItemStack tool, Item expected) { + return harvest(block, tool, expected, true); + } + + private int harvest(Block block, ItemStack tool, Item expected, boolean normalDigging) { + int index = harvestIndex++; + BlockPos pos = new BlockPos(128 + (index % 16) * 3, 180 + (index / 16) * 4, 128); + AxisAlignedBB area = new AxisAlignedBB(pos).grow(0.45); + world.getEntitiesWithinAABB(ItemEntity.class, area).forEach(ItemEntity::remove); + world.setBlockState(pos, block.getDefaultState(), 3); + player.setHeldItem(Hand.MAIN_HAND, tool); + if (normalDigging) { + player.setPosition(pos.getX() + 0.5D, pos.getY(), pos.getZ() + 2.5D); + player.onGround = true; + BlockState state = world.getBlockState(pos); + float speed = tool.getDestroySpeed(state); + check(speed > 1.0F, "Hammer uses untagged mining speed for " + block.getRegistryName()); + float progress = state.getPlayerRelativeBlockHardness(player, world, pos); + int ticks = progress > 0 ? (int) Math.ceil(1.0F / progress) : 400; + int expectedTicks = (int) Math.ceil(state.getBlockHardness(world, pos) * 30.0F / speed); + check(state.canHarvestBlock(world, pos, player) && ticks <= expectedTicks + 1, + "Hammer progress differs from its native speed for " + block.getRegistryName() + ": " + ticks + " vs " + expectedTicks); + JsonObject timing = new JsonObject(); + timing.addProperty("speed", speed); timing.addProperty("ticks", ticks); + timing.addProperty("progress_per_tick", progress); + miningProgress.add(tool.getItem().getRegistryName() + "/" + block.getRegistryName(), timing); + player.interactionManager.func_225416_a(pos, net.minecraft.network.play.client.CPlayerDiggingPacket.Action.START_DESTROY_BLOCK, + net.minecraft.util.Direction.UP, 256); + for (int tick = 0; tick <= Math.min(ticks, 400); tick++) player.interactionManager.tick(); + player.interactionManager.func_225416_a(pos, net.minecraft.network.play.client.CPlayerDiggingPacket.Action.STOP_DESTROY_BLOCK, + net.minecraft.util.Direction.UP, 256); + check(world.isAirBlock(pos), "Normal digging did not remove " + block.getRegistryName()); + } else player.interactionManager.tryHarvestBlock(pos); + int count = 0; + for (ItemEntity drop : world.getEntitiesWithinAABB(ItemEntity.class, area)) { + check(drop.getItem().getItem() == expected, + block.getRegistryName() + " dropped " + drop.getItem().getItem().getRegistryName()); + count += drop.getItem().getCount(); + drop.remove(); + } + world.removeBlock(pos, false); + return count; + } + + private static Block block(String name) { + return ForgeRegistries.BLOCKS.getValue(new ResourceLocation("baseminerals", name)); + } + + private static Item item(String name) { + return ForgeRegistries.ITEMS.getValue(new ResourceLocation("baseminerals", name)); + } + + private void check(boolean condition, String detail) { + checks++; + if (!condition) failures.add(detail); + } +} diff --git a/tools/validation/port115/mining-probe/resources/META-INF/mods.toml b/tools/validation/port115/mining-probe/resources/META-INF/mods.toml new file mode 100644 index 0000000..aa4993e --- /dev/null +++ b/tools/validation/port115/mining-probe/resources/META-INF/mods.toml @@ -0,0 +1,12 @@ +modLoader="javafml" +loaderVersion="[25,)" +[[mods]] +modId="mineralminingprobe" +version="1" +displayName="Base Minerals mining checks" +[[dependencies.mineralminingprobe]] +modId="baseminerals" +mandatory=true +versionRange="[2.5.1.115021,)" +ordering="AFTER" +side="BOTH" diff --git a/tools/validation/port115/mining-probe/resources/pack.mcmeta b/tools/validation/port115/mining-probe/resources/pack.mcmeta new file mode 100644 index 0000000..763e18b --- /dev/null +++ b/tools/validation/port115/mining-probe/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 5, + "description": "Disposable qualification probe" + } +} diff --git a/tools/validation/port115/requirements.txt b/tools/validation/port115/requirements.txt new file mode 100644 index 0000000..96972e7 --- /dev/null +++ b/tools/validation/port115/requirements.txt @@ -0,0 +1 @@ +nbtlib==2.0.4 diff --git a/tools/validation/port115/run_forge.py b/tools/validation/port115/run_forge.py new file mode 100644 index 0000000..ced7f12 --- /dev/null +++ b/tools/validation/port115/run_forge.py @@ -0,0 +1,126 @@ +"""Start a packaged Forge world in a disposable directory and save it after boot.""" +import argparse +import json +import hashlib +from pathlib import Path +import queue +import shutil +import subprocess +import threading +import time + +LAUNCHER = 'forge-1.15.2-31.2.57.jar' + + +def prepare(runtime, target, mods, source=None): + if source and target.resolve().is_relative_to(source.resolve()): + raise ValueError('Disposable output must be outside the source world') + target.mkdir(parents=True) + launcher = runtime.resolve() / LAUNCHER + assert launcher.is_file() and (runtime / 'libraries').is_dir(), 'Incomplete official Forge runtime' + (target / 'forge-runtime.json').write_text(json.dumps(dict(launcher=str(launcher), + sha256=hashlib.sha256(launcher.read_bytes()).hexdigest()), indent=2)) + (target / 'mods').mkdir() + for mod in mods: + shutil.copy2(mod, target / 'mods' / mod.name) + if source: + shutil.copytree(source, target / 'world') + (target / 'eula.txt').write_text('eula=true\n') + (target / 'server.properties').write_text( + 'level-name=world\nlevel-seed=8675309\nonline-mode=false\nserver-ip=127.0.0.1\n' + 'server-port=0\nview-distance=3\nmax-tick-time=0\n' + ) + + +def run(java, target, phase, upgrade=False): + command = [str(java), '-Xms256M', '-Xmx2G'] + if upgrade: + command.append('-Dbaseminerals.debugUpgrade=true') + command.extend(['-jar', json.loads((target / 'forge-runtime.json').read_text())['launcher'], 'nogui']) + if upgrade: + command.append('--forceUpgrade') + log = target / (phase + '-console.log') + messages = queue.Queue() + with log.open('w', encoding='utf-8') as stream: + process = subprocess.Popen(command, cwd=target, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, encoding='utf-8', errors='replace') + + def collect(): + for line in process.stdout: + stream.write(line) + stream.flush() + messages.put(line) + messages.put(None) + + thread = threading.Thread(target=collect, daemon=True) + thread.start() + deadline = time.monotonic() + 480 + started = False + query_lines = [] + try: + while time.monotonic() < deadline: + try: + line = messages.get(timeout=1) + except queue.Empty: + continue + if line is None: + break + query_lines.append(line.strip()) + if 'Run the command /fml confirm' in line 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 31 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') + 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/port115/verify_census.py b/tools/validation/port115/verify_census.py new file mode 100644 index 0000000..7e1240c --- /dev/null +++ b/tools/validation/port115/verify_census.py @@ -0,0 +1,74 @@ +"""Run the full-height generation probe, then compare a saved-world reload.""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +from run_forge import prepare + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('java', 'runtime', 'output', 'probe'): + parser.add_argument('--' + name, required=True, type=Path) + parser.add_argument('--mods', required=True, nargs='+', type=Path) + parser.add_argument('--seed', required=True, type=int) + parser.add_argument('--compare', type=Path, help='Independent same-seed generation report') + parser.add_argument('--provider-override', type=Path) + parser.add_argument('--world-profile', type=Path) + parser.add_argument('--disabled', default='', help='Expected disabled minerals, comma-separated, or all') + args = parser.parse_args() + jars = [*args.mods, args.probe] + prepare(args.runtime, args.output, jars) + (args.output / 'input-jars.json').write_text(json.dumps({ + p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in jars}, indent=2)) + properties = args.output / 'server.properties' + properties.write_text(properties.read_text().replace('level-seed=8675309', 'level-seed=' + str(args.seed))) + for source, relative in ((args.provider_override, 'config/baseminerals-orespawn.json'), + (args.world_profile, 'world/serverconfig/orespawn-worldgen.json')): + if source: + destination = args.output / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + if args.seed == 0: + # DedicatedServer replaces a textual zero with a random seed. An empty, + # explicitly seeded save exercises actual seed zero without editing chunks. + from nbtlib import File, Compound, String, Long, Int, Byte + world = args.output / 'world' + world.mkdir(exist_ok=True) + initial = File({'Data': Compound({'RandomSeed': Long(0), 'LevelName': String('world'), + 'DataVersion': Int(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/port115/verify_client.py b/tools/validation/port115/verify_client.py new file mode 100644 index 0000000..3ccdca4 --- /dev/null +++ b/tools/validation/port115/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.115021.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/port115/verify_generation.py b/tools/validation/port115/verify_generation.py new file mode 100644 index 0000000..5828763 --- /dev/null +++ b/tools/validation/port115/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/port115/verify_mining.py b/tools/validation/port115/verify_mining.py new file mode 100644 index 0000000..a41c9a7 --- /dev/null +++ b/tools/validation/port115/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/port115/verify_named_upgrade.py b/tools/validation/port115/verify_named_upgrade.py new file mode 100644 index 0000000..96068c9 --- /dev/null +++ b/tools/validation/port115/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/port115/verify_upgrade.py b/tools/validation/port115/verify_upgrade.py new file mode 100644 index 0000000..e3d91a2 --- /dev/null +++ b/tools/validation/port115/verify_upgrade.py @@ -0,0 +1,275 @@ +"""Check mineral states and tagged inventories across the real Forge 1.15 upgrade.""" +import argparse +from collections import Counter +from hashlib import sha256 +from io import BytesIO +import json +from pathlib import Path +import struct +import zlib + +import nbtlib +from nbtlib import Byte, ByteArray, Compound, Int, List, Short, String +import numpy as np + +from run_forge import prepare, run + +MOD = 'baseminerals:' +SECTOR = 4096 +PROBE_CHUNK = (64, 64) + + +def digest(path): + return sha256(path.read_bytes()).hexdigest() + + +def fingerprint(world): + return {p.relative_to(world).as_posix(): digest(p) for p in sorted(world.rglob('*')) if p.is_file()} + + +def saved_mineral_rules(world): + path = world / 'serverconfig/orespawn-worldgen.json' + if not path.is_file(): + return {} + ores = json.loads(path.read_text(encoding='utf-8'))['ores'] + return {key: value for key, value in ores.items() if value.get('block', '').startswith(MOD)} + + +def legacy_registry(world, registry): + root = nbtlib.load(world / 'level.dat') + ids = root['FML']['Registries']['minecraft:' + registry]['ids'] + return {int(entry['V']): str(entry['K']) for entry in ids} + + +def chunk_data(region, slot): + offset = int.from_bytes(region[slot * 4:slot * 4 + 3], 'big') * SECTOR + length, compression = struct.unpack_from('>IB', region, offset) + if compression not in (1, 2): + raise ValueError(f'Unsupported region compression {compression}') + data = zlib.decompress(region[offset + 5:offset + 4 + length], 31 if compression == 1 else 15) + return nbtlib.File.parse(BytesIO(data)) + + +def nibble_array(tag): + raw = np.frombuffer(tag.tobytes(), dtype=np.uint8) + result = np.empty(len(raw) * 2, dtype=np.uint8) + result[::2] = raw & 15 + result[1::2] = raw >> 4 + return result + + +def legacy_section(section, ids): + blocks = np.frombuffer(section['Blocks'].tobytes(), dtype=np.uint8).astype(np.uint16) + if 'Add' in section: + blocks |= nibble_array(section['Add']).astype(np.uint16) << 8 + positions = np.flatnonzero(np.isin(blocks, list(ids))) + if not len(positions): + return + metadata = nibble_array(section['Data']) + for index in positions: + block = ids[int(blocks[index])] + properties = (('level', str(metadata[index])),) if block in (MOD + 'lithium', MOD + 'silicon') else () + yield int(index), block, properties + + +def flattened_section(section): + palette = section.get('Palette', []) + targets = {i: (str(entry['Name']), tuple(sorted((k, str(v)) for k, v in entry.get('Properties', {}).items()))) + for i, entry in enumerate(palette) if str(entry['Name']).startswith(MOD)} + if not targets: + return + bits = max(4, (len(palette) - 1).bit_length()) + words = [int(word) & ((1 << 64) - 1) for word in section.get('BlockStates', [])] + for index in range(4096): + start = index * bits + word, shift = divmod(start, 64) + value = words[word] >> shift if words else 0 + if shift + bits > 64 and words: + value |= words[word + 1] << (64 - shift) + state = targets.get(value & ((1 << bits) - 1)) + if state: + yield index, *state + + +def normalized_stack(stack, legacy): + name = str(stack['id']) + tag = stack.get('tag', Compound()).unpack() + if name == 'forge:bucketfilled': + fluid = tag.get('FluidName', '').removeprefix(MOD) + if fluid not in ('lithium', 'silicon'): + return None + name = MOD + fluid + '_bucket' + del tag['FluidName'], tag['Amount'] + if not name.startswith(MOD): + return None + display = tag.get('display', {}) + if 'Name' in display: + value = display['Name'] + display['Name'] = {'text': value} if legacy else json.loads(value) + return name, int(stack['Count']), tag + + +def census(world, ids, coverage=None, require_flattened=False): + chunks = set() + blocks = {} + chests = {} + for path in sorted(world.rglob('r.*.*.mca')): + dimension = path.parent.parent.relative_to(world).as_posix() + region = path.read_bytes() + for slot in range(1024): + if not region[slot * 4:slot * 4 + 3].strip(b'\0'): + continue + root = chunk_data(region, slot) + legacy = int(root.get('DataVersion', -1)) < 1451 + level = root['Level'] + cx, cz = int(level['xPos']), int(level['zPos']) + chunk = dimension, cx, cz + if coverage is not None and chunk not in coverage: + continue + if require_flattened: + assert int(root.get('DataVersion', -1)) >= 2230, f'Chunk did not reach 1.15.2: {chunk}' + chunks.add(chunk) + for section in level.get('Sections', []): + if 'Blocks' in section: + assert not require_flattened, f'Numeric block array survived in {chunk}' + states = legacy_section(section, ids) + else: + states = flattened_section(section) + for index, name, properties in states: + x, y, z = index & 15, (index >> 8) + int(section['Y']) * 16, (index >> 4) & 15 + blocks[dimension, 16 * cx + x, y, 16 * cz + z] = name, properties + for entity in level.get('TileEntities', []): + if 'Items' not in entity: + continue + items = {int(stack['Slot']): result for stack in entity['Items'] + if (result := normalized_stack(stack, legacy))} + if items: + chests[dimension, int(entity['x']), int(entity['y']), int(entity['z'])] = items + return chunks, blocks, chests + + +def signed(value): + return value if value < 128 else value - 256 + + +def set_nibble(array, index, value): + shift = (index & 1) * 4 + prior = int(array[index >> 1]) & 255 + array[index >> 1] = signed((prior & ~(15 << shift)) | value << shift) + + +def add_fixture(world, probe_chunk=PROBE_CHUNK): + cx, cz = probe_chunk + region_path = world / 'region' / f'r.{cx // 32}.{cz // 32}.mca' + slot = (cx & 31) + (cz & 31) * 32 + region = bytearray(region_path.read_bytes()) + chunk = chunk_data(region, slot) + level = chunk['Level'] + assert int(level['xPos']) == cx and int(level['zPos']) == cz + y = 224 + assert all(int(s['Y']) != y // 16 for s in level['Sections']) + section = Compound(Y=Byte(y // 16), Blocks=ByteArray([0] * 4096), + Data=ByteArray([0] * 2048), Add=ByteArray([0] * 2048), + BlockLight=ByteArray([0] * 2048), SkyLight=ByteArray([-1] * 2048)) + level['Sections'].append(section) + solids = sorted((name, id_) for id_, name in legacy_registry(world, 'blocks').items() if name.startswith(MOD)) + + def put(index, id_, meta=0): + section['Blocks'][index] = signed(id_ & 255) + set_nibble(section['Add'], index, id_ >> 8) + set_nibble(section['Data'], index, meta) + + for index, (name, id_) in enumerate(solids, 32): + put(index, id_) + fluid_ids = {name: id_ for name, id_ in solids if name in (MOD + 'lithium', MOD + 'silicon')} + for row, id_ in enumerate(fluid_ids.values(), 4): + for level_value in range(1, 16): + put(row * 16 + level_value, id_, level_value) + item_names = sorted(name for name in legacy_registry(world, 'items').values() if name.startswith(MOD)) + stacks = [Compound(id=String(name), Count=Byte(index % 3 + 1), Damage=Short(0), + tag=Compound(MigrationTest=String(name))) + for index, name in enumerate(item_names)] + for fluid in ('lithium', 'silicon'): + stacks.append(Compound(id=String('forge:bucketfilled'), Count=Byte(1), Damage=Short(0), + tag=Compound(FluidName=String(fluid), Amount=Int(1000), MigrationTest=String(fluid)))) + entities = List[Compound](level.get('TileEntities', [])) + level['TileEntities'] = entities + for index, start in enumerate(range(0, len(stacks), 27)): + chest_x, chest_z = index * 3 + 1, 8 + put(chest_z * 16 + chest_x, 54, 2) + inventory = List[Compound](stacks[start:start + 27]) + for slot_id, stack in enumerate(inventory): + stack['Slot'] = Byte(slot_id) + entities.append(Compound(id=String('minecraft:chest'), x=Int(cx * 16 + chest_x), + y=Int(y), z=Int(cz * 16 + chest_z), Items=inventory)) + raw = BytesIO() + chunk.write(raw) + compressed = zlib.compress(raw.getvalue()) + payload = struct.pack('>IB', len(compressed) + 1, 2) + compressed + sectors = (len(payload) + SECTOR - 1) // SECTOR + offset = len(region) // SECTOR + assert len(region) % SECTOR == 0 and sectors < 256 + region[slot * 4:slot * 4 + 4] = offset.to_bytes(3, 'big') + bytes([sectors]) + region.extend(payload.ljust(sectors * SECTOR, b'\0')) + region_path.write_bytes(region) + return len(solids), len(stacks) + + +def compare(before, after): + original_chunks, original_blocks, original_chests = before + chunks, blocks, chests = after + difference = {position: [original_blocks.get(position), blocks.get(position)] + for position in original_blocks.keys() | blocks.keys() + if original_blocks.get(position) != blocks.get(position)} + if difference: + preview = list(sorted(difference.items()))[:12] + raise AssertionError(f'{len(difference)} mineral coordinates or states changed. First changes {preview}') + assert original_chests == chests, 'Mineral chest items, counts or tags changed' + assert chunks == original_chunks, f'{len(original_chunks - chunks)} original chunks are missing' + return {'chunks': len(chunks), 'blocks': dict(sorted(Counter(b[0] for b in blocks.values()).items())), + 'chests': len(chests), 'stacks': sum(map(len, chests.values())), + 'coordinate_sha256': sha256(repr(sorted(blocks.items())).encode()).hexdigest()} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('java', 'runtime', 'output', 'source'): + parser.add_argument('--' + name, required=True, type=Path) + parser.add_argument('--mods', required=True, nargs='+', type=Path) + parser.add_argument('--probe-chunk', nargs=2, type=int, default=PROBE_CHUNK) + parser.add_argument('--minimum-blocks', type=int, default=1000) + parser.add_argument('--natural-open', action='store_true', + help='Open normally before converting the remaining unloaded chunks') + args = parser.parse_args() + before_source = fingerprint(args.source) + prepare(args.runtime, args.output, args.mods, args.source) + target = args.output / 'world' + ids = {id_: name for id_, name in legacy_registry(target, 'blocks').items() if name.startswith(MOD)} + forms = add_fixture(target, args.probe_chunk) + before = census(target, ids) + rules = saved_mineral_rules(target) + assert len(before[1]) >= args.minimum_blocks and len(ids) > 0, 'No meaningful source mineral census' + source_manifest = {'source': str(args.source), 'fingerprint': before_source, 'registry': ids, + 'added_forms': forms, 'jars': {p.name: digest(p) for p in args.mods}} + (args.output / 'sources.json').write_text(json.dumps(source_manifest, indent=2)) + result = {} + try: + if args.natural_open: + run(args.java, args.output, 'natural-open') + result['natural-open'] = compare(before, census(target, ids, before[0])) + if rules: + assert saved_mineral_rules(target) == rules, 'Saved OreSpawn mineral rules changed' + for phase in ('first', 'reload'): + run(args.java, args.output, phase, upgrade=True) + result[phase] = compare(before, census(target, ids, before[0], require_flattened=True)) + if rules: + assert saved_mineral_rules(target) == rules, 'Saved OreSpawn mineral rules changed' + result[phase]['saved_rules'] = len(rules) + print(f"{phase} census PASS {result[phase]}", flush=True) + (args.output / 'results.json').write_text(json.dumps(result, indent=2)) + finally: + assert before_source == fingerprint(args.source), 'Source fixture changed' + + +if __name__ == '__main__': + main()