diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 896d4cbd4..a8bceecc6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,8 @@ jobs: echo "minecraft_version=$(value minecraft_version)" >> "$GITHUB_OUTPUT" echo "gradle_java_version=$(value gradle_java_version)" >> "$GITHUB_OUTPUT" echo "artifact_prefix=SkysBuildingPieces-$(value mod_version)" >> "$GITHUB_OUTPUT" + echo "grass_source_mode=$(sed -n 's/^source.mode=//p' gradle/grass-slabs-release.properties)" >> "$GITHUB_OUTPUT" + echo "grass_source_commit=$(sed -n 's/^source.commit=//p' gradle/grass-slabs-release.properties)" >> "$GITHUB_OUTPUT" - name: Install target Java toolchain uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 @@ -66,12 +68,30 @@ jobs: - name: Make the wrapper executable run: chmod +x ./gradlew + - name: Check out the pinned Grass Slabs source + if: steps.target.outputs.grass_source_mode == 'checkout' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: MinecraftModDevelopmentMods/SkysGrassSlabs + ref: ${{ steps.target.outputs.grass_source_commit }} + path: .gradle/content-sources/grass-slabs + persist-credentials: false + + - name: Build the pinned Grass Slabs dependency + if: steps.target.outputs.grass_source_mode == 'checkout' + working-directory: .gradle/content-sources/grass-slabs + run: chmod +x ./gradlew && ./gradlew assemble --no-daemon --stacktrace + - name: Build, test, and audit release artifacts + env: + ORG_GRADLE_PROJECT_grassSlabsDirectory: .gradle/content-sources/grass-slabs run: >- ./gradlew clean check integrationTest build javadoc verifyReleaseArtifacts writeReleaseChecksums verifyEclipseProductionClasspath --no-daemon --stacktrace - name: Replay artifact checks offline + env: + ORG_GRADLE_PROJECT_grassSlabsDirectory: .gradle/content-sources/grass-slabs run: >- ./gradlew assemble verifyReleaseArtifacts writeReleaseChecksums --offline --no-daemon --stacktrace diff --git a/CHANGELOG.md b/CHANGELOG.md index feeab71a7..dbfb8cfed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 0.3.10.112021 + +- Stop snow layers hovering over bottom slabs, steps, corners and lowered paths. +- Clear old floating snow as the world updates, keeping valid snow on full-height tops. +- Prevent a crash when chunks are unloaded and loaded again quickly. +- Snow-covered steps and corners give the grass beneath them a matching snow cap. +- Grass and dirt pieces pick up snow from higher terraces and exposed cold ground. +- Recipes for different materials, shapes and quantities have separate recipe-book entries. +- Native slab-to-block recipes take precedence when another mod already supplies the same recipe. + +## 0.3.9.112021 + +- Directional slab placement can be turned off from the Mods menu. +- Vanilla items stay in their usual creative tabs. + ## 0.3.8.112021 - Added the missing recipe-book unlocks for crafting and rebuilding pieces. diff --git a/README.md b/README.md index 3f2c4e6af..47c38ce28 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,11 @@ Pieces doesn't generate terrain. pieces; corners are eighth-block pieces. - Matching pieces can join into supported larger shapes or a full block. Different materials don't combine. -- Find the pieces, including the vanilla items the mod reuses, in the - **Sky's Building Pieces** creative tab. +- Find the new pieces in the **Sky's Building Pieces** creative tab. Vanilla + pieces stay in their usual tabs. +- To use ordinary horizontal placement for regular slabs, open **Mods → Sky's + Building Pieces → Config** and turn off **Directional slab placement**. Restart + Minecraft after saving. Walls have lower panels with posts at ends, corners and junctions. A torch or block above keeps a supporting post. Matching glass walls form a continuous @@ -27,6 +30,9 @@ run, with borders at posts, exposed ends and colour changes. Dirt and grass steps and corners are included too. Grass follows biome colours, spreads and decays much like vanilla grass. Plants need a complete upper face. +Snow-covered pieces also give the exposed grass beneath them a snow cap. Snow +appearance follows nearby snow and exposed cold ground, without changing saved +piece orientations. Use a shovel on an uncovered dirt or grass step or corner to turn it into a matching path piece. Its footprint stays the same, with a one-pixel lower top. Flattening a grass piece also turns an ordinary grass block directly beneath diff --git a/build.gradle b/build.gradle index 529913f34..87a056cfe 100644 --- a/build.gradle +++ b/build.gradle @@ -14,6 +14,8 @@ plugins { id 'net.minecraftforge.gradle' version '7.0.34' } +apply from: 'gradle/legacy-tools.gradle' + group = project.mod_group version = project.mod_version base.archivesName = 'SkysBuildingPieces' @@ -34,6 +36,7 @@ ext.functional_version = versionParts[0..2].join('.') ext.display_version = project.mod_version ext.release_tag = project.mod_version def pinnedJava8 = providers.environmentVariable('SBP_JAVA8_HOME') + .orElse(providers.environmentVariable('JAVA_HOME_8_X64')) // Gradle 9.6.1's ordinary language-level selector prefers the newest cached // Java 8. This opt-in specific installation keeps local/CI qualification exact. def exactJava8Spec = pinnedJava8.isPresent() ? diff --git a/docs/BUILDING.md b/docs/BUILDING.md index be70bc55f..280333737 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -3,6 +3,9 @@ Run Gradle with Java 17. Production code and Minecraft use Java 8; the tested toolchain is Temurin 8.0.502+7. Use the included Gradle wrapper. +The legacy Forge setup verifies its pinned SpecialSource tool from Maven Central. +Run once online before using an empty build cache offline. + ```text gradlew clean check build javadoc verifyReleaseArtifacts writeReleaseChecksums gradlew genEclipseRuns eclipse verifyEclipseProductionClasspath @@ -19,15 +22,19 @@ the launches after changing dependencies. The generated configuration uses processed resources and keeps test code out of ordinary game runs. - `runClient` and `runServer` run Building Pieces on its own. -- `runGrassSlabsClient` and `runGrassSlabsServer` also load the released Grass +- `runGrassSlabsClient` and `runGrassSlabsServer` also load the pinned Grass Slabs jar recorded in `gradle/grass-slabs-release.properties`. - `runMineralogyClient` and `runMineralogyServer` use the optional Mineralogy and OreSpawn jars recorded in `gradle/mineralogy-runtime.properties`. -Each profile has its own game folder. Grass Slabs is downloaded from its public -release, checked against its SHA-256 and mapped to development names. There is -no sibling source build to prepare. The published Grass Slabs jar remains -unchanged, and none of its classes are bundled into Building Pieces. +Each profile has its own game folder. Grass Slabs is checked against its SHA-256 +and mapped to development names. This candidate uses Grass Slabs 1.2.0 from the +sibling 1.12 checkout: run `gradlew assemble` there first. Its source commit and +jar checksum must match `gradle/grass-slabs-release.properties`. Use +`-PgrassSlabsDirectory=` for another location. CI builds that exact +commit before running these checks. The source jar stays unchanged, and none +of its classes are bundled into Building Pieces. The lock also supports a +published Maven jar when `source.mode=release`. For the Mineralogy profile, supply the jars named in its lock file, or use `-PmineralogyRuntimeJar=` and `-PorespawnRuntimeJar=` to select matching @@ -36,7 +43,7 @@ copies. They must pass the recorded checksums. ## Runtime checks `check` runs the unit suite and disposable server checks, both standalone and -with the released Grass Slabs jar. `integrationGrassSlabsClientProcess` checks +with the pinned Grass Slabs jar. `integrationGrassSlabsClientProcess` checks the combined client models. `integrationMineralogyTest` and `integrationMineralogyClientProcess` cover the optional rock pieces when the locked native jars are available. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index dc9cd8a1a..b932771ff 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1,7 +1,14 @@ # Configuration Forge creates `config/skysbuildingpieces.cfg`. Stop the game or server before -editing it, then restart. +editing it, then restart. On the client, the same settings are in +**Mods → Sky's Building Pieces → Config**. + +`gameplay.directionalSlabPlacement=true` + +Click the centre or edge of a face to choose which way a regular slab sits. +Turn this off for normal horizontal placement, then restart. Existing pieces +and separately crafted vertical slabs keep their shape and behaviour. `compat.forceReplaceBuildingBricksPieces=false` diff --git a/docs/GAMEPLAY.md b/docs/GAMEPLAY.md index 7905d5a2f..a77bc9a92 100644 --- a/docs/GAMEPLAY.md +++ b/docs/GAMEPLAY.md @@ -1,5 +1,10 @@ # Pieces and recipes +Snow layers need a complete supporting top at full-block height. Lower grass +and dirt pieces use their snow-covered appearance instead. Floating layers left +by an earlier build clear during normal soil ticks or block updates; the piece +and its orientation stay in place. + Mineralogy rock steps and corners are included automatically when Mineralogy is installed. Three matching full rocks diagonally across the crafting grid make twelve steps; two steps side by side make four corners. Vertical pairs @@ -7,8 +12,8 @@ rebuild corners into steps and steps into Mineralogy's existing slabs. Disabled native slab types are not used by recipes or smoothing. The rock steps and corners remain craftable from full blocks. -Find the pieces in the Sky's Building Pieces creative tab. It includes the -vanilla pieces reused by the catalogue. Separate vertical slab items, old +Find the new pieces in the Sky's Building Pieces creative tab. Reused vanilla +blocks stay in their usual tabs. Separate vertical slab items, old templates and recovery holders stay hidden. All custom walls have lower connecting panels and raised posts. diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index c17577b88..1a38e97e3 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -19,6 +19,9 @@ Sky's Terrain Smoother uses this lookup without depending on palette internals. Building Pieces never generates terrain itself. It optionally joins Grass Slabs' grass-form integration, using 1.1.1.112021 or later on Minecraft 1.12.2. It works without either Grass Slabs or Terrain Smoother installed. +With Grass Slabs 1.2 or later, the mods also share physical snow-form recognition +and calculated snow appearance. Older Grass Slabs versions retain their existing +grass integration; Building Pieces uses its standalone snow rules with them. Mineralogy is supported directly. Its presence adds 35 fixed rock-piece palettes during pre-initialization; no add-on or compile-time Mineralogy diff --git a/gradle.properties b/gradle.properties index ddf477307..ec14c002b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,7 +20,7 @@ release_enabled=true curseforge_project_id=1754162 mod_name=Sky's Building Pieces mod_license=LGPL-2.1-only -mod_version=0.3.8.112021 +mod_version=0.3.10.112021 mod_group=zone.moddev.mc.skysbuildingpieces mod_authors=SkyBlade1978 mod_description=Extra building shapes for vanilla materials, with built-in Mineralogy support when installed. No world generation. diff --git a/gradle/grass-slabs-release.gradle b/gradle/grass-slabs-release.gradle index e63fe9f3b..0e92c2412 100644 --- a/gradle/grass-slabs-release.gradle +++ b/gradle/grass-slabs-release.gradle @@ -12,18 +12,35 @@ if (lock.coordinate != "zone.moddev.mc.skysgrassslabs:SkysGrassSlabs:${lock.vers throw new GradleException('The released Grass Slabs dependency needs its public version and checksum') } +boolean checkoutSource = lock.getProperty('source.mode', 'release') == 'checkout' +def sourceDirectory = file(providers.gradleProperty('grassSlabsDirectory') + .getOrElse(lock.getProperty('source.directory', '../../SkysGrassSlabs112/SkysGrassSlabs'))) configurations { grassSlabsPublishedRelease { transitive = false } } -dependencies { grassSlabsPublishedRelease lock.coordinate } -def publishedJar = providers.provider { configurations.grassSlabsPublishedRelease.singleFile } +if (!checkoutSource) { + dependencies { grassSlabsPublishedRelease lock.coordinate } +} +def publishedJar = providers.provider { + checkoutSource ? new File(sourceDirectory, "build/libs/SkysGrassSlabs-${lock.version}.jar") + : configurations.grassSlabsPublishedRelease.singleFile +} def developmentJar = layout.projectDirectory.file( ".gradle/released-content/SkysGrassSlabs-${lock.version}-deobf.jar") def verifyRelease = tasks.register('verifyGrassSlabsRelease') { group = 'verification' - description = 'Checks the exact public Grass Slabs jar used by the optional development profile.' + description = 'Checks the exact Grass Slabs jar used by the optional development profile.' inputs.file publishedJar inputs.file 'gradle/grass-slabs-release.properties' doLast { File source = publishedJar.get() + if (checkoutSource) { + String commit = providers.exec { + workingDir sourceDirectory + commandLine 'git', 'rev-parse', 'HEAD' + }.standardOutput.asText.get().trim() + if (commit != lock.getProperty('source.commit')) { + throw new GradleException('The Grass Slabs source checkout does not match its pinned commit') + } + } String actual = MessageDigest.getInstance('SHA-256').digest(Files.readAllBytes(source.toPath())) .encodeHex().toString().toUpperCase(Locale.ROOT) if (actual != lock.sha256) { diff --git a/gradle/grass-slabs-release.properties b/gradle/grass-slabs-release.properties index ed42b7491..896220695 100644 --- a/gradle/grass-slabs-release.properties +++ b/gradle/grass-slabs-release.properties @@ -1,5 +1,7 @@ -# Public main jar, used only for optional development and integration checks. -version=1.1.2.112021 -coordinate=zone.moddev.mc.skysgrassslabs:SkysGrassSlabs:1.1.2.112021 -sha256=6F056EA5E4ADCE363D835955967ECC4ECA93A153645A32140DE3FC7655529D9C -source.commit=b2636d8a67efa3f257a8a69293ce513e979010fd +# Released Grass Slabs dependency for development and integration checks. +version=1.2.0.112021 +coordinate=zone.moddev.mc.skysgrassslabs:SkysGrassSlabs:1.2.0.112021 +sha256=0A92C6A9BF28808F2C55A1A3FC00D08D1CBDA7F4910432A3846A839BE9FB497E +source.commit=2780de0ef41fbf7e2ab8336e76c4a4b60919716a +source.mode=checkout +source.directory=../../SkysGrassSlabs112/SkysGrassSlabs diff --git a/gradle/legacy-tools.gradle b/gradle/legacy-tools.gradle new file mode 100644 index 000000000..1f9246731 --- /dev/null +++ b/gradle/legacy-tools.gradle @@ -0,0 +1,58 @@ +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.security.MessageDigest +import java.util.jar.JarFile + +// The old MCP download URL can return HTML. Use the identical, pinned tool from Maven Central. +def toolSha256 = '9105207CC68FBBA768B314FA8584F7C63DE2CF664F1FD50AAAB4A386975A88BD' +def toolSha1 = 'a70987737b33a1d828713fb7cec4622455618fd9' +def toolUrl = 'https://repo.maven.apache.org/maven2/net/md-5/SpecialSource/1.8.3/SpecialSource-1.8.3-shaded.jar' +def cacheRoot = providers.gradleProperty('legacyToolCacheRoot').map { file(it) }.getOrElse( + new File(gradle.gradleUserHomeDir, 'caches/minecraftforge/forgegradle/mavenizer')) +def tool = new File(cacheRoot, 'caches/maven/mcp-tools/net/md-5/SpecialSource/1.8.3/SpecialSource-1.8.3-shaded.jar') +def checksum = new File(tool.path + '.sha1') +def digest = { byte[] bytes -> MessageDigest.getInstance('SHA-256').digest(bytes).encodeHex().toString().toUpperCase() } + +tool.parentFile.mkdirs() +new RandomAccessFile(new File(tool.parentFile, 'specialsource-bootstrap.lock'), 'rw').withCloseable { lockFile -> + def lock = lockFile.channel.lock() + try { + byte[] existing = tool.isFile() ? tool.bytes : null + if (existing == null || digest(existing) != toolSha256) { + if (gradle.startParameter.offline) { + throw new GradleException('The pinned legacy SpecialSource tool is missing or invalid. Run once online to restore it.') + } + def connection = new URL(toolUrl).openConnection() + connection.connectTimeout = 15000 + connection.readTimeout = 30000 + byte[] downloaded = connection.inputStream.withCloseable { it.bytes } + if (digest(downloaded) != toolSha256) { + throw new GradleException('The legacy SpecialSource download did not match its pinned SHA-256.') + } + // Preserve a rejected cache entry before replacing only this one tool. + if (existing != null) { + File rejected = new File(projectDir, '.gradle/legacy-tools/rejected/' + digest(existing) + '.jar') + rejected.parentFile.mkdirs() + if (!rejected.exists()) rejected.bytes = existing + } + def temporary = Files.createTempFile(tool.parentFile.toPath(), 'specialsource-', '.tmp') + try { + Files.write(temporary, downloaded) + new JarFile(temporary.toFile()).withCloseable { archive -> + if (archive.manifest.mainAttributes.getValue('Main-Class') != 'net.md_5.specialsource.SpecialSource') { + throw new GradleException('The legacy build tool has no expected entry point.') + } + } + Files.move(temporary, tool.toPath(), StandardCopyOption.REPLACE_EXISTING) + } finally { + Files.deleteIfExists(temporary) + } + logger.lifecycle('Restored the verified legacy SpecialSource build tool from Maven Central.') + } + if (!checksum.isFile() || checksum.getText('UTF-8').trim() != toolSha1) { + checksum.setText(toolSha1, 'UTF-8') + } + } finally { + lock.release() + } +} diff --git a/gradle/release.gradle b/gradle/release.gradle index fb0b11421..e3147afbf 100644 --- a/gradle/release.gradle +++ b/gradle/release.gradle @@ -33,6 +33,11 @@ tasks.register('verifyReleaseBundleContract') { dependsOn tasks.named('writeReleaseChecksums') doLast { File bundle = layout.buildDirectory.dir('release-bundle-test').get().asFile + if (bundle.canonicalFile.parentFile != layout.buildDirectory.get().asFile.canonicalFile) { + throw new GradleException('Release contract output must stay inside the build directory') + } + // A new version must not inherit files from an earlier contract test. + project.delete(bundle) List filenames = releaseFiles.get().collect { it.toString() } copy { from layout.buildDirectory.dir('libs') diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ClientProbe.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ClientProbe.java index b26456e2c..68291c49f 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ClientProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ClientProbe.java @@ -17,6 +17,13 @@ public final class ClientProbe extends ProbeProxy { public void init() { if (System.getProperty("skysbuildingpieces.integrationPhase", "").startsWith("client")) { + if (org.lwjgl.opengl.Display.isCreated()) { + org.lwjgl.opengl.Display.setLocation(-10000, -10000); + } + if (org.lwjgl.input.Mouse.isCreated()) { + org.lwjgl.input.Mouse.setGrabbed(false); + } + Minecraft.getMinecraft().getSession().setProperties(new com.mojang.authlib.properties.PropertyMap()); MinecraftForge.EVENT_BUS.register(this); } } @@ -75,8 +82,8 @@ public void tick(TickEvent.ClientTickEvent event) { throw new AssertionError("Retired template in mod tab"); } } - if (!entries.contains("minecraft:wooden_slab:0")) { - throw new AssertionError("Reused oak slab missing from mod tab"); + if (entries.stream().anyMatch(key -> key.startsWith("minecraft:"))) { + throw new AssertionError("Vanilla content appears in the Building Pieces tab"); } if (entries.contains("skysbuildingpieces:legacy_piece_holder:0")) { throw new AssertionError("Recovery holder in mod tab"); @@ -89,7 +96,9 @@ public void tick(TickEvent.ClientTickEvent event) { System.out.println("BUILDING_PIECES_CREATIVE_TAB_PASS entries=" + creative.size()); RecipePreviewModels.check(minecraft); + SnowVisualChecks.run(minecraft); + ConfigScreenChecks.run(minecraft); int checked = 0; for (PieceBlock block : Pieces.BLOCKS.values()) { diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ConfigScreenChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ConfigScreenChecks.java new file mode 100644 index 000000000..056b6bfdd --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ConfigScreenChecks.java @@ -0,0 +1,58 @@ +package zone.moddev.mc.skysbuildingpieces.probe; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fml.client.FMLClientHandler; +import net.minecraftforge.fml.client.IModGuiFactory; +import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.client.config.IConfigElement; +import net.minecraftforge.fml.client.event.ConfigChangedEvent; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.ModContainer; +import zone.moddev.mc.skysbuildingpieces.SkysBuildingPieces; +import zone.moddev.mc.skysbuildingpieces.config.BuildingPiecesConfig; + +final class ConfigScreenChecks { + private ConfigScreenChecks() { + } + + static void run(Minecraft minecraft) throws ReflectiveOperationException { + ModContainer mod = Loader.instance().getIndexedModList().get(SkysBuildingPieces.ID); + IModGuiFactory factory = FMLClientHandler.instance().getGuiFactoryFor(mod); + GuiConfig screen = (GuiConfig) factory.createConfigGui(minecraft.currentScreen); + if (!screen.allRequireMcRestart || screen.configElements.size() != 2) { + throw new AssertionError("Building Pieces should have two restart-required settings"); + } + + for (IConfigElement entry : screen.configElements) { + String key = entry.getLanguageKey(); + if (I18n.format(key).equals(key) || I18n.format(key + ".tooltip").equals(key + ".tooltip")) { + throw new AssertionError("Missing Building Pieces setting label or tooltip " + key); + } + } + + Configuration configuration = BuildingPiecesConfig.configuration(); + Property placement = configuration.getCategory("gameplay").get("directionalSlabPlacement"); + if (!placement.getBoolean() || !BuildingPiecesConfig.directionalSlabPlacement()) { + throw new AssertionError("Directional slab placement must default to on"); + } + try { + placement.set(false); + MinecraftForge.EVENT_BUS.post(new ConfigChangedEvent.OnConfigChangedEvent( + SkysBuildingPieces.ID, null, false, true)); + Configuration saved = new Configuration(configuration.getConfigFile()); + saved.load(); + if (saved.get("gameplay", "directionalSlabPlacement", true).getBoolean() + || !BuildingPiecesConfig.directionalSlabPlacement()) { + throw new AssertionError("The placement option should save for the next restart"); + } + } finally { + placement.set(true); + BuildingPiecesConfig.saveChanges(); + } + System.out.println("BUILDING_PIECES_CONFIG_SCREEN_PASS default_on=true saves_off=true restores_on=true"); + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ExistingWorldChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ExistingWorldChecks.java new file mode 100644 index 000000000..a1767c197 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/ExistingWorldChecks.java @@ -0,0 +1,65 @@ +package zone.moddev.mc.skysbuildingpieces.probe; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.List; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; + +/** Load a sealed fixture's existing chunk index without recreating gameplay test objects. */ +public final class ExistingWorldChecks { + private final WorldServer world; + private final List chunks; + private int next; + private int settle; + + ExistingWorldChecks(WorldServer world) throws IOException { + this.world = world; + chunks = Files.readAllLines(new File("upgrade-index.csv").toPath(), StandardCharsets.UTF_8); + if (chunks.isEmpty()) { + throw new IllegalStateException("The saved-world fixture has no indexed chunks"); + } + MinecraftForge.EVENT_BUS.register(this); + } + + @SubscribeEvent + public void tick(TickEvent.ServerTickEvent event) { + if (event.phase != TickEvent.Phase.END) { + return; + } + try { + for (int batch = 0; batch < 8 && next < chunks.size(); batch++) { + String[] point = chunks.get(next++).split(","); + if (point.length != 2) { + throw new IllegalStateException("Malformed saved-world chunk index"); + } + net.minecraft.world.chunk.Chunk chunk = world.getChunk( + Integer.parseInt(point[0]), Integer.parseInt(point[1])); + world.getChunkProvider().queueUnload(chunk); + } + if (next == chunks.size() && ++settle >= 40) { + net.minecraft.world.storage.ThreadedFileIOBase.getThreadedIOInstance().waitForFinish(); + try (PrintWriter out = new PrintWriter(new File(world.getSaveHandler().getWorldDirectory(), + "previous-version-upgrade.pass"), "UTF-8")) { + out.println("indexed_chunks=" + chunks.size()); + net.minecraft.world.storage.WorldSavedData state = + zone.moddev.mc.skysbuildingpieces.legacy.PiecesWorldState.get(world); + out.println("state=" + state.writeToNBT(new net.minecraft.nbt.NBTTagCompound())); + } + System.out.println("BUILDING_PIECES_EXISTING_WORLD_PASS chunks=" + chunks.size()); + MinecraftForge.EVENT_BUS.unregister(this); + world.getMinecraftServer().initiateShutdown(); + } + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Saved-world verification was interrupted", failure); + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException("Saved-world reload verification failed", failure); + } + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/MineralogyChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/MineralogyChecks.java index 4ce3c3528..bcaf69c38 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/MineralogyChecks.java +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/MineralogyChecks.java @@ -13,7 +13,7 @@ final class MineralogyChecks { private MineralogyChecks() { } - static void run() { + static void run(net.minecraft.world.WorldServer world) { Catalogue.Module rocks = Catalogue.INSTANCE.modules.get("mineralogy"); if (!Loader.isModLoaded("mineralogy")) { require(rocks == null, "Mineralogy pieces registered without Mineralogy"); @@ -39,6 +39,7 @@ static void run() { require(facing(bottom) == EnumFacing.UP && facing(top) == EnumFacing.DOWN, "native slab orientation changed"); require(Pieces.stack(bottom, 1).getItemDamage() == 0, "native slab item metadata changed"); + nativeRecipe(world, material.id, bottom); } for (Catalogue.Palette palette : rocks.palettes) { for (String material : palette.materials) { @@ -56,6 +57,38 @@ static void run() { System.out.println("MINERALOGY_CORE_PASS palettes=" + registered + " states=" + states + " addon=false"); } + private static void nativeRecipe(net.minecraft.world.WorldServer world, String material, IBlockState slab) { + net.minecraft.util.ResourceLocation previousId = new net.minecraft.util.ResourceLocation( + "skysbuildingpieces", material.replace(':', '/') + "/slab_recombination"); + net.minecraft.item.crafting.IRecipe previous = net.minecraft.item.crafting.CraftingManager.REGISTRY + .getObject(previousId); + require(previous != null && !previous.isDynamic(), + "old slab recipe ID remains craftable: " + previousId + " -> " + + (previous == null ? "missing" : previous.getRegistryName())); + net.minecraft.inventory.InventoryCrafting grid = RecipeChecks.grid(2); + grid.setInventorySlotContents(0, Pieces.stack(slab, 1)); + grid.setInventorySlotContents(1, Pieces.stack(slab, 1)); + int matches = 0; + for (net.minecraft.item.crafting.IRecipe recipe : net.minecraft.item.crafting.CraftingManager.REGISTRY) { + if (recipe.matches(grid, world)) { + require(recipe == previous, "the old recipe ID resolves to the one active craft: " + previousId); + require(net.minecraft.item.ItemStack.areItemStacksEqual( + previous.getRecipeOutput(), recipe.getCraftingResult(grid)), "native recombination output"); + matches++; + } + } + require(matches == 1, "native slab crafting has one owner"); + net.minecraft.nbt.NBTTagCompound saved = new net.minecraft.nbt.NBTTagCompound(); + net.minecraft.nbt.NBTTagList recipes = new net.minecraft.nbt.NBTTagList(); + recipes.appendTag(new net.minecraft.nbt.NBTTagString(previousId.toString())); + saved.setTag("recipes", recipes); + net.minecraft.stats.RecipeBookServer book = new net.minecraft.stats.RecipeBookServer(); + book.read(saved); + require(book.isUnlocked(previous), "saved recipe book retains the historical Sky recipe ID"); + require(((net.minecraftforge.registries.ForgeRegistry) net.minecraftforge.fml.common.registry.ForgeRegistries.RECIPES) + .isLocked(), "recipe alias recovery preserves Forge's registry lock"); + } + private static EnumFacing facing(IBlockState state) { for (IProperty property : state.getPropertyKeys()) { if (property.getName().equals("facing")) { diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RecipeChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RecipeChecks.java index 489601239..6468d098b 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RecipeChecks.java +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RecipeChecks.java @@ -20,6 +20,7 @@ public final class RecipeChecks { public static void run(WorldServer world) { preflight(world); + verifyBookGroups(); RecombinationChecks.run(world); int recombined = 0; @@ -237,14 +238,35 @@ private static void assertManager(InventoryCrafting grid, WorldServer world, Ite require(ItemStack.areItemStacksEqual(expected, CraftingManager.findMatchingResult(grid, world)), "crafting manager selects " + label); + int matches = 0; for (IRecipe candidate : net.minecraftforge.fml.common.registry.ForgeRegistries.RECIPES.getValuesCollection()) { if (candidate.matches(grid, world)) { + matches++; ItemStack actual = candidate.getCraftingResult(grid); require(ItemStack.areItemStacksEqual(expected, actual), "conflicting recipe " + label + " / " + candidate.getClass().getName() + " / " + actual); } } + require(matches == 1, "duplicate recipes for " + label + ": " + matches); + } + + private static void verifyBookGroups() { + java.util.Map results = new java.util.HashMap(); + for (IRecipe recipe : CraftingManager.REGISTRY) { + if (recipe.getRegistryName() == null + || !recipe.getRegistryName().getNamespace().equals("skysbuildingpieces") + || recipe.getGroup().isEmpty()) { + continue; + } + ItemStack output = recipe.getRecipeOutput(); + String identity = output.getItem().getRegistryName() + "/" + output.getMetadata() + "/" + output.getCount(); + String previous = results.putIfAbsent(recipe.getGroup(), identity); + require(previous == null || previous.equals(identity), + "recipe book groups unrelated results: " + recipe.getGroup()); + } + require(!results.isEmpty(), "recipe book groups were checked"); + System.out.println("BUILDING_PIECES_BOOK_GROUPS_PASS results=" + results.size()); } private static void preflight(WorldServer world) { diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RuntimeProbe.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RuntimeProbe.java index a9edfefb0..e3da04d52 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RuntimeProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/RuntimeProbe.java @@ -92,12 +92,21 @@ public void tick(TickEvent.ServerTickEvent event) { if (phase == null) { throw new AssertionError("Unconfigured runtime probe"); } + if (phase.equals("snow-support")) { + SnowSettlementChecks.run(world); + server.initiateShutdown(); + return; + } if (phase.equals("path-upgrade")) { PathChecks.savedPieces(world, true); System.out.println("BUILDING_PIECES_PATH_UPGRADE_PASS"); server.initiateShutdown(); return; } + if (phase.equals("upgrade-existing")) { + new ExistingWorldChecks(world); + return; + } if (phase.startsWith("sylvester")) { new WorldAuditProbe(world, phase.equals("sylvester-reload")); return; @@ -129,8 +138,11 @@ public void tick(TickEvent.ServerTickEvent event) { rawStoredInventory(world); GameplayChecks.run(world); PathChecks.run(world); + SnowChecks.run(world); + SnowSettlementChecks.run(world); + SnowHarvestChecks.run(world); SharedGrassChecks.run(world); - MineralogyChecks.run(); + MineralogyChecks.run(world); if (!phase.startsWith("client")) { DirtCoverageChecks.run(world); diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowChecks.java new file mode 100644 index 000000000..face3035a --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowChecks.java @@ -0,0 +1,132 @@ +package zone.moddev.mc.skysbuildingpieces.probe; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockGrass; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Biomes; +import net.minecraft.init.Blocks; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.ChunkCache; +import net.minecraft.world.WorldServer; +import zone.moddev.mc.skysbuildingpieces.catalogue.Shape; +import zone.moddev.mc.skysbuildingpieces.content.PieceBlock; +import zone.moddev.mc.skysbuildingpieces.content.Pieces; + +/** Checks real calculated states, including the native grass hook and render chunk cache. */ +final class SnowChecks { + static void run(WorldServer world) throws ReflectiveOperationException { + BlockPos support = new BlockPos(1500, 220, 1500); + BlockPos position = support.up(); + for (int chunkX = -1; chunkX <= 1; chunkX++) { + for (int chunkZ = -1; chunkZ <= 1; chunkZ++) { + world.getChunk((support.getX() >> 4) + chunkX, (support.getZ() >> 4) + chunkZ); + } + } + world.setBlockState(position.up(3), Blocks.GLASS.getDefaultState(), 2); + world.setBlockState(support, Blocks.GRASS.getDefaultState(), 2); + int checked = 0; + for (PieceBlock piece : Pieces.BLOCKS.values()) { + if (!piece.palette.group.equals("snow") && !piece.palette.group.equals("grass") + && !piece.palette.group.equals("dirt")) { + continue; + } + for (int orientation = 0; orientation < piece.palette.shape.states; orientation++) { + IBlockState state = state(piece, orientation); + world.setBlockState(position, state, 2); + boolean touches = piece.palette.shape != Shape.WALL && piece.palette.shape != Shape.PANE + && (piece.mask(state) & 15) != 0; + boolean physicalSnow = piece.palette.group.equals("snow"); + require(snowy(world, support) == (physicalSnow && touches), + "physical snow support " + piece.palette.shape + "/" + orientation); + if (!physicalSnow) { + world.setBlockState(position.east(), Blocks.SNOW.getDefaultState(), 2); + require(actual(piece, state, world, position).getValue(BlockGrass.SNOWY), + "adjacent physical snow reaches grass/dirt piece"); + require(snowy(world, support) == touches, "calculated cap reaches touching support"); + world.setBlockToAir(position.east()); + require(!actual(piece, state, world, position).getValue(BlockGrass.SNOWY), + "removed snow clears the piece"); + } + require(world.getBlockState(position).equals(state), "snow appearance preserves saved metadata"); + require(!world.getBlockState(support).getValue(BlockGrass.SNOWY), "support cap is not saved"); + world.setBlockToAir(position); + require(!snowy(world, support), "removed cover clears the support"); + checked++; + } + } + IBlockState grass = Pieces.state("minecraft:grass", Shape.HORIZONTAL_STEP, 0); + Block block = grass.getBlock(); + world.setBlockState(position, grass, 2); + for (EnumFacing direction : EnumFacing.HORIZONTALS) { + BlockPos higher = position.offset(direction); + world.setBlockState(higher, Blocks.GRASS.getDefaultState(), 2); + world.setBlockState(higher.up(), Blocks.SNOW_LAYER.getDefaultState(), 2); + require(actual(block, grass, world, position).getValue(BlockGrass.SNOWY), "upper terrace " + direction); + world.setBlockToAir(higher.up()); + world.setBlockToAir(higher); + require(!actual(block, grass, world, position).getValue(BlockGrass.SNOWY), "upper snow removal"); + } + byte[] biomes = world.getChunk(position).getBiomeArray(); + int biomeIndex = (position.getZ() & 15) << 4 | position.getX() & 15; + byte originalBiome = biomes[biomeIndex]; + try { + biomes[biomeIndex] = (byte) net.minecraft.world.biome.Biome.getIdForBiome(Biomes.ICE_PLAINS); + world.setBlockToAir(position.up(3)); + require(actual(block, grass, world, position).getValue(BlockGrass.SNOWY), "exposed cold piece"); + ChunkCache cache = new ChunkCache(world, position.add(-2, -2, -2), position.add(2, 4, 2), 0); + require(block.getActualState(grass, cache, position).getValue(BlockGrass.SNOWY), "render cache uses its world"); + world.setBlockState(position.up(3), Blocks.GLASS.getDefaultState(), 2); + require(!actual(block, grass, world, position).getValue(BlockGrass.SNOWY), "glass roof blocks weather cap"); + } finally { + biomes[biomeIndex] = originalBiome; + world.setBlockToAir(position.up(3)); + world.setBlockToAir(position); + world.setBlockToAir(support); + } + BlockPos edge = new BlockPos(5007, 220, 5007); + world.getChunk(edge); + world.setBlockState(edge, Blocks.GRASS.getDefaultState(), 2); + world.setBlockState(edge.up(), grass, 2); + // Placement may populate adjacent chunks. Unload the eastern one before reading visuals. + net.minecraft.world.chunk.Chunk neighbour = world.getChunkProvider().getLoadedChunk( + (edge.getX() >> 4) + 1, edge.getZ() >> 4); + if (neighbour != null) { + world.getChunkProvider().queueUnload(neighbour); + world.getChunkProvider().tick(); + } + int loaded = world.getChunkProvider().getLoadedChunkCount(); + boolean unavailable = false; + for (EnumFacing direction : EnumFacing.HORIZONTALS) { + unavailable |= !world.isBlockLoaded(edge.offset(direction)); + } + require(unavailable, "the snow border test has an unloaded neighbour"); + snowy(world, edge); + require(world.getChunkProvider().getLoadedChunkCount() == loaded, "snow visuals do not load a neighbouring chunk"); + world.setBlockToAir(edge.up()); + world.setBlockToAir(edge); + System.out.println("BUILDING_PIECES_SNOW_PASS orientations=" + checked + + " metadata=true removal=true cache=true loaded_halo=true"); + } + + private static IBlockState state(Block block, int metadata) { + return block.getStateFromMeta(metadata); + } + + private static IBlockState actual(Block block, IBlockState state, WorldServer world, BlockPos position) { + return block.getActualState(state, world, position); + } + + private static boolean snowy(WorldServer world, BlockPos position) { + return actual(Blocks.GRASS, world.getBlockState(position), world, position).getValue(BlockGrass.SNOWY); + } + + private static void require(boolean condition, String message) { + if (!condition) { + throw new AssertionError(message); + } + } + + private SnowChecks() { + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowHarvestChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowHarvestChecks.java new file mode 100644 index 000000000..5e5aab35b --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowHarvestChecks.java @@ -0,0 +1,102 @@ +package zone.moddev.mc.skysbuildingpieces.probe; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Items; +import net.minecraft.init.Blocks; +import net.minecraft.init.Enchantments; +import net.minecraft.item.ItemStack; +import net.minecraft.network.EnumPacketDirection; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.Packet; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.GameType; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.util.FakePlayerFactory; +import zone.moddev.mc.skysbuildingpieces.catalogue.Shape; +import zone.moddev.mc.skysbuildingpieces.content.Pieces; + +/** Harvest through the survival interaction manager rather than calling getDrops directly. */ +final class SnowHarvestChecks { + static void run(WorldServer world) { + EntityPlayerMP player = FakePlayerFactory.getMinecraft(world); + GameType previousMode = player.interactionManager.getGameType(); + ItemStack previousTool = player.getHeldItemMainhand().copy(); + NetHandlerPlayServer previousConnection = player.connection; + BlockPos position = new BlockPos(1540, 220, 1500); + world.getChunk(position); + AxisAlignedBB area = new AxisAlignedBB(position).grow(2); + int checked = 0; + try { + // Forge sends block-break acknowledgements even for a local fake player. + player.connection = new NetHandlerPlayServer(world.getMinecraftServer(), + new NetworkManager(EnumPacketDirection.SERVERBOUND), player) { + @Override + public void sendPacket(Packet packet) { + // The disposable server has no remote client to acknowledge. + } + }; + player.interactionManager.setGameType(GameType.SURVIVAL); + for (String material : new String[] { "minecraft:snow", "minecraft:packed_ice" }) { + for (Shape shape : new Shape[] { Shape.SLAB, Shape.HORIZONTAL_STEP, Shape.CORNER }) { + IBlockState state = Pieces.state(material, shape, shape == Shape.SLAB ? 1 : 0); + require(state != null, "existing snow/ice piece is registered"); + Block block = state.getBlock(); + ItemStack expected = Pieces.stack(state, 1); + for (int toolCase = 0; toolCase < 3; toolCase++) { + for (EntityItem item : world.getEntitiesWithinAABB(EntityItem.class, area)) { + item.setDead(); + } + ItemStack tool = toolCase != 0 + ? new ItemStack(material.equals("minecraft:snow") ? Items.WOODEN_SHOVEL : Items.WOODEN_PICKAXE) + : ItemStack.EMPTY; + if (toolCase == 2) { + tool.addEnchantment(Enchantments.SILK_TOUCH, 1); + } + player.setHeldItem(EnumHand.MAIN_HAND, tool); + Block full = material.equals("minecraft:snow") ? Blocks.SNOW : Blocks.PACKED_ICE; + world.setBlockState(position, full.getDefaultState(), 2); + boolean nativeHarvestable = full.canHarvestBlock(world, position, player); + world.setBlockState(position, state, 2); + boolean harvestable = block.canHarvestBlock(world, position, player); + require(harvestable == nativeHarvestable, "native snow/ice tool requirement " + material); + require(player.interactionManager.tryHarvestBlock(position), "survival breaking succeeds"); + require(world.isAirBlock(position), "harvest removes the piece"); + int units = 0; + for (EntityItem item : world.getEntitiesWithinAABB(EntityItem.class, area)) { + if (item.isDead) { + continue; + } + require(ItemStack.areItemsEqual(item.getItem(), expected), "correct piece identity drops"); + units += item.getItem().getCount(); + item.setDead(); + } + boolean returnsPiece = material.equals("minecraft:snow") ? toolCase != 0 : toolCase == 2; + require(units == (returnsPiece ? 1 : 0), "survival drop count " + material + "/" + shape); + checked++; + } + } + } + } finally { + player.setHeldItem(EnumHand.MAIN_HAND, previousTool); + player.interactionManager.setGameType(previousMode); + player.connection = previousConnection; + world.setBlockToAir(position); + } + System.out.println("BUILDING_PIECES_SURVIVAL_SNOW_ICE_PASS checks=" + checked); + } + + private static void require(boolean condition, String message) { + if (!condition) { + throw new AssertionError(message); + } + } + + private SnowHarvestChecks() { + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowSettlementChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowSettlementChecks.java new file mode 100644 index 000000000..4361463e5 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowSettlementChecks.java @@ -0,0 +1,91 @@ +package zone.moddev.mc.skysbuildingpieces.probe; + +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.block.BlockSnow; +import net.minecraft.block.state.BlockFaceShape; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.WorldServer; +import zone.moddev.mc.skysbuildingpieces.catalogue.Geometry; +import zone.moddev.mc.skysbuildingpieces.catalogue.Shape; +import zone.moddev.mc.skysbuildingpieces.content.PieceBlock; +import zone.moddev.mc.skysbuildingpieces.content.Pieces; + +/** Uses vanilla's snow-placement rule rather than checking our own support flag alone. */ +final class SnowSettlementChecks { + static void run(WorldServer world) { + BlockPos position = new BlockPos(1480, 220, 1480); + for (int chunkX = -1; chunkX <= 1; chunkX++) { + for (int chunkZ = -1; chunkZ <= 1; chunkZ++) { + world.getChunk((position.getX() >> 4) + chunkX, (position.getZ() >> 4) + chunkZ); + } + } + world.setBlockState(position.down(), Blocks.STONE.getDefaultState(), 2); + world.setBlockToAir(position.up()); + world.setBlockState(position, Pieces.state("minecraft:grass", Shape.STEP, 4), 2); + require(!Blocks.SNOW_LAYER.canPlaceBlockAt(world, position.up()), + "snow must not hover over a bottom grass step"); + int cases = 0; + for (PieceBlock block : Pieces.BLOCKS.values()) { + Block nativeMethods = block; + for (int orientation = 0; orientation < block.palette.shape.states; orientation++) { + IBlockState state = nativeMethods.getStateFromMeta(orientation); + world.setBlockState(position, state, 2); + boolean completeTop = block.palette.shape != Shape.WALL && block.palette.shape != Shape.PANE + && !block.palette.group.equals("path") && Geometry.completeTop(block.mask(state)); + require(Blocks.SNOW_LAYER.canPlaceBlockAt(world, position.up()) == completeTop, + "snow needs a full-height supporting top: " + state); + for (EnumFacing face : EnumFacing.values()) { + BlockFaceShape expected = block.palette.shape == Shape.WALL + ? (face.getAxis() == EnumFacing.Axis.Y ? BlockFaceShape.CENTER_BIG + : BlockFaceShape.MIDDLE_POLE_THICK) + : block.palette.shape == Shape.PANE + ? (face.getAxis() == EnumFacing.Axis.Y ? BlockFaceShape.CENTER_SMALL + : BlockFaceShape.MIDDLE_POLE_THIN) + : nativeMethods.isSideSolid(state, world, position, face) ? BlockFaceShape.SOLID + : BlockFaceShape.UNDEFINED; + require(state.getBlockFaceShape(world, position, face) == expected, + "face follows the occupied geometry: " + state + "/" + face); + } + if (block.palette.shape == Shape.WALL) { + require(Blocks.TORCH.canPlaceBlockAt(world, position.up()), "wall torch support"); + } + for (int layers : new int[] { 1, 8 }) { + IBlockState snow = Blocks.SNOW_LAYER.getDefaultState().withProperty(BlockSnow.LAYERS, layers); + world.setBlockState(position.up(), snow, 2); + nativeMethods.neighborChanged(state, world, position, Blocks.SNOW_LAYER, position.up()); + require((world.getBlockState(position.up()).getBlock() == Blocks.SNOW_LAYER) == completeTop, + "a neighbour update removes only unsupported saved snow: " + state); + require(world.getBlockState(position).equals(state), "snow repair keeps the piece metadata"); + world.setBlockToAir(position.up()); + } + if (nativeMethods.getTickRandomly()) { + world.setBlockState(position.up(), Blocks.SNOW_LAYER.getDefaultState(), 2); + nativeMethods.updateTick(world, position, state, new Random(4815162342L)); + require((world.getBlockState(position.up()).getBlock() == Blocks.SNOW_LAYER) == completeTop, + "ordinary soil ticks remove old floating snow: " + state); + world.setBlockToAir(position.up()); + } + cases++; + } + } + world.setBlockState(position, Blocks.STONE.getDefaultState(), 2); + require(Blocks.SNOW_LAYER.canPlaceBlockAt(world, position.up()), "vanilla full-block control"); + world.setBlockToAir(position); + world.setBlockToAir(position.down()); + System.out.println("BUILDING_PIECES_SNOW_SETTLEMENT_PASS states=" + cases + + " native_rule=true full_tops=true saved_snow=true walls=true"); + } + + private static void require(boolean condition, String message) { + if (!condition) { + throw new AssertionError(message); + } + } + + private SnowSettlementChecks() { + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowVisualChecks.java b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowVisualChecks.java new file mode 100644 index 000000000..40b651a62 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysbuildingpieces/probe/SnowVisualChecks.java @@ -0,0 +1,54 @@ +package zone.moddev.mc.skysbuildingpieces.probe; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockGrass; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.fml.common.registry.ForgeRegistries; +import zone.moddev.mc.skysbuildingpieces.client.SnowCoveredGrassModel; + +/** Read actual baked vanilla/BOP models, including uncullable top quads. */ +final class SnowVisualChecks { + static void run(Minecraft minecraft) { + int states = 0; + int tops = 0; + for (Block block : ForgeRegistries.BLOCKS) { + if (!(block instanceof BlockGrass)) { + continue; + } + for (IBlockState state : block.getBlockState().getValidStates()) { + IBakedModel model = minecraft.getBlockRendererDispatcher().getModelForState(state); + if (!state.getValue(BlockGrass.SNOWY)) { + require(!(model instanceof SnowCoveredGrassModel), "ordinary grass stays unchanged"); + continue; + } + require(model instanceof SnowCoveredGrassModel, "snowy grass support model: " + state); + for (EnumFacing side : new EnumFacing[] { null, EnumFacing.UP }) { + for (BakedQuad quad : model.getQuads(state, side, 0)) { + if (quad.getFace() == EnumFacing.UP) { + require(quad.getSprite().getIconName().equals("minecraft:blocks/snow"), "snow top texture"); + require(!quad.hasTintIndex(), "snow top is not biome tinted"); + tops++; + } + } + } + require(model.getParticleTexture() != null, "support particle texture"); + states++; + } + } + require(states > 0 && tops >= states, "snow support models were exercised"); + System.out.println("BUILDING_PIECES_SNOW_MODELS_PASS states=" + states + " tops=" + tops); + } + + private static void require(boolean condition, String message) { + if (!condition) { + throw new AssertionError(message); + } + } + + private SnowVisualChecks() { + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/SkysBuildingPieces.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/SkysBuildingPieces.java index 0ecf2c813..131f76a8f 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/SkysBuildingPieces.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/SkysBuildingPieces.java @@ -1,7 +1,7 @@ package zone.moddev.mc.skysbuildingpieces; import net.minecraftforge.common.*; -import net.minecraftforge.common.config.Configuration; +import zone.moddev.mc.skysbuildingpieces.config.BuildingPiecesConfig; import net.minecraftforge.fml.common.*; import net.minecraftforge.fml.common.event.*; import net.minecraft.block.Block; @@ -14,10 +14,11 @@ modid = SkysBuildingPieces.ID, name = "Sky's Building Pieces", version = SkysBuildingPieces.VERSION, + guiFactory = "zone.moddev.mc.skysbuildingpieces.client.BuildingPiecesGuiFactory", acceptedMinecraftVersions = "[1.12.2]", dependencies = "after:skysgrassslabs@[1.1.1.112021,);after:basemetals;after:mineralogy;before:buildingbricks") public final class SkysBuildingPieces { - public static final String ID = "skysbuildingpieces", VERSION = "0.3.8.112021"; + public static final String ID = "skysbuildingpieces", VERSION = "0.3.10.112021"; public static boolean forceReplace; public static Block HOLDER; @SidedProxy( @@ -27,15 +28,7 @@ public final class SkysBuildingPieces { @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { - Configuration configuration = new Configuration(event.getSuggestedConfigurationFile()); - - configuration.load(); - forceReplace = configuration.getBoolean("forceReplaceBuildingBricksPieces", "compat", false, - "Replace supported BuildingBricks pieces as they load. Back up the world first. Requires restart."); - - if (configuration.hasChanged()) { - configuration.save(); - } + forceReplace = BuildingPiecesConfig.load(event.getSuggestedConfigurationFile()); Pieces.register(); zone.moddev.mc.skysbuildingpieces.compat.MineralogyCompat.register(); @@ -61,6 +54,11 @@ public void beforeServer(FMLServerAboutToStartEvent event) { LegacyBridge.start(event.getServer()); } + @Mod.EventHandler + public void registryMappingsChanged(FMLModIdMappingEvent event) { + zone.moddev.mc.skysbuildingpieces.content.RecipeAliases.restore(); + } + @Mod.EventHandler public void afterServer(FMLServerStoppedEvent event) { LegacyBridge.stop(); diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/client/BuildingPiecesConfigScreen.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/BuildingPiecesConfigScreen.java new file mode 100644 index 000000000..fbe4dffc8 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/BuildingPiecesConfigScreen.java @@ -0,0 +1,23 @@ +package zone.moddev.mc.skysbuildingpieces.client; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.client.config.IConfigElement; +import zone.moddev.mc.skysbuildingpieces.config.BuildingPiecesConfig; + +/** Changes on this screen take effect after restarting Minecraft. */ +public final class BuildingPiecesConfigScreen extends GuiConfig { + public BuildingPiecesConfigScreen(GuiScreen parent) { + super(parent, elements(), "skysbuildingpieces", false, true, "Sky's Building Pieces"); + } + + private static List elements() { + List elements = new ArrayList<>(); + elements.addAll(new ConfigElement(BuildingPiecesConfig.configuration().getCategory("gameplay")).getChildElements()); + elements.addAll(new ConfigElement(BuildingPiecesConfig.configuration().getCategory("compat")).getChildElements()); + return elements; + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/client/BuildingPiecesGuiFactory.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/BuildingPiecesGuiFactory.java new file mode 100644 index 000000000..ca074a1d7 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/BuildingPiecesGuiFactory.java @@ -0,0 +1,42 @@ +package zone.moddev.mc.skysbuildingpieces.client; + +import java.util.Collections; +import java.util.Set; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.client.IModGuiFactory; +import net.minecraftforge.fml.client.event.ConfigChangedEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import zone.moddev.mc.skysbuildingpieces.config.BuildingPiecesConfig; + +/** Connects the Mods list's Config button to Forge's standard settings screen. */ +public final class BuildingPiecesGuiFactory implements IModGuiFactory { + @Override + public void initialize(Minecraft minecraftInstance) { + MinecraftForge.EVENT_BUS.register(this); + } + + @Override + public boolean hasConfigGui() { + return true; + } + + @Override + public GuiScreen createConfigGui(GuiScreen parentScreen) { + return new BuildingPiecesConfigScreen(parentScreen); + } + + @Override + public Set runtimeGuiCategories() { + return Collections.emptySet(); + } + + @SubscribeEvent + public void configChanged(ConfigChangedEvent.OnConfigChangedEvent event) { + if ("skysbuildingpieces".equals(event.getModID())) { + // Keep the active settings until Minecraft restarts. + BuildingPiecesConfig.saveChanges(); + } + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/client/ClientProxy.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/ClientProxy.java index 341a285cf..68eb6b0e7 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/client/ClientProxy.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/ClientProxy.java @@ -16,6 +16,7 @@ public final class ClientProxy extends CommonProxy { public void preInit() { net.minecraftforge.common.MinecraftForge.EVENT_BUS.register(new WallHighlight()); net.minecraftforge.common.MinecraftForge.EVENT_BUS.register(new ContinuousGlassModel.BakeHandler()); + net.minecraftforge.common.MinecraftForge.EVENT_BUS.register(new SnowCoveredGrassModel.BakeHandler()); } @net.minecraftforge.fml.common.eventhandler.SubscribeEvent diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/client/SnowCoveredGrassModel.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/SnowCoveredGrassModel.java new file mode 100644 index 000000000..c93a478db --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/client/SnowCoveredGrassModel.java @@ -0,0 +1,131 @@ +package zone.moddev.mc.skysbuildingpieces.client; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.minecraft.block.Block; +import net.minecraft.block.BlockGrass; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.BakedQuadRetextured; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.client.renderer.block.model.ItemOverrideList; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.registry.IRegistry; +import net.minecraftforge.client.event.ModelBakeEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.registry.ForgeRegistries; + +/** A snow cap on exposed grass between partial pieces, including native BOP grass. */ +public final class SnowCoveredGrassModel implements IBakedModel { + private final IBakedModel original; + private final TextureAtlasSprite snow; + private final Map, List> tops = + Collections.synchronizedMap(new IdentityHashMap, List>()); + + SnowCoveredGrassModel(IBakedModel original, TextureAtlasSprite snow) { + this.original = original; + this.snow = snow; + } + + @Override + public List getQuads(IBlockState state, EnumFacing side, long random) { + List quads = original.getQuads(state, side, random); + if (side != null && side != EnumFacing.UP || quads.isEmpty()) { + return quads; + } + List cached = tops.get(quads); + if (cached != null) { + return cached; + } + List covered = new ArrayList(quads.size()); + for (BakedQuad quad : quads) { + if (quad.getFace() == EnumFacing.UP) { + BakedQuad remapped = new BakedQuadRetextured(quad, snow); + covered.add(new BakedQuad(remapped.getVertexData(), -1, EnumFacing.UP, snow, + quad.shouldApplyDiffuseLighting(), remapped.getFormat())); + } else { + covered.add(quad); + } + } + List result = Collections.unmodifiableList(covered); + if (tops.size() < 128) { + tops.put(quads, result); + } + return result; + } + + @Override + public boolean isAmbientOcclusion() { + return original.isAmbientOcclusion(); + } + + @Override + public boolean isGui3d() { + return original.isGui3d(); + } + + @Override + public boolean isBuiltInRenderer() { + return original.isBuiltInRenderer(); + } + + @Override + public TextureAtlasSprite getParticleTexture() { + return original.getParticleTexture(); + } + + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return original.getItemCameraTransforms(); + } + + @Override + public ItemOverrideList getOverrides() { + return original.getOverrides(); + } + + static void install(IRegistry registry, IBakedModel missing, + Set grassBlocks, TextureAtlasSprite snow) { + Map shared = new IdentityHashMap(); + for (ModelResourceLocation key : new ArrayList(registry.getKeys())) { + if (!grassBlocks.contains(key.getNamespace() + ":" + key.getPath()) + || !Arrays.asList(key.getVariant().split(",")).contains("snowy=true")) { + continue; + } + IBakedModel model = registry.getObject(key); + if (model == null || model == missing || model instanceof SnowCoveredGrassModel) { + continue; + } + SnowCoveredGrassModel replacement = shared.get(model); + if (replacement == null) { + replacement = new SnowCoveredGrassModel(model, snow); + shared.put(model, replacement); + } + registry.putObject(key, replacement); + } + } + + public static final class BakeHandler { + @SubscribeEvent + public void bake(ModelBakeEvent event) { + Set grassBlocks = new HashSet(); + for (Block block : ForgeRegistries.BLOCKS) { + if (block instanceof BlockGrass) { + grassBlocks.add(block.getRegistryName().toString()); + } + } + install(event.getModelRegistry(), event.getModelManager().getMissingModel(), grassBlocks, + Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/snow")); + } + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/config/BuildingPiecesConfig.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/config/BuildingPiecesConfig.java new file mode 100644 index 000000000..5147ac792 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/config/BuildingPiecesConfig.java @@ -0,0 +1,49 @@ +package zone.moddev.mc.skysbuildingpieces.config; + +import java.io.File; +import net.minecraftforge.common.config.Configuration; + +public final class BuildingPiecesConfig { + private static final String GAMEPLAY = "gameplay"; + private static final String COMPAT = "compat"; + private static final String DIRECTIONAL_SLABS = "directionalSlabPlacement"; + private static final String REPLACE_PIECES = "forceReplaceBuildingBricksPieces"; + + private static Configuration configuration; + private static boolean directionalSlabs = true; + + private BuildingPiecesConfig() { + } + + public static boolean load(File file) { + configuration = new Configuration(file); + configuration.load(); + directionalSlabs = configuration.getBoolean(DIRECTIONAL_SLABS, GAMEPLAY, true, + "Use click position to place regular slabs horizontally or vertically. Requires a restart."); + boolean replacePieces = configuration.getBoolean(REPLACE_PIECES, COMPAT, false, + "Replace supported BuildingBricks pieces as they load. Back up the world first. Requires restart."); + + configuration.setCategoryRequiresMcRestart(GAMEPLAY, true); + configuration.setCategoryRequiresMcRestart(COMPAT, true); + configuration.getCategory(GAMEPLAY).get(DIRECTIONAL_SLABS) + .setLanguageKey("config.skysbuildingpieces.directionalSlabPlacement"); + configuration.getCategory(COMPAT).get(REPLACE_PIECES) + .setLanguageKey("config.skysbuildingpieces.forceReplaceBuildingBricksPieces"); + saveChanges(); + return replacePieces; + } + + public static boolean directionalSlabPlacement() { + return directionalSlabs; + } + + public static Configuration configuration() { + return configuration; + } + + public static void saveChanges() { + if (configuration.hasChanged()) { + configuration.save(); + } + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/CuttingRecipe.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/CuttingRecipe.java index 31a34510e..800fe1a88 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/CuttingRecipe.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/CuttingRecipe.java @@ -23,7 +23,7 @@ public final class CuttingRecipe extends ShapedRecipes { private CuttingRecipe(String material, Shape shape, CraftingPattern pattern, ItemStack ingredient, ItemStack output) { - super("skysbuildingpieces/" + shape.name() + "/" + pattern.name(), pattern.width(), pattern.height(), inputs(pattern, ingredient), output); + super(RecipeGroups.result(output), pattern.width(), pattern.height(), inputs(pattern, ingredient), output); this.material = material; this.shape = shape; this.pattern = pattern; diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/GrassLifecycle.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/GrassLifecycle.java index 9b855f561..f8c1300f4 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/GrassLifecycle.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/GrassLifecycle.java @@ -7,11 +7,13 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.common.Loader; /** Standalone grass rules, with a lazily linked optional Grass Slabs API bridge. */ public final class GrassLifecycle { private static Method sharedGrass, sharedDirt; + private static Method sharedSnowAppearance; private GrassLifecycle() { } @@ -42,12 +44,37 @@ public static void initialize() { Random.class); sharedDirt = grassApiClass.getMethod("tickDirt", World.class, BlockPos.class, IBlockState.class, Random.class); + try { + Method registerSnow = grassApiClass.getMethod("registerSnowForm", IBlockState.class); + sharedSnowAppearance = grassApiClass.getMethod("hasSnowAppearance", IBlockAccess.class, BlockPos.class); + for (PieceBlock block : Pieces.BLOCKS.values()) { + if (block.palette.group.equals("snow")) { + for (int orientation = 0; orientation < block.palette.shape.states; orientation++) { + registerSnow.invoke(null, block.getStateFromMeta(orientation)); + } + } + } + } catch (NoSuchMethodException olderGrassSlabs) { + // Older Grass Slabs versions still share the existing lifecycle rules. + sharedSnowAppearance = null; + } } catch (ReflectiveOperationException failure) { throw new IllegalStateException("Install Sky's Grass Slabs 1.1.1.112021 or later for grass-piece integration", failure); } } + static boolean hasSnowAppearance(IBlockAccess world, BlockPos pos) { + if (sharedSnowAppearance != null) { + try { + return (Boolean) sharedSnowAppearance.invoke(null, world, pos); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Cannot read the shared grass snow appearance", failure); + } + } + return SnowAppearance.hasNearbySnow(world, pos); + } + public static boolean grass(IBlockState state) { return state.getBlock() instanceof PieceBlock && ((PieceBlock) state.getBlock()).definition(state).type.equals("grass"); diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/NativeSlabPlacement.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/NativeSlabPlacement.java index cc64575a5..3f43bfb6a 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/NativeSlabPlacement.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/NativeSlabPlacement.java @@ -70,7 +70,8 @@ public static EnumActionResult place(EntityPlayer player, World world, BlockPos public static EnumActionResult place(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing face, float hitX, float hitY, float hitZ) { - if (instance == null || Loader.isModLoaded("buildingbricks")) { + if (instance == null || !zone.moddev.mc.skysbuildingpieces.config.BuildingPiecesConfig.directionalSlabPlacement() + || Loader.isModLoaded("buildingbricks")) { return null; } diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceBlock.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceBlock.java index 12ee2a51a..c6f75ef3d 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceBlock.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceBlock.java @@ -183,6 +183,19 @@ public boolean isSideSolid(IBlockState blockState, IBlockAccess blockAccess, Blo && Geometry.completeFace(mask(blockState), side.getIndex()); } + @Override + public BlockFaceShape getBlockFaceShape(IBlockAccess world, IBlockState state, BlockPos position, EnumFacing face) { + if (palette.shape == Shape.WALL) { + return face.getAxis() == EnumFacing.Axis.Y ? BlockFaceShape.CENTER_BIG : BlockFaceShape.MIDDLE_POLE_THICK; + } + if (palette.shape == Shape.PANE) { + return face.getAxis() == EnumFacing.Axis.Y ? BlockFaceShape.CENTER_SMALL : BlockFaceShape.MIDDLE_POLE_THIN; + } + // Snow uses this separate vanilla check, so a recessed top must not claim full-height support. + IBlockState actual = palette.shape == Shape.STAIRS ? getActualState(state, world, position) : state; + return isSideSolid(actual, world, position, face) ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED; + } + @Override public boolean canPlaceTorchOnTop(IBlockState blockState, IBlockAccess blockAccess, BlockPos position) { return palette.shape == Shape.WALL || super.canPlaceTorchOnTop(blockState, blockAccess, position); @@ -402,15 +415,6 @@ public RayTraceResult collisionRayTrace(IBlockState blockState, World world, Blo } public IBlockState getActualState(IBlockState blockState, IBlockAccess blockAccess, BlockPos position) { - boolean snow = false; - - for (EnumFacing face : new EnumFacing[] { EnumFacing.UP, EnumFacing.NORTH, EnumFacing.EAST, EnumFacing.SOUTH, - EnumFacing.WEST }) { - Block block = blockAccess.getBlockState(position.offset(face)).getBlock(); - - snow |= block == Blocks.SNOW || block == Blocks.SNOW_LAYER; - } - int connections = 0; int connectionBit = 1; @@ -433,7 +437,8 @@ public IBlockState getActualState(IBlockState blockState, IBlockAccess blockAcce blockState = blockState.withProperty(STAIR_SHAPE, stairsShape(blockState, blockAccess, position)); } if (blockState.getPropertyKeys().contains(BlockGrass.SNOWY)) { - blockState = blockState.withProperty(BlockGrass.SNOWY, snow); + blockState = blockState.withProperty(BlockGrass.SNOWY, + GrassLifecycle.hasSnowAppearance(blockAccess, position)); } if (blockState.getPropertyKeys().contains(CONNECTIONS)) { blockState = blockState.withProperty(CONNECTIONS, connections); @@ -589,10 +594,12 @@ public void getSubBlocks(net.minecraft.creativetab.CreativeTabs tab, NonNullList } public void updateTick(World world, BlockPos position, IBlockState blockState, Random rand) { + SnowCover.removeUnsupportedLayer(world, position); GrassLifecycle.tick(world, position, blockState, rand); } public void onBlockAdded(World world, BlockPos position, IBlockState blockState) { + SnowCover.removeUnsupportedLayer(world, position); PathPieces.checkCover(world, position, blockState); GrassLifecycle.repairSupport(world, position, blockState); } @@ -606,6 +613,7 @@ public boolean onBlockActivated(World world, BlockPos position, IBlockState stat @Override public void neighborChanged(IBlockState blockState, World world, BlockPos position, Block changed, BlockPos changedPos) { + SnowCover.removeUnsupportedLayer(world, position); PathPieces.checkCover(world, position, blockState); GrassLifecycle.repairSupport(world, position, blockState); } diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceRecombinationRecipe.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceRecombinationRecipe.java index 5b6c66d47..599183533 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceRecombinationRecipe.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PieceRecombinationRecipe.java @@ -20,7 +20,7 @@ public final class PieceRecombinationRecipe extends ShapedRecipes { private final ItemStack ingredient; private PieceRecombinationRecipe(IBlockState input, ItemStack output) { - super("skysbuildingpieces/recombine/" + ((PieceBlock) input.getBlock()).palette.shape.name(), 1, 2, NonNullList.from(Ingredient.EMPTY, + super(RecipeGroups.result(output), 1, 2, NonNullList.from(Ingredient.EMPTY, PieceIngredients.fromState(input), PieceIngredients.fromState(input)), output.copy()); inputBlock = (PieceBlock) input.getBlock(); diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PiecesTab.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PiecesTab.java index 5a7b51e5f..f638644cc 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PiecesTab.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/PiecesTab.java @@ -1,15 +1,12 @@ package zone.moddev.mc.skysbuildingpieces.content; -import java.util.*; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; -import net.minecraft.item.*; +import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import zone.moddev.mc.skysbuildingpieces.catalogue.Catalogue; -import zone.moddev.mc.skysbuildingpieces.catalogue.Shape; -/** Keeps the pieces together, including the vanilla items reused by the catalogue. */ +/** Shows the pieces registered by the mod and its add-ons. */ public final class PiecesTab extends CreativeTabs { public static final PiecesTab INSTANCE = new PiecesTab(); @@ -23,34 +20,4 @@ public ItemStack createIcon() { return new ItemStack(Blocks.BRICK_STAIRS); } - @SideOnly(Side.CLIENT) - @Override - public void displayAllRelevantItems(net.minecraft.util.NonNullList items) { - super.displayAllRelevantItems(items); - - Set present = new HashSet(); - - for (ItemStack stack : items) { - present.add(key(stack)); - } - for (Catalogue.MaterialDef material : Catalogue.INSTANCE.materials.values()) { - for (Shape shape : new Shape[] { Shape.SLAB, Shape.STAIRS, Shape.WALL, Shape.PANE }) { - String nativeShape = shape.name().toLowerCase(Locale.ROOT); - - if (!Catalogue.supportsShape(material, shape) || material.block(nativeShape) == null) { - continue; - } - - ItemStack stack = Pieces.stack(Pieces.nativeState(material, nativeShape), 1); - - if (stack != null && !stack.isEmpty() && present.add(key(stack))) { - items.add(stack); - } - } - } - } - - private static String key(ItemStack stack) { - return stack.getItem().getRegistryName() + ":" + stack.getMetadata(); - } } diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/RecipeAliases.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/RecipeAliases.java new file mode 100644 index 000000000..220b2aa94 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/RecipeAliases.java @@ -0,0 +1,92 @@ +package zone.moddev.mc.skysbuildingpieces.content; + +import java.lang.reflect.Method; +import java.util.LinkedHashMap; +import java.util.Map; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.registries.ForgeRegistry; +import net.minecraftforge.registries.IForgeRegistry; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.registry.GameRegistry; +import net.minecraftforge.event.world.WorldEvent; + +/** Old recipe books resolve to the native recipe without registering a second craft. */ +@Mod.EventBusSubscriber(modid = "skysbuildingpieces") +public final class RecipeAliases { + private static final Map REDIRECTS = new LinkedHashMap<>(); + private RecipeAliases() { + } + + static void redirect(IForgeRegistry registry, ResourceLocation previous, ResourceLocation current) { + ResourceLocation existing = REDIRECTS.putIfAbsent(previous, current); + if (existing != null && !existing.equals(current)) { + throw new IllegalStateException("Conflicting slab recipe alias " + previous); + } + apply(registry, previous, current); + } + + /** Registry snapshots replace the alias table when a saved world is opened. */ + public static void restore() { + if (REDIRECTS.isEmpty()) { + return; + } + IForgeRegistry registry = GameRegistry.findRegistry(IRecipe.class); + for (Map.Entry entry : REDIRECTS.entrySet()) { + apply(registry, entry.getKey(), entry.getValue()); + } + } + + @SubscribeEvent + public static void worldLoaded(WorldEvent.Load event) { + restore(); + } + + private static void apply(IForgeRegistry registry, ResourceLocation previous, ResourceLocation current) { + if (registry.getValue(previous) == registry.getValue(current) && registry.getValue(current) != null) { + return; + } + if (!(registry instanceof ForgeRegistry) || registry.containsKey(previous) + || registry.getValue(current) == null || previous.equals(current)) { + throw new IllegalStateException("Cannot redirect the old slab recipe " + previous + " to " + current); + } + ForgeRegistry forge = (ForgeRegistry) registry; + boolean locked = forge.isLocked(); + try { + // Forge locks this table before its remap event. Restore our names, then restore the lock. + if (locked) { + forge.unfreeze(); + } + AliasMethod.ADD.invoke(registry, previous, current); + if (registry.getValue(previous) != registry.getValue(current)) { + throw new IllegalStateException("Forge did not retain the slab recipe alias " + previous); + } + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Cannot preserve the old slab recipe " + previous, failure); + } finally { + if (locked) { + forge.freeze(); + } + } + } + + private static final class AliasMethod { + static final Method ADD = find(); + + private static Method find() { + try { + // Forge 1.12 keeps this method package-private; no registry fields are changed directly. + Method method = ForgeRegistry.class.getDeclaredMethod("addAlias", ResourceLocation.class, + ResourceLocation.class); + if (method.getReturnType() != void.class) { + throw new IllegalStateException("Unexpected Forge recipe alias signature"); + } + method.setAccessible(true); + return method; + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Forge's recipe alias method is unavailable", failure); + } + } + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/RecipeGroups.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/RecipeGroups.java new file mode 100644 index 000000000..93a931ce8 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/RecipeGroups.java @@ -0,0 +1,14 @@ +package zone.moddev.mc.skysbuildingpieces.content; + +import net.minecraft.item.ItemStack; + +/** Keep different materials, shapes and yields in separate recipe-book buttons. */ +final class RecipeGroups { + private RecipeGroups() { + } + + static String result(ItemStack output) { + return "skysbuildingpieces/result/" + output.getItem().getRegistryName() + + "/" + output.getMetadata() + "/" + output.getCount(); + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabPlacement.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabPlacement.java index 5bca77069..f9094c24a 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabPlacement.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabPlacement.java @@ -1,6 +1,7 @@ package zone.moddev.mc.skysbuildingpieces.content; import net.minecraft.util.EnumFacing; +import zone.moddev.mc.skysbuildingpieces.config.BuildingPiecesConfig; import zone.moddev.mc.skysbuildingpieces.catalogue.Shape; /** Face-local centre/edge selection, independent of any other mod's placement handlers. */ @@ -9,6 +10,12 @@ public final class SlabPlacement { /** The half of the destination block occupied by a slab. */ public static EnumFacing side(EnumFacing face, float hitX, float hitY, float hitZ) { + if (!BuildingPiecesConfig.directionalSlabPlacement()) { + if (face == EnumFacing.DOWN || face.getAxis().isHorizontal() && hitY > 0.5f) { + return EnumFacing.UP; + } + return EnumFacing.DOWN; + } if (centre(face, hitX, hitY, hitZ)) { return face.getOpposite(); } diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabRecombinationRecipe.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabRecombinationRecipe.java index 99b4daafb..86f16c757 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabRecombinationRecipe.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SlabRecombinationRecipe.java @@ -48,14 +48,42 @@ public static void register(IForgeRegistry registry) { continue; } + net.minecraft.util.ResourceLocation id = new net.minecraft.util.ResourceLocation("skysbuildingpieces", + material.id.replace(':', '/') + "/slab_recombination"); + IRecipe nativeRecipe = findNativeRecipe(registry, Pieces.stack(state, 1), full); + if (nativeRecipe != null) { + RecipeAliases.redirect(registry, id, nativeRecipe.getRegistryName()); + continue; + } SlabRecombinationRecipe recipe = new SlabRecombinationRecipe(state, full); - recipe.setRegistryName("skysbuildingpieces", material.id.replace(':', '/') + "/slab_recombination"); + recipe.setRegistryName(id); RECIPES.add(recipe); registry.register(recipe); } } + private static IRecipe findNativeRecipe(IForgeRegistry registry, ItemStack slab, ItemStack full) { + String owner = slab.getItem().getRegistryName().getNamespace(); + for (IRecipe recipe : registry.getValuesCollection()) { + if (recipe.getRegistryName() == null || !recipe.getRegistryName().getNamespace().equals(owner) + || !ItemStack.areItemStacksEqual(full, recipe.getRecipeOutput()) + || recipe.getIngredients().size() != 2) { + continue; + } + boolean shapeless = recipe instanceof net.minecraft.item.crafting.ShapelessRecipes + || recipe instanceof net.minecraftforge.oredict.ShapelessOreRecipe; + boolean horizontal = recipe instanceof net.minecraftforge.common.crafting.IShapedRecipe + && ((net.minecraftforge.common.crafting.IShapedRecipe) recipe).getRecipeWidth() == 2 + && ((net.minecraftforge.common.crafting.IShapedRecipe) recipe).getRecipeHeight() == 1; + if ((shapeless || horizontal) && recipe.getIngredients().get(0).apply(slab) + && recipe.getIngredients().get(1).apply(slab)) { + return recipe; + } + } + return null; + } + private boolean same(ItemStack input) { if (input == null || input.isEmpty() || input.getItem() != slab.getItem()) { return false; @@ -117,7 +145,7 @@ public boolean canFit(int width, int height) { @Override public String getGroup() { - return "skysbuildingpieces/slab_recombination"; + return RecipeGroups.result(full); } @Override diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SnowAppearance.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SnowAppearance.java new file mode 100644 index 000000000..26f70cb35 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SnowAppearance.java @@ -0,0 +1,63 @@ +package zone.moddev.mc.skysbuildingpieces.content; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.ChunkCache; +import net.minecraft.world.EnumSkyBlock; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.ReflectionHelper; + +/** Standalone equivalent of Grass Slabs' calculated snow cap. */ +final class SnowAppearance { + private SnowAppearance() { + } + + static boolean hasNearbySnow(IBlockAccess access, BlockPos pos) { + if (SnowCover.isSnowPiece(readState(access, pos.up()))) { + return true; + } + for (EnumFacing facing : EnumFacing.HORIZONTALS) { + BlockPos neighbourPos = pos.offset(facing); + IBlockState neighbour = readState(access, neighbourPos); + if (SnowCover.isSnowPiece(neighbour) || neighbour.isFullCube() + && SnowCover.isSnowPiece(readState(access, neighbourPos.up()))) { + return true; + } + } + World world = weatherWorld(access); + return world != null && pos.getY() >= 0 && pos.getY() < 256 && world.isBlockLoaded(pos) + && world.provider.hasSkyLight() && world.getBiome(pos).getTemperature(pos) < 0.15F + && world.getPrecipitationHeight(pos).getY() <= pos.getY() + 1 + && world.getLightFor(EnumSkyBlock.BLOCK, pos.up()) < 10; + } + + private static World weatherWorld(IBlockAccess access) { + if (access instanceof World) { + return (World) access; + } + if (access instanceof ChunkCache) { + try { + return (World) CacheWorld.WORLD.get(access); + } catch (IllegalAccessException failure) { + throw new IllegalStateException("Cannot read weather from Minecraft's chunk cache", failure); + } + } + return null; + } + + private static final class CacheWorld { + static final java.lang.reflect.Field WORLD = ReflectionHelper.findField( + ChunkCache.class, "world", "field_72815_e"); + } + + private static IBlockState readState(IBlockAccess world, BlockPos pos) { + if (pos.getY() < 0 || pos.getY() >= 256 + || world instanceof World && !((World) world).isBlockLoaded(pos)) { + return Blocks.AIR.getDefaultState(); + } + return world.getBlockState(pos); + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SnowCover.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SnowCover.java new file mode 100644 index 000000000..fb5945f12 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/content/SnowCover.java @@ -0,0 +1,67 @@ +package zone.moddev.mc.skysbuildingpieces.content; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockGrass; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import zone.moddev.mc.skysbuildingpieces.catalogue.Shape; + +/** Calculated support visuals; no saved grass state or migration data changes. */ +public final class SnowCover { + private SnowCover() { + } + + static void removeUnsupportedLayer(World world, BlockPos position) { + BlockPos above = position.up(); + if (world.isRemote || above.getY() > 255 || !world.isBlockLoaded(above)) { + return; + } + // Clear old floating layers through ordinary block updates, without a chunk scan or terrain retrogen. + if (world.getBlockState(above).getBlock() == Blocks.SNOW_LAYER + && !Blocks.SNOW_LAYER.canPlaceBlockAt(world, above)) { + world.setBlockToAir(above); + } + } + + public static IBlockState actualState(IBlockState vanilla, IBlockAccess world, BlockPos pos) { + if (vanilla.getValue(BlockGrass.SNOWY) || pos.getY() >= 255) { + return vanilla; + } + BlockPos abovePos = pos.up(); + if (world instanceof World && !((World) world).isBlockLoaded(abovePos)) { + return vanilla; + } + IBlockState above = world.getBlockState(abovePos); + Block block = above.getBlock(); + // Full blocks do not expose their support. This also avoids following another grass flag. + if (above.isFullCube() || above.getMaterial().isLiquid() || block.hasTileEntity(above)) { + return vanilla; + } + boolean physicalSnow = isSnowPiece(above); + if (block instanceof PieceBlock) { + PieceBlock piece = (PieceBlock) block; + if (piece.palette.shape == Shape.WALL || piece.palette.shape == Shape.PANE + || (piece.mask(above) & 15) == 0) { + return vanilla; + } + } else { + AxisAlignedBB bounds = block.getBoundingBox(above, world, abovePos); + if (bounds == null || bounds.minY != 0 || bounds.maxY <= 0 || bounds.maxY >= 1) { + return vanilla; + } + } + boolean calculatedSnow = above.getPropertyKeys().contains(BlockGrass.SNOWY) + && GrassLifecycle.hasSnowAppearance(world, abovePos); + return physicalSnow || calculatedSnow ? vanilla.withProperty(BlockGrass.SNOWY, true) : vanilla; + } + + static boolean isSnowPiece(IBlockState state) { + Block block = state.getBlock(); + return block == Blocks.SNOW || block == Blocks.SNOW_LAYER + || block instanceof PieceBlock && ((PieceBlock) block).definition(state).type.equals("snow"); + } +} diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LegacyBridge.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LegacyBridge.java index 9391b13e9..62b7911a6 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LegacyBridge.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LegacyBridge.java @@ -219,6 +219,13 @@ private static final class StackChange { } } + /** Forge can return an NBT object that its file thread is still writing after an unload. */ + public static NBTTagCompound prepareChunkForRead(World world, NBTTagCompound stored) { + NBTTagCompound snapshot = stored.copy(); + prepareChunk(world, snapshot); + return snapshot; + } + public static void prepareChunk(World world, NBTTagCompound root) { if (ready) { zone.moddev.mc.skysbuildingpieces.compat.MineralogyCompat.prepareStacks(root.getCompoundTag("Level")); diff --git a/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LoaderTransformer.java b/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LoaderTransformer.java index 337505052..77d87dd19 100644 --- a/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LoaderTransformer.java +++ b/src/main/java/zone/moddev/mc/skysbuildingpieces/legacy/LoaderTransformer.java @@ -8,6 +8,7 @@ public final class LoaderTransformer implements IClassTransformer { private static final String BRIDGE = "zone/moddev/mc/skysbuildingpieces/legacy/LegacyBridge"; private static final String PLACEMENT = "zone/moddev/mc/skysbuildingpieces/content/NativeSlabPlacement"; + private static final String SNOW = "zone/moddev/mc/skysbuildingpieces/content/SnowCover"; public byte[] transform(String name, String transformedName, byte[] bytes) { if (bytes == null) { @@ -18,8 +19,9 @@ public byte[] transform(String name, String transformedName, byte[] bytes) { boolean item = transformedName.equals("net.minecraft.item.ItemStack"); boolean placement = transformedName.equals("net.minecraft.item.ItemSlab") || transformedName.equals("net.minecraft.item.ItemBlock"); + boolean grass = transformedName.equals("net.minecraft.block.BlockGrass"); - if (!chunk && !item && !placement) { + if (!chunk && !item && !placement && !grass) { return bytes; } @@ -34,6 +36,15 @@ public byte[] transform(String name, String transformedName, byte[] bytes) { String mappedName = net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper.INSTANCE .mapMethodName(node.name, method.name, method.desc); + if (grass) { + if (method.name.equals("getActualState") || method.name.equals("func_176221_a") + || mappedName.equals("func_176221_a")) { + ++found; + addSnowHook(method); + } + continue; + } + if (placement && (method.name.equals("onItemUse") || method.name.equals("func_180614_a") || mappedName.equals("func_180614_a"))) { ++placementFound; @@ -77,12 +88,15 @@ public byte[] transform(String name, String transformedName, byte[] bytes) { hook.add(new VarInsnNode(Opcodes.ALOAD, 1)); } - descriptor = chunk ? "(" + args[0].getDescriptor() + args[3].getDescriptor() + ")V" + descriptor = chunk ? "(" + args[0].getDescriptor() + args[3].getDescriptor() + ")" + args[3].getDescriptor() : "(" + args[0].getDescriptor() + ")V"; descriptor = net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper.INSTANCE .mapMethodDesc(descriptor); - hook.add(new MethodInsnNode(Opcodes.INVOKESTATIC, BRIDGE, chunk ? "prepareChunk" : "prepareStack", + hook.add(new MethodInsnNode(Opcodes.INVOKESTATIC, BRIDGE, chunk ? "prepareChunkForRead" : "prepareStack", descriptor, false)); + if (chunk) { + hook.add(new VarInsnNode(Opcodes.ASTORE, 4)); + } method.instructions.insert(hook); } if (!placement && found != 1) { @@ -110,6 +124,33 @@ private static boolean hasHook(MethodNode method, String owner) { return false; } + private static void addSnowHook(MethodNode method) { + String descriptor = net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper.INSTANCE + .mapMethodDesc(method.desc); + if ((method.access & Opcodes.ACC_STATIC) != 0 || !descriptor.equals( + "(Lnet/minecraft/block/state/IBlockState;Lnet/minecraft/world/IBlockAccess;Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/state/IBlockState;")) { + throw new IllegalStateException("Unexpected grass actual-state structure for snowy supports"); + } + if (hasHook(method, SNOW)) { + return; + } + int returns = 0; + for (AbstractInsnNode instruction : method.instructions.toArray()) { + if (instruction.getOpcode() == Opcodes.ARETURN) { + InsnList hook = new InsnList(); + // Keep vanilla's result, adding only a calculated cap beneath a snowy partial piece. + hook.add(new VarInsnNode(Opcodes.ALOAD, 2)); + hook.add(new VarInsnNode(Opcodes.ALOAD, 3)); + hook.add(new MethodInsnNode(Opcodes.INVOKESTATIC, SNOW, "actualState", descriptor, false)); + method.instructions.insertBefore(instruction, hook); + ++returns; + } + } + if (returns == 0) { + throw new IllegalStateException("Grass actual-state method has no return to wrap"); + } + } + private static void addPlacementHook(MethodNode method) { String descriptor = net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper.INSTANCE .mapMethodDesc(method.desc); diff --git a/src/main/resources/assets/skysbuildingpieces/lang/de_at.lang b/src/main/resources/assets/skysbuildingpieces/lang/de_at.lang index 8d1b056dc..9acfd7def 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/de_at.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/de_at.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=grüner Wolle material.skysbuildingpieces.minecraft.wool_red=roter Wolle material.skysbuildingpieces.minecraft.wool_black=schwarzer Wolle material.skysbuildingpieces.minecraft.grass_path=Weg +config.skysbuildingpieces.directionalSlabPlacement=Richtungsabhängige Stufenplatzierung +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Erlaubt das senkrechte Platzieren von Stufen per Klick auf Flächen und Kanten. Änderung erfordert einen Neustart. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Alte Bauteile ersetzen +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Ersetzt unterstützte alte Bauteile, wenn ihre ursprüngliche Mod installiert ist. Sichere vorher deine Welt. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/de_au.lang b/src/main/resources/assets/skysbuildingpieces/lang/de_au.lang index 8d1b056dc..9acfd7def 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/de_au.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/de_au.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=grüner Wolle material.skysbuildingpieces.minecraft.wool_red=roter Wolle material.skysbuildingpieces.minecraft.wool_black=schwarzer Wolle material.skysbuildingpieces.minecraft.grass_path=Weg +config.skysbuildingpieces.directionalSlabPlacement=Richtungsabhängige Stufenplatzierung +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Erlaubt das senkrechte Platzieren von Stufen per Klick auf Flächen und Kanten. Änderung erfordert einen Neustart. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Alte Bauteile ersetzen +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Ersetzt unterstützte alte Bauteile, wenn ihre ursprüngliche Mod installiert ist. Sichere vorher deine Welt. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/de_de.lang b/src/main/resources/assets/skysbuildingpieces/lang/de_de.lang index 8d1b056dc..9acfd7def 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/de_de.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/de_de.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=grüner Wolle material.skysbuildingpieces.minecraft.wool_red=roter Wolle material.skysbuildingpieces.minecraft.wool_black=schwarzer Wolle material.skysbuildingpieces.minecraft.grass_path=Weg +config.skysbuildingpieces.directionalSlabPlacement=Richtungsabhängige Stufenplatzierung +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Erlaubt das senkrechte Platzieren von Stufen per Klick auf Flächen und Kanten. Änderung erfordert einen Neustart. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Alte Bauteile ersetzen +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Ersetzt unterstützte alte Bauteile, wenn ihre ursprüngliche Mod installiert ist. Sichere vorher deine Welt. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/en_ca.lang b/src/main/resources/assets/skysbuildingpieces/lang/en_ca.lang index 5349a644c..03128fe14 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/en_ca.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/en_ca.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=Green Wool material.skysbuildingpieces.minecraft.wool_red=Red Wool material.skysbuildingpieces.minecraft.wool_black=Black Wool material.skysbuildingpieces.minecraft.grass_path=Path +config.skysbuildingpieces.directionalSlabPlacement=Directional slab placement +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Allow regular slabs to be placed vertically using face and edge clicks. Restart after changing this. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Replace legacy pieces +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Replace supported legacy pieces when their original mod is installed. Back up your world first. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/en_en.lang b/src/main/resources/assets/skysbuildingpieces/lang/en_en.lang index 5349a644c..03128fe14 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/en_en.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/en_en.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=Green Wool material.skysbuildingpieces.minecraft.wool_red=Red Wool material.skysbuildingpieces.minecraft.wool_black=Black Wool material.skysbuildingpieces.minecraft.grass_path=Path +config.skysbuildingpieces.directionalSlabPlacement=Directional slab placement +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Allow regular slabs to be placed vertically using face and edge clicks. Restart after changing this. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Replace legacy pieces +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Replace supported legacy pieces when their original mod is installed. Back up your world first. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/en_gb.lang b/src/main/resources/assets/skysbuildingpieces/lang/en_gb.lang index 5349a644c..03128fe14 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/en_gb.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/en_gb.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=Green Wool material.skysbuildingpieces.minecraft.wool_red=Red Wool material.skysbuildingpieces.minecraft.wool_black=Black Wool material.skysbuildingpieces.minecraft.grass_path=Path +config.skysbuildingpieces.directionalSlabPlacement=Directional slab placement +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Allow regular slabs to be placed vertically using face and edge clicks. Restart after changing this. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Replace legacy pieces +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Replace supported legacy pieces when their original mod is installed. Back up your world first. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/en_pt.lang b/src/main/resources/assets/skysbuildingpieces/lang/en_pt.lang index 5349a644c..03128fe14 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/en_pt.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/en_pt.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=Green Wool material.skysbuildingpieces.minecraft.wool_red=Red Wool material.skysbuildingpieces.minecraft.wool_black=Black Wool material.skysbuildingpieces.minecraft.grass_path=Path +config.skysbuildingpieces.directionalSlabPlacement=Directional slab placement +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Allow regular slabs to be placed vertically using face and edge clicks. Restart after changing this. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Replace legacy pieces +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Replace supported legacy pieces when their original mod is installed. Back up your world first. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/en_us.lang b/src/main/resources/assets/skysbuildingpieces/lang/en_us.lang index 5349a644c..03128fe14 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/en_us.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/en_us.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=Green Wool material.skysbuildingpieces.minecraft.wool_red=Red Wool material.skysbuildingpieces.minecraft.wool_black=Black Wool material.skysbuildingpieces.minecraft.grass_path=Path +config.skysbuildingpieces.directionalSlabPlacement=Directional slab placement +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Allow regular slabs to be placed vertically using face and edge clicks. Restart after changing this. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Replace legacy pieces +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Replace supported legacy pieces when their original mod is installed. Back up your world first. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/es_es.lang b/src/main/resources/assets/skysbuildingpieces/lang/es_es.lang index 1c280cffd..dee65201e 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/es_es.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/es_es.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=lana verde material.skysbuildingpieces.minecraft.wool_red=lana roja material.skysbuildingpieces.minecraft.wool_black=lana negra material.skysbuildingpieces.minecraft.grass_path=Camino +config.skysbuildingpieces.directionalSlabPlacement=Colocación direccional de losas +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Permite colocar losas normales en vertical haciendo clic en caras y bordes. Reinicia tras cambiar esta opción. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Reemplazar piezas antiguas +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Sustituye las piezas antiguas compatibles si está instalado el mod original. Haz antes una copia de tu mundo. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/es_mx.lang b/src/main/resources/assets/skysbuildingpieces/lang/es_mx.lang index 1c280cffd..dee65201e 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/es_mx.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/es_mx.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=lana verde material.skysbuildingpieces.minecraft.wool_red=lana roja material.skysbuildingpieces.minecraft.wool_black=lana negra material.skysbuildingpieces.minecraft.grass_path=Camino +config.skysbuildingpieces.directionalSlabPlacement=Colocación direccional de losas +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Permite colocar losas normales en vertical haciendo clic en caras y bordes. Reinicia tras cambiar esta opción. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Reemplazar piezas antiguas +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Sustituye las piezas antiguas compatibles si está instalado el mod original. Haz antes una copia de tu mundo. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/fr_ca.lang b/src/main/resources/assets/skysbuildingpieces/lang/fr_ca.lang index e4cac5405..ee68610c5 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/fr_ca.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/fr_ca.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=laine verte material.skysbuildingpieces.minecraft.wool_red=laine rouge material.skysbuildingpieces.minecraft.wool_black=laine noire material.skysbuildingpieces.minecraft.grass_path=Chemin +config.skysbuildingpieces.directionalSlabPlacement=Placement directionnel des dalles +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Permet de poser les dalles à la verticale en cliquant sur une face ou une arête. Redémarre après avoir modifié ce réglage. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Remplacer les anciennes pièces +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Remplace les pièces anciennes prises en charge si leur mod d'origine est installé. Fais d'abord une copie de ton monde. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/fr_fr.lang b/src/main/resources/assets/skysbuildingpieces/lang/fr_fr.lang index e4cac5405..ee68610c5 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/fr_fr.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/fr_fr.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=laine verte material.skysbuildingpieces.minecraft.wool_red=laine rouge material.skysbuildingpieces.minecraft.wool_black=laine noire material.skysbuildingpieces.minecraft.grass_path=Chemin +config.skysbuildingpieces.directionalSlabPlacement=Placement directionnel des dalles +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Permet de poser les dalles à la verticale en cliquant sur une face ou une arête. Redémarre après avoir modifié ce réglage. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Remplacer les anciennes pièces +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Remplace les pièces anciennes prises en charge si leur mod d'origine est installé. Fais d'abord une copie de ton monde. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/ja_jp.lang b/src/main/resources/assets/skysbuildingpieces/lang/ja_jp.lang index 8b5b324e0..13145e9bb 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/ja_jp.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/ja_jp.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=緑色の羊毛 material.skysbuildingpieces.minecraft.wool_red=赤色の羊毛 material.skysbuildingpieces.minecraft.wool_black=黒色の羊毛 material.skysbuildingpieces.minecraft.grass_path=土の道 +config.skysbuildingpieces.directionalSlabPlacement=ハーフブロックの向き指定 +config.skysbuildingpieces.directionalSlabPlacement.tooltip=面や縁をクリックして、通常のハーフブロックを縦に設置できるようにします。変更後は再起動してください。 +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=旧式の建材を置き換える +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=元のMODが入っているときに、対応する旧パーツを置き換えます。先にワールドをバックアップしてください。 diff --git a/src/main/resources/assets/skysbuildingpieces/lang/ko_kr.lang b/src/main/resources/assets/skysbuildingpieces/lang/ko_kr.lang index eb211cc1c..5dacd9a6c 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/ko_kr.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/ko_kr.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=초록색 양털 material.skysbuildingpieces.minecraft.wool_red=빨간색 양털 material.skysbuildingpieces.minecraft.wool_black=검은색 양털 material.skysbuildingpieces.minecraft.grass_path=흙길 +config.skysbuildingpieces.directionalSlabPlacement=반 블록 방향 지정 배치 +config.skysbuildingpieces.directionalSlabPlacement.tooltip=면이나 모서리를 클릭해 일반 반 블록을 세로로 놓을 수 있습니다. 변경한 뒤 게임을 다시 시작하세요. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=이전 건축 부품 교체 +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=원래 모드가 설치되어 있으면 지원되는 옛 부품을 교체합니다. 먼저 월드를 백업하세요. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/pt_br.lang b/src/main/resources/assets/skysbuildingpieces/lang/pt_br.lang index 158243745..786da7e2e 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/pt_br.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/pt_br.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=lã verde material.skysbuildingpieces.minecraft.wool_red=lã vermelha material.skysbuildingpieces.minecraft.wool_black=lã preta material.skysbuildingpieces.minecraft.grass_path=Caminho +config.skysbuildingpieces.directionalSlabPlacement=Colocação direcional de lajes +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Permite colocar lajes comuns na vertical ao clicar em faces ou bordas. Reinicie o jogo após alterar esta opção. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Substituir peças antigas +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Substitui peças antigas compatíveis se o mod original estiver instalado. Faça primeiro uma cópia do seu mundo. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/pt_pt.lang b/src/main/resources/assets/skysbuildingpieces/lang/pt_pt.lang index 3958b0d19..c4e3bc150 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/pt_pt.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/pt_pt.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=lã verde material.skysbuildingpieces.minecraft.wool_red=lã vermelha material.skysbuildingpieces.minecraft.wool_black=lã preta material.skysbuildingpieces.minecraft.grass_path=Caminho +config.skysbuildingpieces.directionalSlabPlacement=Colocação direcional de lajes +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Permite colocar lajes normais na vertical ao clicar numa face ou aresta. Reinicia o jogo depois de alterar esta opção. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Substituir peças antigas +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Substitui peças antigas compatíveis se o mod original estiver instalado. Faz primeiro uma cópia do teu mundo. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/ru_ru.lang b/src/main/resources/assets/skysbuildingpieces/lang/ru_ru.lang index e89cf0c0a..5522a44d1 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/ru_ru.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/ru_ru.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=зелёной шерсти material.skysbuildingpieces.minecraft.wool_red=красной шерсти material.skysbuildingpieces.minecraft.wool_black=чёрной шерсти material.skysbuildingpieces.minecraft.grass_path=Тропа +config.skysbuildingpieces.directionalSlabPlacement=Установка плит с выбором направления +config.skysbuildingpieces.directionalSlabPlacement.tooltip=Позволяет ставить обычные плиты вертикально, нажимая на грани и края. После изменения перезапустите игру. +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=Заменять старые детали +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=Заменяет поддерживаемые старые детали, если установлен исходный мод. Сначала сделайте резервную копию мира. diff --git a/src/main/resources/assets/skysbuildingpieces/lang/zh_cn.lang b/src/main/resources/assets/skysbuildingpieces/lang/zh_cn.lang index c62a6cba7..f358e6e40 100644 --- a/src/main/resources/assets/skysbuildingpieces/lang/zh_cn.lang +++ b/src/main/resources/assets/skysbuildingpieces/lang/zh_cn.lang @@ -118,3 +118,7 @@ material.skysbuildingpieces.minecraft.wool_green=绿色羊毛 material.skysbuildingpieces.minecraft.wool_red=红色羊毛 material.skysbuildingpieces.minecraft.wool_black=黑色羊毛 material.skysbuildingpieces.minecraft.grass_path=土径 +config.skysbuildingpieces.directionalSlabPlacement=按方向放置台阶 +config.skysbuildingpieces.directionalSlabPlacement.tooltip=允许通过点击方块的面或边缘竖直放置普通台阶。更改后请重启游戏。 +config.skysbuildingpieces.forceReplaceBuildingBricksPieces=替换旧版建筑部件 +config.skysbuildingpieces.forceReplaceBuildingBricksPieces.tooltip=安装了原模组时,替换受支持的旧建筑部件。请先备份世界。 diff --git a/src/test/java/zone/moddev/mc/skysbuildingpieces/LoaderHooksTest.java b/src/test/java/zone/moddev/mc/skysbuildingpieces/LoaderHooksTest.java index 13a3cfb98..3fb0683b1 100644 --- a/src/test/java/zone/moddev/mc/skysbuildingpieces/LoaderHooksTest.java +++ b/src/test/java/zone/moddev/mc/skysbuildingpieces/LoaderHooksTest.java @@ -7,6 +7,21 @@ import static org.junit.jupiter.api.Assertions.*; class LoaderHooksTest { + @Test + void chunkRecoveryNeverEditsThePendingSaveObject() { + net.minecraft.nbt.NBTTagCompound queued = new net.minecraft.nbt.NBTTagCompound(); + net.minecraft.nbt.NBTTagCompound level = new net.minecraft.nbt.NBTTagCompound(); + level.setString("unrelated", "keep"); + queued.setTag("Level", level); + net.minecraft.nbt.NBTTagCompound before = queued.copy(); + net.minecraft.nbt.NBTTagCompound loaded = + zone.moddev.mc.skysbuildingpieces.legacy.LegacyBridge.prepareChunkForRead(null, queued); + assertNotSame(queued, loaded); + assertNotSame(level, loaded.getCompoundTag("Level")); + loaded.getCompoundTag("Level").setInteger("new_coverage", 1); + assertEquals(before, queued, "the file thread retains its own immutable snapshot"); + } + private byte[] fixture(String name, String method, String descriptor) { ClassWriter w = new ClassWriter(0); @@ -113,9 +128,10 @@ void nativePlacementHooksAreExactAndIdempotent() { } @Test - void realForge112ClassesMatchAllFourHooks() throws Exception { + void realForge112ClassesMatchAllFiveHooks() throws Exception { for (String name : new String[] { "net.minecraft.item.ItemStack", "net.minecraft.item.ItemBlock", - "net.minecraft.item.ItemSlab", "net.minecraft.world.chunk.storage.AnvilChunkLoader" }) { + "net.minecraft.item.ItemSlab", "net.minecraft.world.chunk.storage.AnvilChunkLoader", + "net.minecraft.block.BlockGrass" }) { try (java.io.InputStream stream = getClass().getClassLoader() .getResourceAsStream(name.replace('.', '/') + ".class")) { assertNotNull(stream, name); @@ -152,4 +168,14 @@ void realForge112ClassesMatchAllFourHooks() throws Exception { } } } + + @Test + void grassVisualHookRejectsMissingOrChangedMethods() { + String name = "net.minecraft.block.BlockGrass"; + LoaderTransformer transformer = new LoaderTransformer(); + assertThrows(IllegalStateException.class, () -> transformer.transform(name, name, + fixture(name.replace('.', '/'), "getActualState", "()Ljava/lang/Object;"))); + assertThrows(IllegalStateException.class, () -> transformer.transform(name, name, + fixture(name.replace('.', '/'), "unexpectedMethod", "()V"))); + } } diff --git a/src/test/java/zone/moddev/mc/skysbuildingpieces/ResourceTest.java b/src/test/java/zone/moddev/mc/skysbuildingpieces/ResourceTest.java index 06af60ab6..0c54d549c 100644 --- a/src/test/java/zone/moddev/mc/skysbuildingpieces/ResourceTest.java +++ b/src/test/java/zone/moddev/mc/skysbuildingpieces/ResourceTest.java @@ -49,7 +49,9 @@ void allEighteenUtf8LocalesMatch() throws Exception { assertTrue(line.substring(line.indexOf('=') + 1).length() > 0); } - assertEquals(17 + Catalogue.INSTANCE.materials.size(), current.size()); + assertEquals(21 + Catalogue.INSTANCE.materials.size(), current.size()); + assertTrue(current.contains("config.skysbuildingpieces.directionalSlabPlacement")); + assertTrue(current.contains("config.skysbuildingpieces.directionalSlabPlacement.tooltip")); assertTrue(current.contains("itemGroup.skysbuildingpieces")); if (keys == null) {