From e28079566b492b432c59ac8f1bae2c01c4136cff Mon Sep 17 00:00:00 2001 From: Dustin Norberg Date: Wed, 30 Sep 2026 16:44:22 -0400 Subject: [PATCH] Implement terrain symbol generation profiles --- BUILDING.txt | 6 +- README.md | 3 +- build.gradle | 72 +++---- docs/AGE_PROFILES.md | 30 ++- docs/GAMETESTS.md | 9 +- docs/WRITING_GRAMMAR.md | 4 +- gradle.properties | 2 +- .../rivencraft/book/AgeDefinition.java | 2 +- .../rivencraft/book/AgeDimensionService.java | 27 ++- .../rivencraft/book/AgeRuntimeProfiles.java | 15 +- .../book/TerrainWritingGameTests.java | 175 ++++++++++++++++++ .../gametest/WritingDataGameTests.java | 16 ++ .../dnorberg/rivencraft/item/PageItem.java | 55 ++++-- .../rivencraft/registry/ModCreativeTabs.java | 5 +- .../rivencraft/writing/SymbolPoems.java | 5 + .../assets/rivencraft/lang/en_us.json | 10 + .../rivencraft/symbols/terrain/amplified.json | 8 + .../rivencraft/symbols/terrain/cave.json | 8 + .../rivencraft/symbols/terrain/flat.json | 8 + .../rivencraft/symbols/terrain/island.json | 8 + .../rivencraft/symbols/terrain/void.json | 8 + 21 files changed, 398 insertions(+), 78 deletions(-) create mode 100644 src/main/java/net/dnorberg/rivencraft/book/TerrainWritingGameTests.java create mode 100644 src/main/resources/data/rivencraft/rivencraft/symbols/terrain/amplified.json create mode 100644 src/main/resources/data/rivencraft/rivencraft/symbols/terrain/cave.json create mode 100644 src/main/resources/data/rivencraft/rivencraft/symbols/terrain/flat.json create mode 100644 src/main/resources/data/rivencraft/rivencraft/symbols/terrain/island.json create mode 100644 src/main/resources/data/rivencraft/rivencraft/symbols/terrain/void.json diff --git a/BUILDING.txt b/BUILDING.txt index 6bce045..42153b0 100644 --- a/BUILDING.txt +++ b/BUILDING.txt @@ -75,9 +75,9 @@ All required GameTests should pass before distributing a build. GameTests use `build/gametest-run/world`, separate from the normal development world. Gradle starts each default run with a fresh world and removes it after -a successful run. Failed worlds are retained under -`build/gametest-run/failed-worlds/` for inspection until the next successful -run. Logs and configuration are kept. A caller-supplied `-PgameTestRunDir` +every run, whether tests pass or fail. The GameTest server always uses seed `0`, +so retries regenerate a clean world with that seed. Logs and configuration are kept. +A caller-supplied `-PgameTestRunDir` is never removed automatically. To run the suite in a fresh temporary directory instead, use: diff --git a/README.md b/README.md index f62ee8d..f3c1a9a 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,8 @@ Panel, it describes a randomly generated Age. Authored writing is compiled once into a versioned, server-owned Age plan. The plan freezes the Age seed, resolved symbol meanings, page order, and runtime profile, so later data-pack changes do not reinterpret an existing Age. An authored terrain page selects its runtime -profile; other symbol effects are scheduled for later Milestone 5 slices. The +profile. Built-in pages cover Standard, Amplified, Cave, Island, Flat, and Void; +other symbol effects are scheduled for later Milestone 5 slices. The writing is also stored on the book; the Descriptive Book screen's turned pages show ordered symbols and unresolved IDs. The Descriptive Book screen follows Legacy's book spread: the title and Age details are on the left, the destination diff --git a/build.gradle b/build.gradle index 26fc36a..7e3ae1a 100644 --- a/build.gradle +++ b/build.gradle @@ -38,6 +38,35 @@ sourceSets.main.resources { exclude("src/generated/**/.cache") // datagen cache files } +// Generate the client-safe creative-page index from bundled symbol definitions. +// New built-in symbols then appear in the Pages tab without another Java list. +abstract class GenerateCreativeSymbolIndex extends DefaultTask { + @InputDirectory abstract DirectoryProperty getSymbolsDir() + @OutputDirectory abstract DirectoryProperty getIndexDir() + + @TaskAction void generate() { + File root = symbolsDir.get().asFile + def definitions = new LinkedHashMap() + java.nio.file.Files.walk(root.toPath()).withCloseable { paths -> + paths.filter { java.nio.file.Files.isRegularFile(it) && it.toString().endsWith('.json') } + .sorted().forEach { source -> + String path = root.toPath().relativize(source).toString() + .replace('\\', '/').replaceAll(/\.json$/, '') + definitions["rivencraft:${path}"] = new groovy.json.JsonSlurper().parse(source.toFile()) + } + } + File index = new File(indexDir.get().asFile, 'assets/rivencraft/creative_symbol_pages.json') + index.parentFile.mkdirs() + index.text = groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(definitions)) + '\n' + } +} + +def generateCreativeSymbolIndex = tasks.register('generateCreativeSymbolIndex', GenerateCreativeSymbolIndex) { + symbolsDir.set(layout.projectDirectory.dir('src/main/resources/data/rivencraft/rivencraft/symbols')) + indexDir.set(layout.buildDirectory.dir('generated/resources/creativeSymbols')) +} +sourceSets.main.resources.srcDir generateCreativeSymbolIndex + // Archived suites use separate namespaces but share the same empty structure. tasks.named('processResources', ProcessResources).configure { archivedGameTestSuites.each { suite -> @@ -148,67 +177,38 @@ neoForge { } } -// Every default run gets a fresh world. Failed worlds stay available until a -// successful run; caller-supplied directories are never managed here. +// Vanilla's GameTestServer uses a fixed world seed of 0. Every default run +// regenerates its world; custom run directories are never managed here. boolean customGameTestRunDir = providers.gradleProperty('gameTestRunDir').isPresent() File dedicatedGameTestBuildDir = layout.buildDirectory.get().asFile File dedicatedGameTestDir = layout.buildDirectory.dir('gametest-run').get().asFile -File dedicatedGameTestWorld = new File(dedicatedGameTestDir, 'world') -File gameTestSuccessMarker = new File(dedicatedGameTestDir, '.last-gametest-succeeded') def prepareGameTestWorld = tasks.register('prepareGameTestWorld') { onlyIf { !customGameTestRunDir } doLast { - java.nio.file.Files.deleteIfExists(gameTestSuccessMarker.toPath()) - File preserved = GameTestWorlds.preserve(dedicatedGameTestBuildDir, dedicatedGameTestDir) - if (preserved != null) logger.lifecycle('Preserved GameTest world for inspection at {}', preserved) + GameTestWorlds.clean(dedicatedGameTestBuildDir, dedicatedGameTestDir) } } def finishGameTestWorld = tasks.register('finishGameTestWorld') { onlyIf { !customGameTestRunDir } doLast { - if (gameTestSuccessMarker.exists()) { - GameTestWorlds.clean(dedicatedGameTestBuildDir, dedicatedGameTestDir) - java.nio.file.Files.delete(gameTestSuccessMarker.toPath()) - } else { - File preserved = GameTestWorlds.preserve(dedicatedGameTestBuildDir, dedicatedGameTestDir) - if (preserved != null) logger.lifecycle('Preserved GameTest world for inspection at {}', preserved) - } + GameTestWorlds.clean(dedicatedGameTestBuildDir, dedicatedGameTestDir) } } tasks.named('runGameTestServer').configure { dependsOn(prepareGameTestWorld) finalizedBy(finishGameTestWorld) - doLast { - if (!customGameTestRunDir) { - GameTestWorlds.check(dedicatedGameTestBuildDir, dedicatedGameTestDir) - java.nio.file.Files.createFile(gameTestSuccessMarker.toPath()) - } - } } class GameTestWorlds { static void check(File buildDir, File runDir) { - [buildDir, runDir, new File(runDir, 'world'), new File(runDir, 'failed-worlds')].each { path -> + [buildDir, runDir, new File(runDir, 'world'), new File(runDir, 'failed-worlds'), + new File(runDir, 'failed-seed.txt'), new File(runDir, '.last-gametest-succeeded')].each { path -> if (java.nio.file.Files.isSymbolicLink(path.toPath())) { throw new GradleException("Refusing to manage a symlinked GameTest path: ${path}") } } } - static File preserve(File buildDir, File runDir) { - File world = new File(runDir, 'world') - if (!world.exists()) return null - check(buildDir, runDir) - if (!world.isDirectory()) throw new GradleException("Expected a GameTest world directory: ${world}") - File failures = new File(runDir, 'failed-worlds') - java.nio.file.Files.createDirectories(failures.toPath()) - String snapshot = java.time.format.DateTimeFormatter.ofPattern('yyyyMMdd-HHmmss-SSS') - .format(java.time.LocalDateTime.now()) + '-' + java.util.UUID.randomUUID() - File destination = new File(failures, snapshot) - java.nio.file.Files.move(world.toPath(), destination.toPath()) - return destination - } - static void clean(File buildDir, File runDir) { check(buildDir, runDir) [new File(runDir, 'world'), new File(runDir, 'failed-worlds')].each { root -> @@ -220,6 +220,8 @@ class GameTestWorlds { } } } + java.nio.file.Files.deleteIfExists(new File(runDir, 'failed-seed.txt').toPath()) + java.nio.file.Files.deleteIfExists(new File(runDir, '.last-gametest-succeeded').toPath()) } } diff --git a/docs/AGE_PROFILES.md b/docs/AGE_PROFILES.md index cf455be..a24c2d6 100644 --- a/docs/AGE_PROFILES.md +++ b/docs/AGE_PROFILES.md @@ -30,15 +30,35 @@ resources and can be overridden by a higher-priority pack. The example under directory. Valid custom profiles join the stable, sorted pool used when a new Age rolls its base terrain; the selected ID is then persisted with that Age. +Each built-in profile now has a matching `terrain/` Symbol Page. Put one +of those pages after the Link Panel in a Book Binder to select that terrain +instead of the seed-selected random profile. Standard, Amplified, and Cave use +their corresponding registered noise settings; Island uses Minecraft's +floating-islands noise settings; Flat and Void use flat-source generators. +The Cave and Island pages are Rivencraft terrain choices based on existing +profiles, not claims that Legacy had identically named terrain symbols. +Every family retains a safe cobblestone arrival platform. An omitted terrain +page still uses the deterministic seed-selected profile. + ## Persistence and reload behavior An Age permanently stores its selected profile ID, generation version, seed, -and rolled traits. `/reload` replaces the profile definitions but does not -reroll those immutable values. An unloaded Age resolves its stored profile -again when it loads, so intentional profile overrides affect its runtime -resources and newly generated chunks. +and rolled traits. For an **authored** Age, the generation plan also stores a +copy of the resolved runtime profile: terrain shape, noise settings, biome +preset, and dimension type. `/reload` cannot reinterpret that plan; an unloaded +authored Age uses the saved profile snapshot when it loads, even if the defining +symbol or profile JSON has since changed. An older, page-free Age has no plan +and continues to resolve its saved profile ID at load time. -A profile removed after an Age was created resolves to `rivencraft:standard`. +Registered noise, biome-preset, and dimension-type IDs are validated when +profiles load. Before loading an authored Age, the saved references are checked +again. If a data pack supplying one has been removed, the dimension stays +unloaded and the log identifies the missing resource; the Age's plan is not +silently replaced. Restore the pack to load that Age. A custom dimension type +retains its own skylight capability: normal lighting cannot make a Nether-style +type skylit. + +A profile removed after a page-free Age was created resolves to `rivencraft:standard`. The legacy `rivencraft:random_vanilla` alias also resolves to `standard`. Rivencraft logs this fallback. Invalid built-in overrides do not replace the required built-in definitions; a reload fails if a required built-in profile diff --git a/docs/GAMETESTS.md b/docs/GAMETESTS.md index 1004d85..be1cfb2 100644 --- a/docs/GAMETESTS.md +++ b/docs/GAMETESTS.md @@ -34,11 +34,10 @@ Immersive Portals. The core suite delegates to the original regression methods for its selected cases, so the two suites do not maintain duplicate test logic. GameTest Ages are created in `build/gametest-run/world`, not in a development -client save. Every default GameTest invocation starts with a fresh world. If -tests fail, Gradle moves the world under `build/gametest-run/failed-worlds/` -for inspection. A retry starts fresh but keeps those failed worlds; the next -successful run removes them and its own world. A forcibly killed run may leave -`world` behind; the next run preserves it as a failure snapshot before starting. +client save. Every default GameTest invocation starts with a fresh world. +Minecraft 1.21.1's GameTest server uses the fixed seed `0`. Gradle deletes the +world after every run, whether tests pass or fail. A forcibly killed run may +leave `world` behind; the next run deletes it before starting. Logs and configuration remain available. Cleanup never targets a custom `-PgameTestRunDir` or a player world; callers using a custom directory manage it themselves. The full suite should still be run diff --git a/docs/WRITING_GRAMMAR.md b/docs/WRITING_GRAMMAR.md index d60b946..609219d 100644 --- a/docs/WRITING_GRAMMAR.md +++ b/docs/WRITING_GRAMMAR.md @@ -8,4 +8,6 @@ The supported order follows the representable subset of the [Legacy grammar audi Missing terrain, controller, weather, lighting, celestial, or the controller's minimum biome count is an **incomplete** warning, not an error: the compiler retains the seed-selected profile and traits for missing branches. The minimum is zero for Native, one for Single, two for Tiled/Grid, and three for Tiny–Huge. Native cannot consume authored biome pages; Single accepts only one. Unknown IDs, schema-v1 display-only symbols, wrong ordering, misplaced modifiers, duplicates, conflicts, missing/extra Link Panels, and oversized writing are errors. The Binder disables output and exposes the first error on the result-slot tooltip. When that error belongs to a page, its thumbnail is tinted and outlined red, the strip scrolls to it, and hovering it shows the diagnostic. This maps the parser's compact entry position back through any empty page positions. Rejected inputs remain removable. Binding an unwritten Descriptive Book rechecks its server-owned writing and reports the first error without creating an Age. A terrain symbol whose profile is unavailable is also rejected before Binder inputs are consumed. -The plan stores the original writing order, the authoritative semantic value of each resolved symbol, the Age seed, and a copy of the selected runtime profile. An explicit terrain page replaces the random terrain selection; an omitted terrain uses the seed-selected profile. Age loading uses the frozen runtime profile and does not need the original symbol definition or runtime-profile JSON. Existing bound books without plans are not reinterpreted. Page-free and Link-Panel-only books keep the pre-existing random path. Biome, lighting, weather, celestial, and feature effects are retained in the plan but will be applied in issues #33–#35; instability remains Milestone 6 work. +The plan stores the original writing order, the authoritative semantic value of each resolved symbol, the Age seed, and a copy of the selected runtime profile. An explicit terrain page replaces the random terrain selection; an omitted terrain uses the seed-selected profile. The built-in Standard, Amplified, Cave, Island, Flat, and Void terrain pages now select their matching generation resources. Age loading uses the frozen runtime profile and does not need the original symbol definition or runtime-profile JSON, though its referenced noise, biome-preset, and dimension-type registry entries must remain available. Existing bound books without plans are not reinterpreted. Page-free and Link-Panel-only books keep the pre-existing random path. Biome, lighting, weather, celestial, and feature effects are retained in the plan but will be applied in issues #33–#35; instability remains Milestone 6 work. + +The Rivencraft Pages creative tab reads a generated index of bundled symbol definitions. Adding another valid JSON symbol under `src/main/resources/data/rivencraft/rivencraft/symbols/` includes its page automatically in the next build; no Java starter-page list needs updating. The server catalog still decides whether that page is valid for writing. External server data-pack symbols are not included in this bundled index. diff --git a/gradle.properties b/gradle.properties index 7ab70c8..e942439 100644 --- a/gradle.properties +++ b/gradle.properties @@ -36,7 +36,7 @@ mod_name=Rivencraft # The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. mod_license=LGPL-3.0-or-later # The mod version. Rivencraft uses the x.y.z.b policy documented in README.md. -mod_version=0.4.3.0 +mod_version=0.4.4.1 immersive_portals_version=6.0.7 # The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. # This should match the base package used for the mod sources. diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeDefinition.java b/src/main/java/net/dnorberg/rivencraft/book/AgeDefinition.java index e6f60af..20a3c56 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeDefinition.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeDefinition.java @@ -22,7 +22,7 @@ public record AgeDefinition( public static final ResourceLocation RANDOM_VANILLA_PROFILE = ResourceLocation.fromNamespaceAndPath( Rivencraft.MOD_ID, "random_vanilla" ); - public static final int CURRENT_GENERATION_VERSION = 14; + public static final int CURRENT_GENERATION_VERSION = 15; public AgeDefinition { Objects.requireNonNull(id, "id"); diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeDimensionService.java b/src/main/java/net/dnorberg/rivencraft/book/AgeDimensionService.java index 38ce0c6..0c9095d 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeDimensionService.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeDimensionService.java @@ -60,6 +60,7 @@ public final class AgeDimensionService { DynamicDimensionLoadCallback.register((server, loader) -> { ServerLevel overworld = server.overworld(); for (AgeDefinition age : AgeRegistrySavedData.get(overworld).definitions()) { + if (!canLoadProfile(server, age)) continue; ServerLevel level = loader.loadDynamicDimension( age.dimensionId(), createGenerator(server, age), @@ -106,6 +107,8 @@ public final class AgeDimensionService { return existing; } + if (!canLoadProfile(server, definition)) return null; + ServerLevel overworld = server.overworld(); ServerLevel loaded = DynamicDimensionRegistry.from(server).loadDynamicDimension( definition.dimensionId(), @@ -154,6 +157,22 @@ public final class AgeDimensionService { } } + private static boolean canLoadProfile(MinecraftServer server, AgeDefinition age) { + try { + AgeRuntimeProfiles.validateReferences(server.registryAccess(), age.generationProfile(), runtimeProfile(age)); + return true; + } catch (IllegalArgumentException exception) { + Rivencraft.LOGGER.error("Cannot load Age {} ({}): {}. Restore its data pack; saved Age data is unchanged.", + age.id(), age.dimensionId(), exception.getMessage()); + return false; + } + } + + private static AgeRuntimeProfile runtimeProfile(AgeDefinition age) { + return age.plan() == null ? AgeRuntimeProfiles.resolve(age.generationProfile()) + : age.plan().runtimeProfile(); + } + private static void applyInitialCelestialPhase(ServerLevel level, AgeDefinition age) { long phaseTime = (long)(age.traits().celestialPhase() * Level.TICKS_PER_DAY); level.setDayTime(phaseTime); @@ -267,8 +286,7 @@ public final class AgeDimensionService { } private static ChunkGenerator createGenerator(MinecraftServer server, AgeDefinition age) { - AgeRuntimeProfile profile = age.plan() == null ? AgeRuntimeProfiles.resolve(age.generationProfile()) - : age.plan().runtimeProfile(); + AgeRuntimeProfile profile = runtimeProfile(age); if (profile.terrain() == AgeRuntimeProfile.Terrain.FLAT) { return new FlatLevelSource(FlatLevelGeneratorSettings.getDefault( server.registryAccess().lookupOrThrow(Registries.BIOME), @@ -392,12 +410,11 @@ public final class AgeDimensionService { } private static DimensionType createDimensionType(MinecraftServer server, AgeDefinition age) { - AgeRuntimeProfile profile = age.plan() == null ? AgeRuntimeProfiles.resolve(age.generationProfile()) - : age.plan().runtimeProfile(); + AgeRuntimeProfile profile = runtimeProfile(age); DimensionType base = server.registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE) .getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, profile.dimensionType())).value(); AgeTraits.Lighting lighting = age.traits().lighting(); - boolean hasSkyLight = lighting != AgeTraits.Lighting.DARK; + boolean hasSkyLight = base.hasSkyLight() && lighting != AgeTraits.Lighting.DARK; float ambientLight = lighting == AgeTraits.Lighting.BRIGHT ? 0.25F : 0.0F; return new DimensionType( base.fixedTime(), diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeRuntimeProfiles.java b/src/main/java/net/dnorberg/rivencraft/book/AgeRuntimeProfiles.java index d3a4612..3b9cbe6 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeRuntimeProfiles.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeRuntimeProfiles.java @@ -70,14 +70,19 @@ public final class AgeRuntimeProfiles { ResourceLocation noise = location(object, "noise_settings", "minecraft:overworld"); ResourceLocation biome = location(object, "biome_preset", "minecraft:overworld"); ResourceLocation dimension = location(object, "dimension_type", "minecraft:overworld"); + AgeRuntimeProfile profile = new AgeRuntimeProfile(schemaVersion, terrain, noise, biome, dimension); + validateReferences(registries, id, profile); + return profile; + } - if (terrain == AgeRuntimeProfile.Terrain.NOISE) { - requireRegistryEntry(registries, Registries.NOISE_SETTINGS, noise, id, "noise_settings"); + /** Recheck frozen plans before loading: a removed registry entry must not crash or silently alter an Age. */ + public static void validateReferences(RegistryAccess registries, ResourceLocation id, AgeRuntimeProfile profile) { + if (profile.terrain() == AgeRuntimeProfile.Terrain.NOISE) { + requireRegistryEntry(registries, Registries.NOISE_SETTINGS, profile.noiseSettings(), id, "noise_settings"); requireRegistryEntry(registries, Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST, - biome, id, "biome_preset"); + profile.biomePreset(), id, "biome_preset"); } - requireRegistryEntry(registries, Registries.DIMENSION_TYPE, dimension, id, "dimension_type"); - return new AgeRuntimeProfile(schemaVersion, terrain, noise, biome, dimension); + requireRegistryEntry(registries, Registries.DIMENSION_TYPE, profile.dimensionType(), id, "dimension_type"); } private static String requiredString(JsonObject object, String name) { diff --git a/src/main/java/net/dnorberg/rivencraft/book/TerrainWritingGameTests.java b/src/main/java/net/dnorberg/rivencraft/book/TerrainWritingGameTests.java new file mode 100644 index 0000000..3fac049 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/book/TerrainWritingGameTests.java @@ -0,0 +1,175 @@ +package net.dnorberg.rivencraft.book; + +import com.google.gson.JsonParser; +import java.util.List; +import java.util.UUID; +import net.dnorberg.rivencraft.writing.OrderedWriting; +import net.dnorberg.rivencraft.writing.SymbolCatalog; +import net.dnorberg.rivencraft.writing.SymbolReference; +import net.dnorberg.rivencraft.writing.SymbolSemantics; +import net.dnorberg.rivencraft.writing.WritingEntry; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.Registries; +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestHelper; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.levelgen.FlatLevelSource; +import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; +import net.neoforged.neoforge.gametest.GameTestHolder; +import net.neoforged.neoforge.gametest.PrefixGameTestTemplate; + +/** Issue #32: authored terrain must drive actual runtime generation and survive reload. */ +@GameTestHolder("rivencraft_archive_linking") +@PrefixGameTestTemplate(false) +public final class TerrainWritingGameTests { + private TerrainWritingGameTests() {} + + @GameTest(template = "empty", timeoutTicks = 600) + public static void writtenTerrainFamiliesGenerateSafelyAndReload(GameTestHelper helper) { + var player = helper.makeMockServerPlayerInLevel(); + checkWrittenTerrain(helper, player, AgeGenerationProfiles.all(), 0); + } + + private static void checkWrittenTerrain(GameTestHelper helper, + net.minecraft.server.level.ServerPlayer player, + List profiles, int index) { + if (index >= profiles.size()) { + helper.succeed(); + return; + } + var server = helper.getLevel().getServer(); + ResourceLocation profileId = profiles.get(index); + SymbolReference symbol = new SymbolReference(ResourceLocation.fromNamespaceAndPath( + "rivencraft", "terrain/" + profileId.getPath())); + var semantics = SymbolCatalog.find(symbol).orElseThrow().semantics().orElseThrow(); + helper.assertValueEqual(semantics.role(), SymbolSemantics.Role.TERRAIN, + "A built-in terrain page must have terrain semantics"); + helper.assertValueEqual(((SymbolSemantics.ResourceValue) semantics.value()).id(), profileId, + "A terrain page must point at its matching profile"); + + OrderedWriting writing = new OrderedWriting(List.of( + WritingEntry.linkPanel(), WritingEntry.symbol(symbol))); + AgeReference reference = new AgeReference(UUID.randomUUID(), + "Written " + profileId.getPath() + " " + UUID.randomUUID()); + var target = AgeDimensionService.resolve(player, reference, writing).orElseThrow(); + AgeDefinition age = AgeRegistrySavedData.get(helper.getLevel()).find(reference.id()).orElseThrow(); + helper.assertValueEqual(age.generationProfile(), profileId, + "Written terrain must override the random profile chosen from the seed"); + helper.assertValueEqual(age.plan().runtimeProfile(), AgeRuntimeProfiles.profiles().get(profileId), + "The selected noise and dimension-type resources must be frozen in the plan"); + helper.runAfterDelay(1, () -> { + var level = server.getLevel(target.location().dimension()); + helper.assertTrue(level != null, "The written Age must create a runtime dimension"); + assertGenerator(helper, level, age.plan().runtimeProfile()); + BlockPos spawn = target.location().pos(); + helper.assertTrue(level.getBlockState(spawn.below()).is(Blocks.COBBLESTONE) + && level.getBlockState(spawn).isAir() + && level.getBlockState(spawn.above()).isAir(), + "Every written terrain family must retain a safe arrival platform"); + + helper.assertValueEqual(AgeDimensionService.unload(server, age), + AgeDimensionService.UnloadResult.UNLOADED, + "A written Age must unload without losing its plan"); + var reloaded = AgeDimensionService.ensureLoaded(server, age); + helper.assertTrue(reloaded != null, "The written Age must reload from its frozen plan"); + assertGenerator(helper, reloaded, age.plan().runtimeProfile()); + helper.assertValueEqual(reloaded.dimensionType().effectsLocation(), + level.dimensionType().effectsLocation(), "Reload must retain dimension effects"); + helper.runAfterDelay(1, () -> checkWrittenTerrain(helper, player, profiles, index + 1)); + }); + } + + @GameTest(template = "empty") + public static void missingRegistryResourcesRejectProfileAndPreserveAge(GameTestHelper helper) { + ResourceLocation missing = ResourceLocation.parse("rivencraft:missing_noise"); + var json = JsonParser.parseString(""" + {"schema_version":1,"terrain":"noise","noise_settings":"rivencraft:missing_noise", + "biome_preset":"minecraft:overworld","dimension_type":"minecraft:overworld"} + """); + boolean rejected = false; + try { + AgeRuntimeProfiles.parse(missing, json, helper.getLevel().registryAccess()); + } catch (IllegalArgumentException exception) { + rejected = exception.getMessage().contains("noise_settings") + && exception.getMessage().contains(missing.toString()); + } + helper.assertTrue(rejected, "A profile with missing noise settings needs an actionable rejection"); + + long seed = 42L; + OrderedWriting writing = new OrderedWriting(List.of(WritingEntry.linkPanel(), + WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:terrain/standard"))))); + AgeRuntimeProfile broken = new AgeRuntimeProfile(1, AgeRuntimeProfile.Terrain.NOISE, + missing, ResourceLocation.parse("minecraft:overworld"), + ResourceLocation.parse("minecraft:overworld")); + AgeGenerationPlan plan = new AgeGenerationPlan(1, seed, writing, + List.of(new AgeGenerationPlan.ResolvedSymbol(1, + writing.entries().get(1).symbol().orElseThrow(), + new SymbolSemantics(SymbolSemantics.Role.TERRAIN, + new SymbolSemantics.ResourceValue(AgeGenerationProfiles.STANDARD)))), broken); + AgeDefinition age = new AgeDefinition(UUID.randomUUID(), "Missing Resource", seed, + AgeGenerationProfiles.STANDARD, AgeDefinition.CURRENT_GENERATION_VERSION, + helper.getLevel().getGameTime(), + ResourceLocation.parse("rivencraft:gametest/missing_resource_" + UUID.randomUUID()), + null, AgeTraits.select(seed), plan); + helper.assertTrue(AgeDimensionService.ensureLoaded(helper.getLevel().getServer(), age) == null, + "A removed resource must not silently turn an authored Age into a different terrain"); + helper.assertValueEqual(age.plan(), plan, "Failed loading must not mutate the saved plan"); + helper.succeed(); + } + + @GameTest(template = "empty") + public static void dimensionTypeSnapshotKeepsNetherSkylightRules(GameTestHelper helper) { + var profile = AgeRuntimeProfiles.parse(ResourceLocation.parse("rivencraft:gametest_nether"), + JsonParser.parseString(""" + {"schema_version":1,"terrain":"noise","noise_settings":"minecraft:nether", + "biome_preset":"minecraft:nether","dimension_type":"minecraft:the_nether"} + """), helper.getLevel().registryAccess()); + long seed = 99L; + OrderedWriting writing = new OrderedWriting(List.of(WritingEntry.linkPanel(), + WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:feature/caves"))))); + var parsed = net.dnorberg.rivencraft.writing.WritingGrammar.parse(writing); + AgeGenerationPlan plan = new AgeGenerationPlan(1, seed, writing, + parsed.symbols().stream().map(symbol -> new AgeGenerationPlan.ResolvedSymbol( + symbol.index(), symbol.reference(), symbol.semantics())).toList(), profile); + AgeDefinition age = new AgeDefinition(UUID.randomUUID(), "Nether Type Snapshot", seed, + ResourceLocation.parse("rivencraft:gametest_nether"), AgeDefinition.CURRENT_GENERATION_VERSION, + helper.getLevel().getGameTime(), + ResourceLocation.parse("rivencraft:gametest/nether_type_" + UUID.randomUUID()), + null, AgeTraits.LEGACY_DEFAULTS, plan); + var level = AgeDimensionService.ensureLoaded(helper.getLevel().getServer(), age); + helper.assertTrue(level != null, "A valid custom dimension-type snapshot must load"); + helper.assertFalse(level.dimensionType().hasSkyLight(), + "Normal lighting must not add skylight to a Nether-style dimension type"); + helper.assertValueEqual(level.dimensionType().effectsLocation(), BuiltinDimensionTypes.NETHER_EFFECTS, + "The authored profile's dimension effects must reach the runtime Age"); + helper.succeed(); + } + + private static void assertGenerator(GameTestHelper helper, net.minecraft.server.level.ServerLevel level, + AgeRuntimeProfile profile) { + var generator = level.getChunkSource().getGenerator(); + if (profile.terrain() == AgeRuntimeProfile.Terrain.NOISE) { + helper.assertTrue(generator instanceof NoiseBasedChunkGenerator, + "Noise terrain must use a noise-based chunk generator"); + var expected = level.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow( + ResourceKey.create(Registries.NOISE_SETTINGS, profile.noiseSettings())).value(); + helper.assertValueEqual(((NoiseBasedChunkGenerator) generator).generatorSettings().value().noiseSettings(), + expected.noiseSettings(), "Written noise settings must be applied to the generator"); + } else { + helper.assertTrue(generator instanceof FlatLevelSource, + "Flat and Void terrain must use a flat-source generator"); + if (profile.terrain() == AgeRuntimeProfile.Terrain.VOID) { + helper.assertTrue(generator.getBiomeSource().possibleBiomes().stream() + .allMatch(biome -> biome.is(net.minecraft.world.level.biome.Biomes.THE_VOID)), + "Void terrain must use the Void biome"); + } + } + var expectedType = level.registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow( + ResourceKey.create(Registries.DIMENSION_TYPE, profile.dimensionType())).value(); + helper.assertValueEqual(level.dimensionType().effectsLocation(), expectedType.effectsLocation(), + "The profile's dimension-type effects must be applied"); + } +} diff --git a/src/main/java/net/dnorberg/rivencraft/gametest/WritingDataGameTests.java b/src/main/java/net/dnorberg/rivencraft/gametest/WritingDataGameTests.java index d8c176f..1d82c18 100644 --- a/src/main/java/net/dnorberg/rivencraft/gametest/WritingDataGameTests.java +++ b/src/main/java/net/dnorberg/rivencraft/gametest/WritingDataGameTests.java @@ -106,6 +106,22 @@ public final class WritingDataGameTests { helper.succeed(); } + @GameTest(template = "empty") + public static void creativePagesIncludeEveryBuiltInTerrain(GameTestHelper helper) { + for (String terrain : List.of("standard", "amplified", "cave", "island", "flat", "void")) { + String path = "terrain/" + terrain; + helper.assertTrue(PageItem.bundledCreativeSymbols().contains(path), + "The Pages creative tab must include " + path); + ItemStack page = PageItem.createBundledCreativePage(path); + helper.assertValueEqual(PageItem.content(page).symbol().orElseThrow().id(), + ResourceLocation.fromNamespaceAndPath("rivencraft", path), + "The creative starter page must contain the matching terrain symbol"); + helper.assertTrue(page.get(ModDataComponents.PAGE_SYMBOL_DISPLAY.get()).resolved(), + "The creative starter page must have display metadata before catalog reload"); + } + helper.succeed(); + } + @GameTest(template = "empty") public static void semanticSchemaIsServerOnlyBoundedAndV1Compatible(GameTestHelper helper) { var builtIn = SymbolCatalog.find(reference("rivencraft:terrain/standard")).orElseThrow(); diff --git a/src/main/java/net/dnorberg/rivencraft/item/PageItem.java b/src/main/java/net/dnorberg/rivencraft/item/PageItem.java index bfb8579..9622c69 100644 --- a/src/main/java/net/dnorberg/rivencraft/item/PageItem.java +++ b/src/main/java/net/dnorberg/rivencraft/item/PageItem.java @@ -1,14 +1,20 @@ package net.dnorberg.rivencraft.item; +import com.google.gson.JsonParser; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import net.dnorberg.rivencraft.Rivencraft; import net.dnorberg.rivencraft.registry.ModDataComponents; import net.dnorberg.rivencraft.registry.ModItems; import net.dnorberg.rivencraft.writing.PageContent; import net.dnorberg.rivencraft.writing.SymbolCatalog; +import net.dnorberg.rivencraft.writing.SymbolDefinition; import net.dnorberg.rivencraft.writing.SymbolDisplayMetadata; import net.dnorberg.rivencraft.writing.SymbolReference; -import net.dnorberg.rivencraft.writing.SymbolPoems; import net.minecraft.ChatFormatting; import net.minecraft.core.component.DataComponents; import net.minecraft.network.chat.Component; @@ -18,6 +24,8 @@ import net.minecraft.world.item.TooltipFlag; /** One stackable Page item whose server-owned component identifies its writing state. */ public final class PageItem extends Item { + private static final Map CREATIVE_SYMBOLS = loadCreativeSymbols(); + public PageItem(Properties properties) { super(properties); } @@ -29,23 +37,44 @@ public final class PageItem extends Item { return create(PageContent.symbol(reference)); } - /** Fixed starter examples for the creative tab; the server still validates catalog membership on use. */ - public static ItemStack createCreativeStarterPage(String path) { - if (!List.of("terrain/standard", "biome/native", "lighting/normal", "weather/normal", - "celestial/normal_time", "feature/caves").contains(path)) { - throw new IllegalArgumentException("Not a starter symbol: " + path); + public static List bundledCreativeSymbols() { + return List.copyOf(CREATIVE_SYMBOLS.keySet()); + } + + /** Bundled symbols for the creative tab; the server still validates catalog membership on use. */ + public static ItemStack createBundledCreativePage(String path) { + SymbolDisplayMetadata metadata = CREATIVE_SYMBOLS.get(path); + if (metadata == null) { + throw new IllegalArgumentException("Not a bundled symbol: " + path); } - SymbolReference reference = new SymbolReference( - net.minecraft.resources.ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path)); + SymbolReference reference = new SymbolReference(metadata.id()); ItemStack page = create(PageContent.symbol(reference)); - String key = "symbol.rivencraft." + path.replace('/', '.'); - page.set(ModDataComponents.PAGE_SYMBOL_DISPLAY.get(), new SymbolDisplayMetadata( - reference.id(), key, key + ".description", - net.minecraft.resources.ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path.split("/")[0]), - true, SymbolPoems.builtIn(reference.id()))); + page.set(ModDataComponents.PAGE_SYMBOL_DISPLAY.get(), metadata); return page; } + private static Map loadCreativeSymbols() { + String resource = "/assets/rivencraft/creative_symbol_pages.json"; + try (var stream = PageItem.class.getResourceAsStream(resource)) { + if (stream == null) { + throw new IllegalStateException("Missing generated creative symbol index " + resource); + } + var json = JsonParser.parseReader(new InputStreamReader(stream, StandardCharsets.UTF_8)) + .getAsJsonObject(); + Map symbols = new LinkedHashMap<>(); + json.entrySet().forEach(entry -> { + var id = net.minecraft.resources.ResourceLocation.parse(entry.getKey()); + if (!id.getNamespace().equals(Rivencraft.MOD_ID)) { + throw new IllegalStateException("Creative symbol is not a Rivencraft page: " + id); + } + symbols.put(id.getPath(), SymbolDefinition.parse(entry.getValue()).display(id)); + }); + return Collections.unmodifiableMap(symbols); + } catch (java.io.IOException exception) { + throw new IllegalStateException("Could not read generated creative symbol index " + resource, exception); + } + } + public static ItemStack createLinkPanelPage() { return create(PageContent.LINK_PANEL); } diff --git a/src/main/java/net/dnorberg/rivencraft/registry/ModCreativeTabs.java b/src/main/java/net/dnorberg/rivencraft/registry/ModCreativeTabs.java index 276fab8..b8e221f 100644 --- a/src/main/java/net/dnorberg/rivencraft/registry/ModCreativeTabs.java +++ b/src/main/java/net/dnorberg/rivencraft/registry/ModCreativeTabs.java @@ -35,9 +35,8 @@ public final class ModCreativeTabs { .displayItems((parameters, output) -> { output.accept(ModItems.PAGE.get()); output.accept(PageItem.createLinkPanelPage()); - for (String id : new String[] {"terrain/standard", "biome/native", "lighting/normal", - "weather/normal", "celestial/normal_time", "feature/caves"}) { - output.accept(PageItem.createCreativeStarterPage(id)); + for (String id : PageItem.bundledCreativeSymbols()) { + output.accept(PageItem.createBundledCreativePage(id)); } }) .build()); diff --git a/src/main/java/net/dnorberg/rivencraft/writing/SymbolPoems.java b/src/main/java/net/dnorberg/rivencraft/writing/SymbolPoems.java index b61f566..fba49b5 100644 --- a/src/main/java/net/dnorberg/rivencraft/writing/SymbolPoems.java +++ b/src/main/java/net/dnorberg/rivencraft/writing/SymbolPoems.java @@ -10,6 +10,11 @@ public final class SymbolPoems { if (!id.getNamespace().equals("rivencraft")) return ""; return switch (id.getPath()) { case "terrain/standard" -> "Terrain Form Tradition Flow"; + case "terrain/amplified" -> "Terrain Form Tradition Spur"; + case "terrain/cave" -> "Terrain Transform Void Flow"; + case "terrain/island" -> "Terrain Transform Form Celestial"; + case "terrain/flat" -> "Terrain Form Inhibit Motion"; + case "terrain/void" -> "Terrain Form Infinite Void"; case "biome/native" -> "Constraint Nature Tradition Sustain"; case "lighting/normal" -> "Ethereal Dynamic Cycle Balance"; case "weather/normal" -> "Sustain Dynamic Tradition Balance"; diff --git a/src/main/resources/assets/rivencraft/lang/en_us.json b/src/main/resources/assets/rivencraft/lang/en_us.json index 2419d1f..544f0d0 100644 --- a/src/main/resources/assets/rivencraft/lang/en_us.json +++ b/src/main/resources/assets/rivencraft/lang/en_us.json @@ -120,6 +120,16 @@ "symbol.rivencraft.unresolved.description": "Missing symbol: %s", "symbol.rivencraft.terrain.standard": "Standard Terrain", "symbol.rivencraft.terrain.standard.description": "A familiar continental terrain foundation.", + "symbol.rivencraft.terrain.amplified": "Amplified Terrain", + "symbol.rivencraft.terrain.amplified.description": "Tall, sharply varied Overworld terrain.", + "symbol.rivencraft.terrain.cave": "Cave Terrain", + "symbol.rivencraft.terrain.cave.description": "An enclosed cave-shaped world with a sheltered arrival.", + "symbol.rivencraft.terrain.island": "Island Terrain", + "symbol.rivencraft.terrain.island.description": "Floating-island terrain above the void.", + "symbol.rivencraft.terrain.flat": "Flat Terrain", + "symbol.rivencraft.terrain.flat.description": "A level Overworld-style landscape.", + "symbol.rivencraft.terrain.void": "Void Terrain", + "symbol.rivencraft.terrain.void.description": "An empty world with a safe arrival platform.", "symbol.rivencraft.biome.native": "Native Biomes", "symbol.rivencraft.biome.native.description": "Use the terrain profile's native biome climate.", "symbol.rivencraft.lighting.normal": "Normal Lighting", diff --git a/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/amplified.json b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/amplified.json new file mode 100644 index 0000000..130c5d7 --- /dev/null +++ b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/amplified.json @@ -0,0 +1,8 @@ +{ + "schema_version": 2, + "name": "symbol.rivencraft.terrain.amplified", + "description": "symbol.rivencraft.terrain.amplified.description", + "category": "rivencraft:terrain", + "semantics": { "role": "terrain", "value": "rivencraft:amplified" }, + "poem": "Terrain Form Tradition Spur" +} diff --git a/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/cave.json b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/cave.json new file mode 100644 index 0000000..2b628e3 --- /dev/null +++ b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/cave.json @@ -0,0 +1,8 @@ +{ + "schema_version": 2, + "name": "symbol.rivencraft.terrain.cave", + "description": "symbol.rivencraft.terrain.cave.description", + "category": "rivencraft:terrain", + "semantics": { "role": "terrain", "value": "rivencraft:cave" }, + "poem": "Terrain Transform Void Flow" +} diff --git a/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/flat.json b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/flat.json new file mode 100644 index 0000000..599bf6a --- /dev/null +++ b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/flat.json @@ -0,0 +1,8 @@ +{ + "schema_version": 2, + "name": "symbol.rivencraft.terrain.flat", + "description": "symbol.rivencraft.terrain.flat.description", + "category": "rivencraft:terrain", + "semantics": { "role": "terrain", "value": "rivencraft:flat" }, + "poem": "Terrain Form Inhibit Motion" +} diff --git a/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/island.json b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/island.json new file mode 100644 index 0000000..9f37c1a --- /dev/null +++ b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/island.json @@ -0,0 +1,8 @@ +{ + "schema_version": 2, + "name": "symbol.rivencraft.terrain.island", + "description": "symbol.rivencraft.terrain.island.description", + "category": "rivencraft:terrain", + "semantics": { "role": "terrain", "value": "rivencraft:island" }, + "poem": "Terrain Transform Form Celestial" +} diff --git a/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/void.json b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/void.json new file mode 100644 index 0000000..a078cff --- /dev/null +++ b/src/main/resources/data/rivencraft/rivencraft/symbols/terrain/void.json @@ -0,0 +1,8 @@ +{ + "schema_version": 2, + "name": "symbol.rivencraft.terrain.void", + "description": "symbol.rivencraft.terrain.void.description", + "category": "rivencraft:terrain", + "semantics": { "role": "terrain", "value": "rivencraft:void" }, + "poem": "Terrain Form Infinite Void" +}