Public Access
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e28079566b | ||
|
|
28c2ca0db3 | ||
|
|
27abebe3aa |
No files matched your search
+5
-3
@@ -74,9 +74,11 @@ Or, with mise:
|
||||
All required GameTests should pass before distributing a build.
|
||||
|
||||
GameTests use `build/gametest-run/world`, separate from the normal development
|
||||
world. Before each run, Gradle removes that test world if it exceeds 512 MiB.
|
||||
Override the limit with `-PgameTestMaxWorldMiB=NUMBER`. A caller-supplied
|
||||
`-PgameTestRunDir` is never removed automatically.
|
||||
world. Gradle starts each default run with a fresh world and removes it after
|
||||
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:
|
||||
|
||||
|
||||
@@ -92,10 +92,14 @@ outputs a Descriptive Book once the title, cover, and Link Panel are present.
|
||||
Inputs are consumed only when the result is taken.
|
||||
|
||||
The completed book receives its Age identity when assembled. With only a Link
|
||||
Panel, it describes a randomly generated Age. Its writing is stored on the
|
||||
book; the Descriptive Book screen's turned pages show ordered symbols and
|
||||
unresolved IDs. Until Milestone 5, symbols do not affect generation and written
|
||||
books use the same random Age fallback. The Descriptive Book screen follows
|
||||
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. 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
|
||||
preview is on the right, and clicks in the bottom corners turn pages. Ordered
|
||||
symbol pages appear before the final blank spread; their pictograms await
|
||||
|
||||
+71
-32
@@ -17,7 +17,7 @@ tasks.named('wrapper', Wrapper).configure {
|
||||
version = mod_version
|
||||
group = mod_group_id
|
||||
|
||||
List<String> archivedGameTestSuites = ['linking', 'writing', 'desk', 'binder', 'mixer', 'recipe']
|
||||
List<String> archivedGameTestSuites = ['linking', 'writing', 'grammar', 'desk', 'binder', 'mixer', 'recipe']
|
||||
List<String> selectedArchivedGameTestSuites = providers.gradleProperty('withArchivedGameTests')
|
||||
.map { it.toBoolean() }.orElse(false).get() ? archivedGameTestSuites
|
||||
: providers.gradleProperty('archivedGameTestSuites').orElse('').get()
|
||||
@@ -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<String, Object>()
|
||||
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,42 +177,52 @@ neoForge {
|
||||
}
|
||||
}
|
||||
|
||||
// GameTests generate Ages, so their dedicated world can grow quickly across runs.
|
||||
// Never auto-delete a caller-supplied gameTestRunDir or a normal dev world.
|
||||
long gameTestWorldLimitMiB = providers.gradleProperty('gameTestMaxWorldMiB').orElse('512').get().toLong()
|
||||
if (gameTestWorldLimitMiB <= 0) {
|
||||
throw new GradleException('gameTestMaxWorldMiB must be a positive number')
|
||||
}
|
||||
// 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 dedicatedGameTestDir = layout.buildDirectory.dir('gametest-run').get().asFile.canonicalFile
|
||||
File dedicatedGameTestWorld = new File(dedicatedGameTestDir, 'world')
|
||||
def cleanOversizedGameTestWorld = tasks.register('cleanOversizedGameTestWorld') {
|
||||
File dedicatedGameTestBuildDir = layout.buildDirectory.get().asFile
|
||||
File dedicatedGameTestDir = layout.buildDirectory.dir('gametest-run').get().asFile
|
||||
def prepareGameTestWorld = tasks.register('prepareGameTestWorld') {
|
||||
onlyIf { !customGameTestRunDir }
|
||||
doLast {
|
||||
if (customGameTestRunDir) {
|
||||
getLogger().lifecycle('Skipping automatic GameTest world cleanup for custom gameTestRunDir')
|
||||
return
|
||||
}
|
||||
|
||||
def worldDir = dedicatedGameTestWorld
|
||||
if (!worldDir.isDirectory() || java.nio.file.Files.isSymbolicLink(worldDir.toPath())) {
|
||||
return
|
||||
}
|
||||
|
||||
def paths = java.nio.file.Files.walk(worldDir.toPath()).withCloseable { it.toList() }
|
||||
long bytes = paths.sum(0L) { path ->
|
||||
java.nio.file.Files.isRegularFile(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)
|
||||
? java.nio.file.Files.size(path) : 0L
|
||||
}
|
||||
long limit = gameTestWorldLimitMiB * 1024L * 1024L
|
||||
if (bytes > limit) {
|
||||
getLogger().lifecycle('Removing oversized GameTest world {} ({} MiB; limit {} MiB)',
|
||||
worldDir, Math.ceil(bytes / 1048576d) as long, gameTestWorldLimitMiB)
|
||||
paths.toSorted(java.util.Comparator.reverseOrder()).each { java.nio.file.Files.delete(it) }
|
||||
}
|
||||
GameTestWorlds.clean(dedicatedGameTestBuildDir, dedicatedGameTestDir)
|
||||
}
|
||||
}
|
||||
def finishGameTestWorld = tasks.register('finishGameTestWorld') {
|
||||
onlyIf { !customGameTestRunDir }
|
||||
doLast {
|
||||
GameTestWorlds.clean(dedicatedGameTestBuildDir, dedicatedGameTestDir)
|
||||
}
|
||||
}
|
||||
tasks.named('runGameTestServer').configure {
|
||||
dependsOn(cleanOversizedGameTestWorld)
|
||||
dependsOn(prepareGameTestWorld)
|
||||
finalizedBy(finishGameTestWorld)
|
||||
}
|
||||
|
||||
class GameTestWorlds {
|
||||
static void check(File buildDir, File runDir) {
|
||||
[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 void clean(File buildDir, File runDir) {
|
||||
check(buildDir, runDir)
|
||||
[new File(runDir, 'world'), new File(runDir, 'failed-worlds')].each { root ->
|
||||
if (root.exists()) {
|
||||
java.nio.file.Files.walk(root.toPath()).withCloseable { paths ->
|
||||
paths.sorted(java.util.Comparator.reverseOrder()).forEach { path ->
|
||||
java.nio.file.Files.delete(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
java.nio.file.Files.deleteIfExists(new File(runDir, 'failed-seed.txt').toPath())
|
||||
java.nio.file.Files.deleteIfExists(new File(runDir, '.last-gametest-succeeded').toPath())
|
||||
}
|
||||
}
|
||||
|
||||
// Sets up a dependency configuration called 'localRuntime'.
|
||||
|
||||
+25
-5
@@ -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/<name>` 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
|
||||
|
||||
+14
-12
@@ -1,15 +1,15 @@
|
||||
# GameTest suites
|
||||
|
||||
The default dedicated-server run is a small smoke suite: 17 Rivencraft tests
|
||||
The default dedicated-server run is a small smoke suite: 19 Rivencraft tests
|
||||
cover core linking, deterministic Age definition, writing persistence, legacy
|
||||
data migration, workstation transactions, and forged/replayed menu actions.
|
||||
NeoForge currently adds two of its own tests, so the runner reports 19.
|
||||
NeoForge currently adds two of its own tests, so the runner reports 21.
|
||||
|
||||
```shell
|
||||
./gradlew runGameTestServer
|
||||
```
|
||||
|
||||
The remaining 47 Rivencraft tests are archived, not deleted. They cover
|
||||
The remaining 49 Rivencraft tests are archived, not deleted. They cover
|
||||
completed milestone details such as every Age terrain profile, Notebook and
|
||||
Desk surface interactions, refill edge cases, book assembly controls, and
|
||||
workstation break/drop behavior. Run only the relevant archive alongside the
|
||||
@@ -17,11 +17,11 @@ core tests when investigating an issue:
|
||||
|
||||
```shell
|
||||
./gradlew runGameTestServer -ParchivedGameTestSuites=desk
|
||||
./gradlew runGameTestServer -ParchivedGameTestSuites=linking,binder
|
||||
./gradlew runGameTestServer -ParchivedGameTestSuites=grammar,binder
|
||||
```
|
||||
|
||||
Available suite names are `linking`, `writing`, `desk`, `binder`, `mixer`, and
|
||||
`recipe`. Run all 64 Rivencraft tests (66 including NeoForge's two) before a
|
||||
Available suite names are `linking`, `writing`, `grammar`, `desk`, `binder`, `mixer`, and
|
||||
`recipe`. Run all 68 Rivencraft tests (70 including NeoForge's two) before a
|
||||
release or after broad cross-system changes:
|
||||
|
||||
```shell
|
||||
@@ -34,9 +34,11 @@ 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. The Gradle task removes that **dedicated** world automatically if
|
||||
it exceeds 512 MiB; override the threshold with `-PgameTestMaxWorldMiB=128`,
|
||||
for example. Cleanup never targets a custom `-PgameTestRunDir` or a player
|
||||
world. A fresh test world can also help diagnose a slow or stalled worldgen
|
||||
run. The full suite should still be run before shipping changes in the
|
||||
archived systems.
|
||||
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
|
||||
before shipping changes in the archived systems.
|
||||
@@ -39,6 +39,6 @@ These are schema bounds, not claims that Legacy shipped numeric config ranges. S
|
||||
|
||||
The server rejects a v2 definition with an unknown top-level or semantics field, missing/incorrectly typed field, unknown role or choice, malformed/non-canonical resource ID, or out-of-range/non-finite number. An invalid definition is logged with its file ID and excluded from the active catalog. Saved pages and books still retain that ID, allowing the player to recover them if the data pack is corrected. A reload atomically replaces the catalog rather than mutating saved writing.
|
||||
|
||||
Schema v1 definitions remain readable as **display-only** symbols; existing packs need not be rewritten merely to show or copy pages. A v1 definition cannot add a `semantics` field. To make one eligible for future Age compilation, publish a v2 definition with the **same file path and ID**, adding a valid role and value. Do not rename the page ID or reorder a book's `OrderedWriting`. The client receives only `SymbolDisplayMetadata` (ID, translation keys, category, resolved flag); semantic definitions are not serialized to it. This slice defines and validates meaning but does **not yet apply** written symbols to Age generation; issues #30 and #31 implement parsing and compilation.
|
||||
Schema v1 definitions remain readable as **display-only** symbols; existing packs need not be rewritten merely to show or copy pages. A v1 definition cannot add a `semantics` field. To make one eligible for Age grammar parsing, publish a v2 definition with the **same file path and ID**, adding a valid role and value. Do not rename the page ID or reorder a book's `OrderedWriting`. The client receives only `SymbolDisplayMetadata` (ID, translation keys, category, resolved flag); semantic definitions are not serialized to it. The [ordered-writing parser](WRITING_GRAMMAR.md) validates new books, but does **not yet apply** written symbols to Age generation; issue #31 adds compilation.
|
||||
|
||||
The six built-in definitions demonstrate terrain, biome-controller, lighting, weather, celestial, and feature roles. A third-party pack may add its own definitions under its namespace. Use an explicit semantic role even when the display category has the same name; the two fields serve different purposes.
|
||||
@@ -0,0 +1,13 @@
|
||||
# Ordered Descriptive Book grammar (Milestone 5, issue #30)
|
||||
|
||||
`WritingGrammar` interprets the saved `OrderedWriting` on the server using only `SymbolCatalog`'s schema-v2 semantics. Client display metadata, page names, and supplied translations never determine an Age's meaning. The parser is pure: it returns immutable parsed entries and indexed diagnostics without changing a book or its pages.
|
||||
|
||||
New Binder writing has at most one Link Panel plus 27 symbol pages. The Link Panel must be first. A Link-Panel-only book, or an older book with no writing component, keeps the existing random Age path. Any authored supported symbol makes the book a partial or complete grammar. From 0.4.3.0, the server compiles it into a persistent Age plan before consuming Binder inputs or generating chunks.
|
||||
|
||||
The supported order follows the representable subset of the [Legacy grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md): terrain; zero or more biome pages; biome controller; weather; lighting; zero or more period, angle, or phase modifiers; one celestial page; then zero or more distinct features. Biome pages precede the controller that consumes them, and celestial modifiers precede the celestial page. Terrain, controller, weather, lighting, and celestial are single-choice categories; identical repeats are duplicates and differing values conflict. Repeated modifiers are intentional. Biome pages may repeat, preserving author order and any future weighting; feature IDs may not repeat.
|
||||
|
||||
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. 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.
|
||||
+1
-1
@@ -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.1.5
|
||||
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.
|
||||
|
||||
@@ -5,6 +5,9 @@ import java.util.List;
|
||||
import java.util.UUID;
|
||||
import net.dnorberg.rivencraft.book.AgeReference;
|
||||
import net.dnorberg.rivencraft.book.AgeRegistrySavedData;
|
||||
import net.dnorberg.rivencraft.book.AgeGenerationPlan;
|
||||
import net.dnorberg.rivencraft.book.AgeGenerationProfiles;
|
||||
import net.dnorberg.rivencraft.book.AgeRuntimeProfiles;
|
||||
import net.dnorberg.rivencraft.item.PageItem;
|
||||
import net.dnorberg.rivencraft.registry.ModBlockEntities;
|
||||
import net.dnorberg.rivencraft.registry.ModDataComponents;
|
||||
@@ -12,7 +15,9 @@ import net.dnorberg.rivencraft.registry.ModItems;
|
||||
import net.dnorberg.rivencraft.writing.NotebookContents;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.dnorberg.rivencraft.writing.PageContent;
|
||||
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||
import net.dnorberg.rivencraft.writing.SymbolSemantics;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.NonNullList;
|
||||
@@ -108,7 +113,58 @@ public final class BookBinderBlockEntity extends BlockEntity implements Containe
|
||||
if (!page.isEmpty() && (!validPage(page) || !PageItem.isUsableWriting(page) || page.getCount() != 1
|
||||
|| PageItem.content(page).kind() == PageContent.Kind.BLANK)) return false;
|
||||
}
|
||||
return true;
|
||||
OrderedWriting writing = currentWriting();
|
||||
if (!writingGrammar().canCreate()) return false;
|
||||
try {
|
||||
AgeGenerationPlan.compile(writing, 0L, AgeGenerationProfiles.STANDARD);
|
||||
return true;
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public WritingGrammar.Result writingGrammar() {
|
||||
WritingGrammar.Result parsed = WritingGrammar.parse(currentWriting());
|
||||
if (!parsed.canCreate()) return parsed;
|
||||
var terrain = parsed.symbols().stream()
|
||||
.filter(symbol -> symbol.semantics().role() == SymbolSemantics.Role.TERRAIN)
|
||||
.findFirst();
|
||||
if (terrain.isEmpty()) return parsed;
|
||||
var profile = ((SymbolSemantics.ResourceValue) terrain.orElseThrow().semantics().value()).id();
|
||||
if (AgeRuntimeProfiles.profiles().containsKey(profile)) return parsed;
|
||||
List<WritingGrammar.Diagnostic> diagnostics = new ArrayList<>(parsed.diagnostics());
|
||||
diagnostics.add(new WritingGrammar.Diagnostic(WritingGrammar.Code.UNSUPPORTED_PROFILE,
|
||||
terrain.orElseThrow().index(), "Restore the Age profile " + profile + " or remove this page"));
|
||||
return new WritingGrammar.Result(parsed.symbols(), diagnostics);
|
||||
}
|
||||
|
||||
/** Map the parser's compact entry index back to the visible strip, including empty page positions. */
|
||||
public int writingStripIndex(int grammarIndex) {
|
||||
if (grammarIndex < 0) return -1;
|
||||
int entryIndex = 0;
|
||||
if (canPlaceItem(LINK_PANEL, items.get(LINK_PANEL))) {
|
||||
if (grammarIndex == 0) return 0;
|
||||
entryIndex++;
|
||||
}
|
||||
for (int slot = FIRST_PAGE; slot < SIZE; slot++) {
|
||||
ItemStack page = items.get(slot);
|
||||
if (!page.isEmpty() && PageItem.content(page).symbol().isPresent()) {
|
||||
if (entryIndex == grammarIndex) return slot - FIRST_PAGE + 1;
|
||||
entryIndex++;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private OrderedWriting currentWriting() {
|
||||
List<WritingEntry> entries = new ArrayList<>();
|
||||
if (canPlaceItem(LINK_PANEL, items.get(LINK_PANEL))) entries.add(WritingEntry.linkPanel());
|
||||
for (int slot = FIRST_PAGE; slot < SIZE; slot++) {
|
||||
ItemStack page = items.get(slot);
|
||||
if (!page.isEmpty()) PageItem.content(page).symbol().ifPresent(reference ->
|
||||
entries.add(WritingEntry.symbol(reference)));
|
||||
}
|
||||
return new OrderedWriting(entries);
|
||||
}
|
||||
|
||||
public ItemStack previewBook() {
|
||||
@@ -117,15 +173,9 @@ public final class BookBinderBlockEntity extends BlockEntity implements Containe
|
||||
pendingAgeId = UUID.randomUUID();
|
||||
setChanged();
|
||||
}
|
||||
List<WritingEntry> entries = new ArrayList<>();
|
||||
entries.add(WritingEntry.linkPanel());
|
||||
for (int slot = FIRST_PAGE; slot < SIZE; slot++) {
|
||||
ItemStack page = items.get(slot);
|
||||
if (!page.isEmpty()) entries.add(WritingEntry.symbol(PageItem.content(page).symbol().orElseThrow()));
|
||||
}
|
||||
ItemStack book = new ItemStack(ModItems.DESCRIPTIVE_BOOK.get());
|
||||
book.set(ModDataComponents.AGE_REFERENCE.get(), new AgeReference(pendingAgeId, title));
|
||||
book.set(ModDataComponents.BOOK_WRITING.get(), new OrderedWriting(entries));
|
||||
book.set(ModDataComponents.BOOK_WRITING.get(), currentWriting());
|
||||
book.set(DataComponents.CUSTOM_NAME, Component.literal(title));
|
||||
return book;
|
||||
}
|
||||
@@ -135,7 +185,7 @@ public final class BookBinderBlockEntity extends BlockEntity implements Containe
|
||||
if (!canAssemble()) return false;
|
||||
if (pendingAgeId == null) pendingAgeId = UUID.randomUUID();
|
||||
if (level instanceof ServerLevel serverLevel)
|
||||
AgeRegistrySavedData.resolveOrCreate(serverLevel, new AgeReference(pendingAgeId, title));
|
||||
AgeRegistrySavedData.resolveOrCreate(serverLevel, new AgeReference(pendingAgeId, title), currentWriting());
|
||||
items.get(COVER).shrink(1);
|
||||
if (items.get(COVER).isEmpty()) items.set(COVER, ItemStack.EMPTY);
|
||||
items.get(LINK_PANEL).shrink(1);
|
||||
|
||||
@@ -16,12 +16,13 @@ public record AgeDefinition(
|
||||
long createdGameTime,
|
||||
ResourceLocation dimensionId,
|
||||
BlockPos spawn,
|
||||
AgeTraits traits
|
||||
AgeTraits traits,
|
||||
AgeGenerationPlan plan
|
||||
) {
|
||||
public static final ResourceLocation RANDOM_VANILLA_PROFILE = ResourceLocation.fromNamespaceAndPath(
|
||||
Rivencraft.MOD_ID, "random_vanilla"
|
||||
);
|
||||
public static final int CURRENT_GENERATION_VERSION = 13;
|
||||
public static final int CURRENT_GENERATION_VERSION = 15;
|
||||
|
||||
public AgeDefinition {
|
||||
Objects.requireNonNull(id, "id");
|
||||
@@ -29,6 +30,16 @@ public record AgeDefinition(
|
||||
Objects.requireNonNull(generationProfile, "generationProfile");
|
||||
Objects.requireNonNull(dimensionId, "dimensionId");
|
||||
Objects.requireNonNull(traits, "traits");
|
||||
if (plan != null && plan.ageSeed() != seed) {
|
||||
throw new IllegalArgumentException("Age plan seed does not match its Age definition");
|
||||
}
|
||||
}
|
||||
|
||||
public AgeDefinition(UUID id, String name, long seed, ResourceLocation generationProfile,
|
||||
int generationVersion, long createdGameTime, ResourceLocation dimensionId,
|
||||
BlockPos spawn, AgeTraits traits) {
|
||||
this(id, name, seed, generationProfile, generationVersion, createdGameTime,
|
||||
dimensionId, spawn, traits, null);
|
||||
}
|
||||
|
||||
public static ResourceLocation dimensionId(UUID ageId) {
|
||||
@@ -59,6 +70,6 @@ public record AgeDefinition(
|
||||
|
||||
public AgeDefinition withSpawn(BlockPos spawn) {
|
||||
return new AgeDefinition(id, name, seed, generationProfile, generationVersion,
|
||||
createdGameTime, dimensionId, spawn.immutable(), traits);
|
||||
createdGameTime, dimensionId, spawn.immutable(), traits, plan);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import java.util.Comparator;
|
||||
import java.util.Collections;
|
||||
import net.dnorberg.rivencraft.Rivencraft;
|
||||
import net.dnorberg.rivencraft.compat.ImmersivePortalsChunkLoaders;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
import net.minecraft.core.Holder;
|
||||
@@ -59,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),
|
||||
@@ -73,7 +75,12 @@ public final class AgeDimensionService {
|
||||
}
|
||||
|
||||
public static Optional<LinkTarget> resolve(ServerPlayer player, AgeReference reference) {
|
||||
AgeDefinition definition = AgeRegistrySavedData.resolveOrCreate(player.serverLevel(), reference);
|
||||
return resolve(player, reference, OrderedWriting.EMPTY);
|
||||
}
|
||||
|
||||
public static Optional<LinkTarget> resolve(ServerPlayer player, AgeReference reference,
|
||||
OrderedWriting writing) {
|
||||
AgeDefinition definition = AgeRegistrySavedData.resolveOrCreate(player.serverLevel(), reference, writing);
|
||||
ServerLevel level = ensureLoaded(player.getServer(), definition);
|
||||
if (level == null) {
|
||||
return Optional.empty();
|
||||
@@ -100,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(),
|
||||
@@ -148,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);
|
||||
@@ -261,7 +286,7 @@ public final class AgeDimensionService {
|
||||
}
|
||||
|
||||
private static ChunkGenerator createGenerator(MinecraftServer server, AgeDefinition age) {
|
||||
AgeRuntimeProfile profile = AgeRuntimeProfiles.resolve(age.generationProfile());
|
||||
AgeRuntimeProfile profile = runtimeProfile(age);
|
||||
if (profile.terrain() == AgeRuntimeProfile.Terrain.FLAT) {
|
||||
return new FlatLevelSource(FlatLevelGeneratorSettings.getDefault(
|
||||
server.registryAccess().lookupOrThrow(Registries.BIOME),
|
||||
@@ -385,11 +410,11 @@ public final class AgeDimensionService {
|
||||
}
|
||||
|
||||
private static DimensionType createDimensionType(MinecraftServer server, AgeDefinition age) {
|
||||
AgeRuntimeProfile profile = AgeRuntimeProfiles.resolve(age.generationProfile());
|
||||
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(),
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.dnorberg.rivencraft.writing.SymbolReference;
|
||||
import net.dnorberg.rivencraft.writing.SymbolSemantics;
|
||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/** A frozen interpretation of authored pages. Later slices consume its resolved branches. */
|
||||
public record AgeGenerationPlan(int version, long ageSeed, OrderedWriting writing, List<ResolvedSymbol> symbols,
|
||||
AgeRuntimeProfile runtimeProfile) {
|
||||
public static final int CURRENT_VERSION = 1;
|
||||
|
||||
public AgeGenerationPlan {
|
||||
if (version != CURRENT_VERSION) throw new IllegalArgumentException("Unsupported Age plan version " + version);
|
||||
Objects.requireNonNull(writing, "writing");
|
||||
symbols = List.copyOf(symbols);
|
||||
Objects.requireNonNull(runtimeProfile, "runtimeProfile");
|
||||
if (runtimeProfile.schemaVersion() != AgeRuntimeProfile.CURRENT_SCHEMA_VERSION) {
|
||||
throw new IllegalArgumentException("Unsupported runtime profile snapshot version");
|
||||
}
|
||||
for (ResolvedSymbol symbol : symbols) {
|
||||
if (symbol.index() < 0 || symbol.index() >= writing.entries().size()
|
||||
|| !symbol.reference().equals(writing.entries().get(symbol.index()).symbol().orElse(null))) {
|
||||
throw new IllegalArgumentException("Resolved symbol does not match original page order");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** No plan is made for old page-free books or Link-Panel-only random Ages. */
|
||||
public static AgeGenerationPlan compile(OrderedWriting writing, long ageSeed, ResourceLocation seedProfile) {
|
||||
WritingGrammar.Result parsed = WritingGrammar.parse(writing);
|
||||
if (!parsed.canCreate()) throw new IllegalArgumentException(parsed.firstError().orElseThrow().message());
|
||||
if (parsed.randomFallback()) return null;
|
||||
ResourceLocation terrain = parsed.symbols().stream()
|
||||
.filter(symbol -> symbol.semantics().role() == SymbolSemantics.Role.TERRAIN)
|
||||
.map(symbol -> ((SymbolSemantics.ResourceValue) symbol.semantics().value()).id())
|
||||
.findFirst().orElse(null);
|
||||
// The seed-selected terrain remains the deterministic completion for a missing branch.
|
||||
// An explicit terrain must resolve now, before Binder inputs can be consumed.
|
||||
if (terrain != null && !AgeRuntimeProfiles.profiles().containsKey(terrain)) {
|
||||
throw new IllegalArgumentException("Unsupported Age terrain profile " + terrain);
|
||||
}
|
||||
ResourceLocation selected = terrain == null ? seedProfile : terrain;
|
||||
AgeRuntimeProfile profile = AgeRuntimeProfiles.profiles().get(selected);
|
||||
if (profile == null) throw new IllegalArgumentException("Unsupported Age terrain profile " + selected);
|
||||
return new AgeGenerationPlan(CURRENT_VERSION, ageSeed, writing,
|
||||
parsed.symbols().stream().map(symbol -> new ResolvedSymbol(
|
||||
symbol.index(), symbol.reference(), symbol.semantics())).toList(),
|
||||
profile);
|
||||
}
|
||||
|
||||
public ResourceLocation authoredTerrain() {
|
||||
return symbols.stream().filter(symbol -> symbol.semantics().role() == SymbolSemantics.Role.TERRAIN)
|
||||
.map(symbol -> ((SymbolSemantics.ResourceValue) symbol.semantics().value()).id())
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public CompoundTag save() {
|
||||
CompoundTag tag = new CompoundTag();
|
||||
tag.putInt("Version", version);
|
||||
tag.putLong("AgeSeed", ageSeed);
|
||||
ListTag pages = new ListTag();
|
||||
for (WritingEntry entry : writing.entries()) {
|
||||
CompoundTag page = new CompoundTag();
|
||||
page.putString("Kind", entry.kind().name());
|
||||
entry.symbol().ifPresent(symbol -> page.putString("Symbol", symbol.id().toString()));
|
||||
pages.add(page);
|
||||
}
|
||||
tag.put("Writing", pages);
|
||||
ListTag resolved = new ListTag();
|
||||
for (ResolvedSymbol symbol : symbols) {
|
||||
CompoundTag item = new CompoundTag();
|
||||
item.putInt("Index", symbol.index());
|
||||
item.putString("Symbol", symbol.reference().id().toString());
|
||||
item.putString("Role", symbol.semantics().role().name());
|
||||
SymbolSemantics.Value value = symbol.semantics().value();
|
||||
item.putString("Value", value instanceof SymbolSemantics.ResourceValue resource
|
||||
? resource.id().toString() : value instanceof SymbolSemantics.ChoiceValue choice
|
||||
? choice.id() : Double.toString(((SymbolSemantics.NumberValue) value).amount()));
|
||||
resolved.add(item);
|
||||
}
|
||||
tag.put("Resolved", resolved);
|
||||
CompoundTag profile = new CompoundTag();
|
||||
profile.putInt("Version", runtimeProfile.schemaVersion());
|
||||
profile.putString("Terrain", runtimeProfile.terrain().name());
|
||||
profile.putString("Noise", runtimeProfile.noiseSettings().toString());
|
||||
profile.putString("Biomes", runtimeProfile.biomePreset().toString());
|
||||
profile.putString("Dimension", runtimeProfile.dimensionType().toString());
|
||||
tag.put("RuntimeProfile", profile);
|
||||
return tag;
|
||||
}
|
||||
|
||||
public static AgeGenerationPlan load(CompoundTag tag) {
|
||||
int version = tag.getInt("Version");
|
||||
List<WritingEntry> pages = new ArrayList<>();
|
||||
ListTag writingTags = tag.getList("Writing", CompoundTag.TAG_COMPOUND);
|
||||
for (int index = 0; index < writingTags.size(); index++) {
|
||||
CompoundTag page = writingTags.getCompound(index);
|
||||
pages.add(WritingEntry.Kind.valueOf(page.getString("Kind")) == WritingEntry.Kind.LINK_PANEL
|
||||
? WritingEntry.linkPanel() : WritingEntry.symbol(new SymbolReference(
|
||||
ResourceLocation.parse(page.getString("Symbol")))));
|
||||
}
|
||||
List<ResolvedSymbol> resolved = new ArrayList<>();
|
||||
ListTag resolvedTags = tag.getList("Resolved", CompoundTag.TAG_COMPOUND);
|
||||
for (int index = 0; index < resolvedTags.size(); index++) {
|
||||
CompoundTag item = resolvedTags.getCompound(index);
|
||||
SymbolSemantics.Role role = SymbolSemantics.Role.valueOf(item.getString("Role"));
|
||||
String raw = item.getString("Value");
|
||||
SymbolSemantics.Value value = switch (role) {
|
||||
case TERRAIN, BIOME, FEATURE -> new SymbolSemantics.ResourceValue(ResourceLocation.parse(raw));
|
||||
case PERIOD_MODIFIER, ANGLE_MODIFIER, PHASE_MODIFIER ->
|
||||
new SymbolSemantics.NumberValue(Double.parseDouble(raw));
|
||||
default -> new SymbolSemantics.ChoiceValue(raw);
|
||||
};
|
||||
resolved.add(new ResolvedSymbol(item.getInt("Index"),
|
||||
new SymbolReference(ResourceLocation.parse(item.getString("Symbol"))),
|
||||
new SymbolSemantics(role, value)));
|
||||
}
|
||||
CompoundTag profile = tag.getCompound("RuntimeProfile");
|
||||
return new AgeGenerationPlan(version, tag.getLong("AgeSeed"), new OrderedWriting(pages), resolved,
|
||||
new AgeRuntimeProfile(profile.getInt("Version"),
|
||||
AgeRuntimeProfile.Terrain.valueOf(profile.getString("Terrain")),
|
||||
ResourceLocation.parse(profile.getString("Noise")),
|
||||
ResourceLocation.parse(profile.getString("Biomes")),
|
||||
ResourceLocation.parse(profile.getString("Dimension"))));
|
||||
}
|
||||
|
||||
public record ResolvedSymbol(int index, SymbolReference reference, SymbolSemantics semantics) {
|
||||
public ResolvedSymbol {
|
||||
Objects.requireNonNull(reference, "reference");
|
||||
Objects.requireNonNull(semantics, "semantics");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
import net.dnorberg.rivencraft.Rivencraft;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.dnorberg.rivencraft.writing.SymbolReference;
|
||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
@@ -18,6 +22,54 @@ public final class AgePersistenceGameTests {
|
||||
private AgePersistenceGameTests() {
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void authoredPlanRetainsResolvedMeaningAndAgeIdentity(GameTestHelper helper) {
|
||||
OrderedWriting writing = new OrderedWriting(List.of(
|
||||
WritingEntry.linkPanel(),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:terrain/standard"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:weather/normal"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:lighting/normal"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:celestial/normal_time"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:feature/caves")))
|
||||
));
|
||||
UUID id = UUID.randomUUID();
|
||||
AgeReference reference = new AgeReference(id, "Authored Plan " + id);
|
||||
AgeDefinition created = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(), reference, writing);
|
||||
helper.assertTrue(created.plan() != null, "Authored writing must create a frozen plan");
|
||||
helper.assertValueEqual(created.plan().version(), AgeGenerationPlan.CURRENT_VERSION,
|
||||
"The plan format must be explicitly versioned");
|
||||
helper.assertValueEqual(created.plan().ageSeed(), created.seed(),
|
||||
"The Age seed must be captured in the immutable plan");
|
||||
helper.assertValueEqual(created.plan().writing(), writing, "The original page order must be retained");
|
||||
helper.assertValueEqual(created.plan().symbols().size(), 5, "Every symbol must be resolved in order");
|
||||
helper.assertValueEqual(created.generationProfile(), AgeGenerationProfiles.STANDARD,
|
||||
"Authored terrain must replace the seed-selected random terrain");
|
||||
helper.assertValueEqual(created.plan().runtimeProfile(), AgeRuntimeProfiles.resolve(AgeGenerationProfiles.STANDARD),
|
||||
"The plan must snapshot the runtime profile instead of looking it up after reload");
|
||||
|
||||
AgeDefinition sameId = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(id, "Renamed"), OrderedWriting.EMPTY);
|
||||
helper.assertValueEqual(sameId, created, "The same Age UUID must never reroll from a later book");
|
||||
AgeRegistrySavedData registry = AgeRegistrySavedData.get(helper.getLevel());
|
||||
AgeDefinition restored = AgeRegistrySavedData.load(
|
||||
registry.save(new CompoundTag(), helper.getLevel().registryAccess()),
|
||||
helper.getLevel().registryAccess()).find(id).orElseThrow();
|
||||
helper.assertValueEqual(restored, created, "The complete plan must survive a saved-data round trip");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void randomFallbackDoesNotCreateAuthoredPlan(GameTestHelper helper) {
|
||||
AgeDefinition pageFree = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(UUID.randomUUID(), "Page Free"), OrderedWriting.EMPTY);
|
||||
AgeDefinition panelOnly = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(UUID.randomUUID(), "Panel Only"),
|
||||
new OrderedWriting(List.of(WritingEntry.linkPanel())));
|
||||
helper.assertTrue(pageFree.plan() == null && panelOnly.plan() == null,
|
||||
"Old and Link-Panel-only books must retain the random Age path");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void everyTraitCombinationRoundTripsWithoutRerolling(GameTestHelper helper) {
|
||||
ListTag entries = new ListTag();
|
||||
@@ -89,6 +141,8 @@ public final class AgePersistenceGameTests {
|
||||
"Definitions predating named dimensions must retain the UUID-derived dimension");
|
||||
helper.assertValueEqual(definition.traits(), AgeTraits.LEGACY_DEFAULTS,
|
||||
"Definitions predating traits must receive stable legacy defaults");
|
||||
helper.assertTrue(definition.plan() == null,
|
||||
"Existing Ages must not be reinterpreted as authored plans during migration");
|
||||
|
||||
CompoundTag serialized = migrated.save(new CompoundTag(), helper.getLevel().registryAccess());
|
||||
AgeDefinition reloaded = AgeRegistrySavedData.load(serialized, helper.getLevel().registryAccess())
|
||||
|
||||
@@ -5,6 +5,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
@@ -29,6 +30,7 @@ public final class AgeRegistrySavedData extends SavedData {
|
||||
private static final String SPAWN_Y_TAG = "SpawnY";
|
||||
private static final String SPAWN_Z_TAG = "SpawnZ";
|
||||
private static final String TRAITS_TAG = "Traits";
|
||||
private static final String PLAN_TAG = "GenerationPlan";
|
||||
private static final String BIOME_DISTRIBUTION_TAG = "BiomeDistribution";
|
||||
private static final String LIGHTING_TAG = "Lighting";
|
||||
private static final String WEATHER_TAG = "Weather";
|
||||
@@ -49,8 +51,12 @@ public final class AgeRegistrySavedData extends SavedData {
|
||||
|
||||
/** Resolves a book identity, creating its deterministic random definition exactly once. */
|
||||
public static AgeDefinition resolveOrCreate(ServerLevel level, AgeReference reference) {
|
||||
return resolveOrCreate(level, reference, OrderedWriting.EMPTY);
|
||||
}
|
||||
|
||||
public static AgeDefinition resolveOrCreate(ServerLevel level, AgeReference reference, OrderedWriting writing) {
|
||||
ServerLevel overworld = level.getServer().overworld();
|
||||
return get(overworld).getOrCreate(reference, overworld.getSeed(), overworld.getGameTime());
|
||||
return get(overworld).getOrCreate(reference, writing, overworld.getSeed(), overworld.getGameTime());
|
||||
}
|
||||
|
||||
public Optional<AgeDefinition> find(UUID ageId) {
|
||||
@@ -78,7 +84,8 @@ public final class AgeRegistrySavedData extends SavedData {
|
||||
return updated;
|
||||
}
|
||||
|
||||
private AgeDefinition getOrCreate(AgeReference reference, long worldSeed, long createdGameTime) {
|
||||
private AgeDefinition getOrCreate(AgeReference reference, OrderedWriting writing,
|
||||
long worldSeed, long createdGameTime) {
|
||||
AgeDefinition existing = ages.get(reference.id());
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
@@ -87,16 +94,19 @@ public final class AgeRegistrySavedData extends SavedData {
|
||||
String name = normalizedName(reference.name());
|
||||
ResourceLocation dimensionId = availableDimensionId(name);
|
||||
long seed = ageSeed(worldSeed, dimensionId);
|
||||
ResourceLocation seedProfile = AgeRuntimeProfiles.select(seed);
|
||||
AgeGenerationPlan plan = AgeGenerationPlan.compile(writing, seed, seedProfile);
|
||||
AgeDefinition created = new AgeDefinition(
|
||||
reference.id(),
|
||||
name,
|
||||
seed,
|
||||
AgeRuntimeProfiles.select(seed),
|
||||
plan == null || plan.authoredTerrain() == null ? seedProfile : plan.authoredTerrain(),
|
||||
AgeDefinition.CURRENT_GENERATION_VERSION,
|
||||
createdGameTime,
|
||||
dimensionId,
|
||||
null,
|
||||
AgeTraits.select(seed)
|
||||
AgeTraits.select(seed),
|
||||
plan
|
||||
);
|
||||
ages.put(created.id(), created);
|
||||
setDirty();
|
||||
@@ -138,7 +148,9 @@ public final class AgeRegistrySavedData extends SavedData {
|
||||
entry.getLong(CREATED_TIME_TAG),
|
||||
dimensionId,
|
||||
spawn,
|
||||
readTraits(entry)
|
||||
readTraits(entry),
|
||||
entry.contains(PLAN_TAG, CompoundTag.TAG_COMPOUND)
|
||||
? AgeGenerationPlan.load(entry.getCompound(PLAN_TAG)) : null
|
||||
));
|
||||
}
|
||||
return data;
|
||||
@@ -171,6 +183,7 @@ public final class AgeRegistrySavedData extends SavedData {
|
||||
traits.putFloat(CELESTIAL_ANGLE_TAG, age.traits().celestialAngle());
|
||||
traits.putFloat(CELESTIAL_PHASE_TAG, age.traits().celestialPhase());
|
||||
entry.put(TRAITS_TAG, traits);
|
||||
if (age.plan() != null) entry.put(PLAN_TAG, age.plan().save());
|
||||
serializedAges.add(entry);
|
||||
});
|
||||
tag.put(AGES_TAG, serializedAges);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<ResourceLocation> 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");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package net.dnorberg.rivencraft.client.screen;
|
||||
|
||||
import java.util.Locale;
|
||||
import net.dnorberg.rivencraft.Rivencraft;
|
||||
import net.dnorberg.rivencraft.block.entity.BookBinderBlockEntity;
|
||||
import net.dnorberg.rivencraft.item.PageItem;
|
||||
@@ -32,6 +33,7 @@ public final class BookBinderScreen extends AbstractContainerScreen<BookBinderMe
|
||||
|
||||
private EditBox titleInput;
|
||||
private int firstVisible;
|
||||
private int lastGrammarErrorStripIndex = -1;
|
||||
private boolean stripClickPendingRelease;
|
||||
|
||||
public BookBinderScreen(BookBinderMenu menu, Inventory inventory, Component title) {
|
||||
@@ -86,6 +88,13 @@ public final class BookBinderScreen extends AbstractContainerScreen<BookBinderMe
|
||||
@Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) {
|
||||
super.render(graphics, mouseX, mouseY, partialTick);
|
||||
firstVisible = Math.min(firstVisible, maxFirstVisible());
|
||||
int errorStripIndex = menu.grammarErrorStripIndex();
|
||||
if (errorStripIndex != lastGrammarErrorStripIndex) {
|
||||
if (errorStripIndex >= 0
|
||||
&& (errorStripIndex < firstVisible || errorStripIndex >= firstVisible + VISIBLE_PAGES))
|
||||
firstVisible = Math.clamp(errorStripIndex - VISIBLE_PAGES + 1, 0, maxFirstVisible());
|
||||
lastGrammarErrorStripIndex = errorStripIndex;
|
||||
}
|
||||
graphics.enableScissor(leftPos + STRIP_X + 8, topPos + STRIP_Y,
|
||||
leftPos + STRIP_X + STRIP_WIDTH - 8, topPos + STRIP_Y + STRIP_HEIGHT);
|
||||
int count = visiblePageCount();
|
||||
@@ -97,6 +106,16 @@ public final class BookBinderScreen extends AbstractContainerScreen<BookBinderMe
|
||||
}
|
||||
graphics.disableScissor();
|
||||
drawScrollEnds(graphics);
|
||||
Component grammarTooltip = menu.grammarError().map(code -> Component.translatable(
|
||||
"screen.rivencraft.book_binder.grammar." + code.name().toLowerCase(Locale.ROOT),
|
||||
errorStripIndex + 1)).orElse(null);
|
||||
if (menu.getSlot(BookBinderMenu.RESULT).getItem().isEmpty()
|
||||
&& mouseX >= leftPos + 152 && mouseX < leftPos + 168
|
||||
&& mouseY >= topPos + 27 && mouseY < topPos + 43
|
||||
&& grammarTooltip != null) {
|
||||
graphics.renderTooltip(font, grammarTooltip, mouseX, mouseY);
|
||||
return;
|
||||
}
|
||||
if (mouseY >= topPos + STRIP_Y && mouseY < topPos + STRIP_Y + STRIP_HEIGHT) {
|
||||
if (firstVisible > 0 && mouseX >= leftPos + STRIP_X && mouseX < leftPos + STRIP_X + 8)
|
||||
graphics.renderTooltip(font, Component.translatable("screen.rivencraft.book_binder.previous_pages"), mouseX, mouseY);
|
||||
@@ -111,7 +130,9 @@ public final class BookBinderScreen extends AbstractContainerScreen<BookBinderMe
|
||||
return;
|
||||
}
|
||||
int hovered = pageIndexAt(mouseX, mouseY);
|
||||
if (hovered >= 0 && hovered < displayedPages() && !pageAtIndex(hovered).isEmpty())
|
||||
if (hovered >= 0 && hovered == errorStripIndex && grammarTooltip != null)
|
||||
graphics.renderTooltip(font, grammarTooltip, mouseX, mouseY);
|
||||
else if (hovered >= 0 && hovered < displayedPages() && !pageAtIndex(hovered).isEmpty())
|
||||
graphics.renderTooltip(font, pageAtIndex(hovered), mouseX, mouseY);
|
||||
else renderTooltip(graphics, mouseX, mouseY);
|
||||
}
|
||||
@@ -148,6 +169,10 @@ public final class BookBinderScreen extends AbstractContainerScreen<BookBinderMe
|
||||
case SYMBOL, UNRESOLVED_SYMBOL -> graphics.blit(NotebookScreen.symbolTexture(page),
|
||||
x + 1, y + 5, 24, 24, 0, 0, 128, 128, 128, 128);
|
||||
}
|
||||
if (index == menu.grammarErrorStripIndex() && menu.grammarError().isPresent()) {
|
||||
graphics.fill(x, y, x + PAGE_WIDTH, y + PAGE_HEIGHT, 0x55FF2020);
|
||||
graphics.renderOutline(x, y, PAGE_WIDTH, PAGE_HEIGHT, 0xFFFF3030);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawScrollEnds(GuiGraphics graphics) {
|
||||
|
||||
@@ -14,6 +14,7 @@ import net.dnorberg.rivencraft.registry.ModItems;
|
||||
import net.dnorberg.rivencraft.writing.NotebookContents;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.dnorberg.rivencraft.writing.SymbolReference;
|
||||
import net.dnorberg.rivencraft.writing.SymbolCatalog;
|
||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
@@ -86,12 +87,41 @@ public final class BookBinderGameTests {
|
||||
restored.loadWithComponents(saved, helper.getLevel().registryAccess());
|
||||
helper.assertValueEqual(PageItem.content(restored.getItem(BookBinderBlockEntity.FIRST_PAGE))
|
||||
.symbol().orElseThrow(), missing, "Reload must preserve the removed data-pack symbol ID");
|
||||
helper.assertFalse(restored.canAssemble(), "Missing symbol cannot create a new written Age");
|
||||
restored.getItem(BookBinderBlockEntity.FIRST_PAGE).set(ModDataComponents.PAGE_SYMBOL_DISPLAY.get(),
|
||||
SymbolCatalog.display(new SymbolReference(ResourceLocation.parse("rivencraft:terrain/standard"))));
|
||||
helper.assertFalse(restored.canAssemble(),
|
||||
"Forged display metadata cannot make a missing symbol valid for a new Age");
|
||||
helper.assertTrue(restored.getItem(BookBinderBlockEntity.FIRST_PAGE).is(ModItems.PAGE.get()),
|
||||
"Rejected writing must remain recoverable as a Page");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void conflictingGrammarKeepsBinderInputsRecoverable(GameTestHelper helper) {
|
||||
BookBinderBlockEntity binder = place(helper);
|
||||
binder.setTitle("Recoverable Duplicate");
|
||||
binder.setItem(BookBinderBlockEntity.COVER, new ItemStack(Items.LEATHER));
|
||||
binder.setItem(BookBinderBlockEntity.LINK_PANEL, PageItem.createLinkPanelPage());
|
||||
binder.setItem(BookBinderBlockEntity.FIRST_PAGE, terrainPage());
|
||||
binder.setItem(BookBinderBlockEntity.FIRST_PAGE + 5, terrainPage());
|
||||
helper.assertFalse(binder.canAssemble(), "Duplicate terrain must not assemble a new Age");
|
||||
int errorEntry = binder.writingGrammar().firstError().orElseThrow().index();
|
||||
helper.assertValueEqual(errorEntry, 2, "Parser must identify the second authored symbol");
|
||||
helper.assertValueEqual(binder.writingStripIndex(errorEntry), 6,
|
||||
"A grammar error must highlight the correct strip page despite empty positions");
|
||||
helper.assertFalse(binder.consumeAssembly(), "Rejected grammar must not consume binder inputs");
|
||||
helper.assertTrue(binder.getItem(BookBinderBlockEntity.COVER).is(Items.LEATHER),
|
||||
"Rejected grammar must leave the cover recoverable");
|
||||
helper.assertTrue(binder.getItem(BookBinderBlockEntity.LINK_PANEL).is(ModItems.PAGE.get()),
|
||||
"Rejected grammar must leave the Link Panel recoverable");
|
||||
helper.assertTrue(binder.getItem(BookBinderBlockEntity.FIRST_PAGE + 5).is(ModItems.PAGE.get()),
|
||||
"Rejected grammar must leave the duplicate page removable");
|
||||
ItemStack removed = binder.takePage(5);
|
||||
helper.assertTrue(removed.is(ModItems.PAGE.get()), "Player must be able to correct the duplicate page");
|
||||
helper.assertTrue(binder.canAssemble(), "Corrected partial writing must become assemblable");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
public static void assemblyIsAtomicAndRetainsPageOrder(GameTestHelper helper) {
|
||||
BookBinderBlockEntity binder = place(helper);
|
||||
binder.setTitle("A New Age");
|
||||
|
||||
@@ -47,6 +47,11 @@ public final class CoreGameTests {
|
||||
WritingDataGameTests.semanticSchemaIsServerOnlyBoundedAndV1Compatible(helper);
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void orderedWritingGrammar(GameTestHelper helper) {
|
||||
WritingGrammarGameTests.orderedGrammarAcceptsPartialWritingAndDiagnosesInvalidSequences(helper);
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void notebookPersistence(GameTestHelper helper) {
|
||||
WritingDataGameTests.notebookContentsPreserveOrderGapsNamesAndUnknownPages(helper);
|
||||
@@ -82,6 +87,11 @@ public final class CoreGameTests {
|
||||
BookBinderGameTests.assemblyIsAtomicAndRetainsPageOrder(helper);
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void binderRejectsConflictingGrammar(GameTestHelper helper) {
|
||||
BookBinderGameTests.conflictingGrammarKeepsBinderInputsRecoverable(helper);
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void binderRejectsForgedAndReplayedActions(GameTestHelper helper) {
|
||||
BookBinderGameTests.forgedBinderActionsAndReplayedOutputCannotDuplicateBook(helper);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package net.dnorberg.rivencraft.gametest;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.dnorberg.rivencraft.writing.SymbolCatalog;
|
||||
import net.dnorberg.rivencraft.writing.SymbolDefinition;
|
||||
import net.dnorberg.rivencraft.writing.SymbolReference;
|
||||
import net.dnorberg.rivencraft.writing.SymbolSemantics;
|
||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.neoforged.neoforge.gametest.GameTestHolder;
|
||||
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
|
||||
|
||||
/** Issue #30: parsing must not mutate writing or trust client display metadata. */
|
||||
@GameTestHolder("rivencraft_archive_grammar")
|
||||
@PrefixGameTestTemplate(false)
|
||||
public final class WritingGrammarGameTests {
|
||||
private WritingGrammarGameTests() {}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void orderedGrammarAcceptsPartialWritingAndDiagnosesInvalidSequences(GameTestHelper helper) {
|
||||
SymbolReference terrain = ref("rivencraft:terrain/standard");
|
||||
SymbolReference nativeBiomes = ref("rivencraft:biome/native");
|
||||
SymbolReference weather = ref("rivencraft:weather/normal");
|
||||
SymbolReference lighting = ref("rivencraft:lighting/normal");
|
||||
SymbolReference celestial = ref("rivencraft:celestial/normal_time");
|
||||
SymbolReference caves = ref("rivencraft:feature/caves");
|
||||
SymbolReference plains = ref("test:biome/plains");
|
||||
SymbolReference forest = ref("test:biome/forest");
|
||||
SymbolReference single = ref("test:controller/single");
|
||||
SymbolReference alternateTerrain = ref("test:terrain/alternate");
|
||||
SymbolReference periodHalf = ref("test:period/half");
|
||||
SymbolReference periodFull = ref("test:period/full");
|
||||
SymbolReference displayOnly = ref("test:display_only");
|
||||
Map<SymbolReference, SymbolDefinition> definitions = Map.of(
|
||||
plains, definition(SymbolSemantics.Role.BIOME,
|
||||
new SymbolSemantics.ResourceValue(ResourceLocation.parse("minecraft:plains"))),
|
||||
forest, definition(SymbolSemantics.Role.BIOME,
|
||||
new SymbolSemantics.ResourceValue(ResourceLocation.parse("minecraft:forest"))),
|
||||
single, definition(SymbolSemantics.Role.BIOME_CONTROLLER,
|
||||
new SymbolSemantics.ChoiceValue("single")),
|
||||
alternateTerrain, definition(SymbolSemantics.Role.TERRAIN,
|
||||
new SymbolSemantics.ResourceValue(ResourceLocation.parse("test:alternate"))),
|
||||
periodHalf, definition(SymbolSemantics.Role.PERIOD_MODIFIER,
|
||||
new SymbolSemantics.NumberValue(0.5)),
|
||||
periodFull, definition(SymbolSemantics.Role.PERIOD_MODIFIER,
|
||||
new SymbolSemantics.NumberValue(1.0)),
|
||||
displayOnly, new SymbolDefinition(1, "symbol.test", "symbol.test.description",
|
||||
ResourceLocation.parse("test:display"), Optional.empty(), ""));
|
||||
java.util.function.Function<SymbolReference, Optional<SymbolDefinition>> resolver = reference ->
|
||||
Optional.ofNullable(definitions.get(reference)).or(() -> SymbolCatalog.find(reference));
|
||||
|
||||
helper.assertTrue(parse(resolver, WritingEntry.linkPanel()).randomFallback(),
|
||||
"Link-Panel-only writing must retain the random Age path");
|
||||
helper.assertTrue(WritingGrammar.parse(OrderedWriting.EMPTY, resolver).randomFallback(),
|
||||
"Old page-free books must retain the random Age path");
|
||||
OrderedWriting partial = writing(WritingEntry.linkPanel(), WritingEntry.symbol(terrain));
|
||||
WritingGrammar.Result incomplete = WritingGrammar.parse(partial, resolver);
|
||||
helper.assertTrue(incomplete.canCreate() && !incomplete.randomFallback(),
|
||||
"Partial authored writing must remain valid, without pretending it is page-free");
|
||||
helper.assertTrue(incomplete.diagnostics().stream().anyMatch(d -> d.code() == WritingGrammar.Code.INCOMPLETE),
|
||||
"Missing branches must be reported for deterministic completion");
|
||||
helper.assertValueEqual(partial.entries().size(), 2, "Parsing must not rewrite saved page order");
|
||||
|
||||
WritingGrammar.Result complete = parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(terrain),
|
||||
WritingEntry.symbol(plains), WritingEntry.symbol(single), WritingEntry.symbol(weather),
|
||||
WritingEntry.symbol(lighting), WritingEntry.symbol(periodHalf), WritingEntry.symbol(celestial),
|
||||
WritingEntry.symbol(caves));
|
||||
helper.assertTrue(complete.canCreate(), "Legacy-ordered categories and prefix modifiers must parse");
|
||||
helper.assertValueEqual(complete.symbols().size(), 8, "Parsed symbols must preserve every authored page");
|
||||
helper.assertValueEqual(complete.symbols().get(1).reference(), plains,
|
||||
"A biome page must precede the controller that consumes it");
|
||||
helper.assertValueEqual(WritingGrammar.parse(writing(WritingEntry.linkPanel(), WritingEntry.symbol(terrain),
|
||||
WritingEntry.symbol(plains), WritingEntry.symbol(single), WritingEntry.symbol(weather),
|
||||
WritingEntry.symbol(lighting), WritingEntry.symbol(periodHalf), WritingEntry.symbol(celestial),
|
||||
WritingEntry.symbol(caves)), resolver), complete,
|
||||
"Identical ordered writing and server definitions must parse deterministically");
|
||||
|
||||
WritingGrammar.Result repeatedModifiers = parse(resolver, WritingEntry.linkPanel(),
|
||||
WritingEntry.symbol(periodHalf), WritingEntry.symbol(periodFull), WritingEntry.symbol(celestial));
|
||||
helper.assertTrue(repeatedModifiers.canCreate(), "Repeated period modifiers must remain legal");
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(terrain),
|
||||
WritingEntry.symbol(terrain)), WritingGrammar.Code.DUPLICATE);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(terrain),
|
||||
WritingEntry.symbol(alternateTerrain)), WritingGrammar.Code.CONFLICT);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(weather),
|
||||
WritingEntry.symbol(terrain)), WritingGrammar.Code.OUT_OF_ORDER);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(celestial),
|
||||
WritingEntry.symbol(periodHalf)), WritingGrammar.Code.MISPLACED_MODIFIER);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(nativeBiomes),
|
||||
WritingEntry.symbol(plains)), WritingGrammar.Code.OUT_OF_ORDER);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(plains),
|
||||
WritingEntry.symbol(nativeBiomes)), WritingGrammar.Code.CONFLICT);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(plains),
|
||||
WritingEntry.symbol(forest), WritingEntry.symbol(single)), WritingGrammar.Code.CONFLICT);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(caves),
|
||||
WritingEntry.symbol(caves)), WritingGrammar.Code.DUPLICATE);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(ref("test:missing"))),
|
||||
WritingGrammar.Code.UNRESOLVED);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.symbol(displayOnly)),
|
||||
WritingGrammar.Code.UNSUPPORTED);
|
||||
assertCode(helper, parse(resolver, WritingEntry.symbol(terrain)), WritingGrammar.Code.MISSING_PANEL);
|
||||
assertCode(helper, parse(resolver, WritingEntry.linkPanel(), WritingEntry.linkPanel()),
|
||||
WritingGrammar.Code.DUPLICATE_PANEL);
|
||||
|
||||
List<WritingEntry> oversized = new ArrayList<>();
|
||||
for (int index = 0; index <= WritingGrammar.MAX_NEW_ENTRIES; index++)
|
||||
oversized.add(WritingEntry.linkPanel());
|
||||
assertCode(helper, WritingGrammar.parse(new OrderedWriting(oversized), resolver), WritingGrammar.Code.TOO_MANY);
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
private static SymbolReference ref(String id) {
|
||||
return new SymbolReference(ResourceLocation.parse(id));
|
||||
}
|
||||
|
||||
private static SymbolDefinition definition(SymbolSemantics.Role role, SymbolSemantics.Value value) {
|
||||
return new SymbolDefinition(2, "symbol.test", "symbol.test.description",
|
||||
ResourceLocation.parse("test:" + role.id()), Optional.of(new SymbolSemantics(role, value)), "");
|
||||
}
|
||||
|
||||
private static OrderedWriting writing(WritingEntry... entries) {
|
||||
return new OrderedWriting(List.of(entries));
|
||||
}
|
||||
|
||||
private static WritingGrammar.Result parse(
|
||||
java.util.function.Function<SymbolReference, Optional<SymbolDefinition>> resolver,
|
||||
WritingEntry... entries) {
|
||||
return WritingGrammar.parse(writing(entries), resolver);
|
||||
}
|
||||
|
||||
private static void assertCode(GameTestHelper helper, WritingGrammar.Result result, WritingGrammar.Code code) {
|
||||
helper.assertFalse(result.canCreate(), "Writing with " + code + " must not create a new Age");
|
||||
helper.assertTrue(result.diagnostics().stream().anyMatch(diagnostic -> diagnostic.code() == code),
|
||||
"Writing must report " + code + " rather than silently dropping a page");
|
||||
}
|
||||
}
|
||||
@@ -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<String, SymbolDisplayMetadata> 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<String> 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<String, SymbolDisplayMetadata> 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<String, SymbolDisplayMetadata> 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);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package net.dnorberg.rivencraft.menu;
|
||||
|
||||
import java.util.Optional;
|
||||
import net.dnorberg.rivencraft.block.entity.BookBinderBlockEntity;
|
||||
import net.dnorberg.rivencraft.item.PageItem;
|
||||
import net.dnorberg.rivencraft.registry.ModItems;
|
||||
import net.dnorberg.rivencraft.registry.ModMenus;
|
||||
import net.dnorberg.rivencraft.writing.PageContent;
|
||||
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.SimpleContainer;
|
||||
@@ -32,6 +34,8 @@ public final class BookBinderMenu extends AbstractContainerMenu {
|
||||
private final SimpleContainer result = new SimpleContainer(1);
|
||||
private final boolean clientSide;
|
||||
private int selectedPage = -1;
|
||||
private int grammarErrorCode = -1;
|
||||
private int grammarErrorStripIndex = -1;
|
||||
|
||||
public BookBinderMenu(int id, Inventory inventory, RegistryFriendlyByteBuf data) {
|
||||
this(id, inventory, inventory.player.level().getBlockEntity(data.readBlockPos())
|
||||
@@ -47,6 +51,20 @@ public final class BookBinderMenu extends AbstractContainerMenu {
|
||||
@Override public int get() { return selectedPage; }
|
||||
@Override public void set(int value) { selectedPage = value; }
|
||||
});
|
||||
addDataSlot(new DataSlot() {
|
||||
@Override public int get() {
|
||||
return clientSide || binder == null ? grammarErrorCode : binder.writingGrammar().firstError()
|
||||
.map(error -> error.code().ordinal()).orElse(-1);
|
||||
}
|
||||
@Override public void set(int value) { grammarErrorCode = value; }
|
||||
});
|
||||
addDataSlot(new DataSlot() {
|
||||
@Override public int get() {
|
||||
return clientSide || binder == null ? grammarErrorStripIndex : binder.writingGrammar().firstError()
|
||||
.map(error -> binder.writingStripIndex(error.index())).orElse(-1);
|
||||
}
|
||||
@Override public void set(int value) { grammarErrorStripIndex = value; }
|
||||
});
|
||||
addSlot(new BinderSlot(BookBinderBlockEntity.COVER, 8, 27, 64));
|
||||
addSlot(new BinderSlot(BookBinderBlockEntity.LINK_PANEL, -1000, -1000, 1));
|
||||
addSlot(new BinderSlot(BookBinderBlockEntity.NOTEBOOK, -1000, -1000, 1));
|
||||
@@ -66,6 +84,12 @@ public final class BookBinderMenu extends AbstractContainerMenu {
|
||||
}
|
||||
|
||||
public int selectedPage() { return selectedPage; }
|
||||
public Optional<WritingGrammar.Code> grammarError() {
|
||||
WritingGrammar.Code[] codes = WritingGrammar.Code.values();
|
||||
return grammarErrorCode >= 0 && grammarErrorCode < codes.length
|
||||
? Optional.of(codes[grammarErrorCode]) : Optional.empty();
|
||||
}
|
||||
public int grammarErrorStripIndex() { return grammarErrorStripIndex; }
|
||||
public String title() { return binder == null ? "" : binder.title(); }
|
||||
public boolean setTitle(Player player, String title) {
|
||||
if (clientSide || !stillValid(player) || title == null
|
||||
|
||||
@@ -5,6 +5,8 @@ import net.dnorberg.rivencraft.book.LinkingService;
|
||||
import net.dnorberg.rivencraft.book.AgeReference;
|
||||
import net.dnorberg.rivencraft.book.AgeRegistrySavedData;
|
||||
import net.dnorberg.rivencraft.book.AgeDimensionService;
|
||||
import net.dnorberg.rivencraft.book.AgeGenerationPlan;
|
||||
import net.dnorberg.rivencraft.book.AgeGenerationProfiles;
|
||||
import net.dnorberg.rivencraft.block.entity.BookStandBlockEntity;
|
||||
import net.dnorberg.rivencraft.client.ClientLinkPreviewHandler;
|
||||
import net.dnorberg.rivencraft.client.ClientBookInteractionHandler;
|
||||
@@ -20,6 +22,7 @@ import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.dnorberg.rivencraft.writing.SymbolCatalog;
|
||||
import net.dnorberg.rivencraft.writing.SymbolDisplayMetadata;
|
||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
@@ -133,10 +136,28 @@ public final class ModNetworking {
|
||||
return;
|
||||
}
|
||||
|
||||
var grammar = WritingGrammar.parse(access.stack()
|
||||
.getOrDefault(ModDataComponents.BOOK_WRITING.get(), OrderedWriting.EMPTY));
|
||||
if (!grammar.canCreate()) {
|
||||
player.displayClientMessage(Component.translatable("message.rivencraft.descriptive_book.invalid_writing",
|
||||
grammar.firstError().orElseThrow().message()), true);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
AgeGenerationPlan.compile(access.stack()
|
||||
.getOrDefault(ModDataComponents.BOOK_WRITING.get(), OrderedWriting.EMPTY),
|
||||
0L, AgeGenerationProfiles.STANDARD);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
player.displayClientMessage(Component.translatable("message.rivencraft.descriptive_book.invalid_writing",
|
||||
exception.getMessage()), true);
|
||||
return;
|
||||
}
|
||||
|
||||
WRITING_BOOKS.add(access.stack());
|
||||
try {
|
||||
AgeReference reference = new AgeReference(UUID.randomUUID(), title);
|
||||
if (AgeDimensionService.resolve(player, reference).isEmpty()) {
|
||||
if (AgeDimensionService.resolve(player, reference, access.stack()
|
||||
.getOrDefault(ModDataComponents.BOOK_WRITING.get(), OrderedWriting.EMPTY)).isEmpty()) {
|
||||
player.displayClientMessage(Component.translatable("message.rivencraft.descriptive_book.unavailable"), true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package net.dnorberg.rivencraft.writing;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import net.dnorberg.rivencraft.writing.SymbolSemantics.ChoiceValue;
|
||||
import net.dnorberg.rivencraft.writing.SymbolSemantics.Role;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/** Server-owned interpretation of ordered writing; compilation belongs to the next release slice. */
|
||||
public final class WritingGrammar {
|
||||
// A newly assembled book has one Link Panel plus at most 27 page positions.
|
||||
public static final int MAX_NEW_ENTRIES = NotebookContents.MAX_PAGES + 1;
|
||||
|
||||
private WritingGrammar() {}
|
||||
|
||||
public static Result parse(OrderedWriting writing) {
|
||||
return parse(writing, SymbolCatalog::find);
|
||||
}
|
||||
|
||||
/** The resolver must be the authoritative server catalog, never page display metadata. */
|
||||
public static Result parse(OrderedWriting writing,
|
||||
Function<SymbolReference, Optional<SymbolDefinition>> resolver) {
|
||||
Objects.requireNonNull(writing, "writing");
|
||||
Objects.requireNonNull(resolver, "resolver");
|
||||
List<ParsedSymbol> symbols = new ArrayList<>();
|
||||
List<Diagnostic> diagnostics = new ArrayList<>();
|
||||
if (writing.entries().size() > MAX_NEW_ENTRIES) {
|
||||
diagnostics.add(new Diagnostic(Code.TOO_MANY, -1, "At most " + MAX_NEW_ENTRIES + " entries are allowed"));
|
||||
return new Result(symbols, diagnostics);
|
||||
}
|
||||
if (writing.entries().isEmpty()) return new Result(symbols, diagnostics);
|
||||
|
||||
EnumMap<Role, ParsedSymbol> singular = new EnumMap<>(Role.class);
|
||||
Set<ResourceLocation> features = new HashSet<>();
|
||||
int panels = 0;
|
||||
int lastStage = -1;
|
||||
int biomeCount = 0;
|
||||
for (int index = 0; index < writing.entries().size(); index++) {
|
||||
WritingEntry entry = writing.entries().get(index);
|
||||
if (entry.kind() == WritingEntry.Kind.LINK_PANEL) {
|
||||
panels++;
|
||||
if (panels > 1) diagnostics.add(new Diagnostic(Code.DUPLICATE_PANEL, index,
|
||||
"Use exactly one Link Panel"));
|
||||
else if (index != 0) diagnostics.add(new Diagnostic(Code.PANEL_ORDER, index,
|
||||
"Move the Link Panel to the first position"));
|
||||
continue;
|
||||
}
|
||||
|
||||
SymbolReference reference = entry.symbol().orElseThrow();
|
||||
Optional<SymbolDefinition> definition = resolver.apply(reference);
|
||||
if (definition.isEmpty()) {
|
||||
diagnostics.add(new Diagnostic(Code.UNRESOLVED, index,
|
||||
"Restore the data pack for " + reference.id() + " or remove this page"));
|
||||
continue;
|
||||
}
|
||||
Optional<SymbolSemantics> semantics = definition.orElseThrow().semantics();
|
||||
if (semantics.isEmpty()) {
|
||||
diagnostics.add(new Diagnostic(Code.UNSUPPORTED, index,
|
||||
"Update " + reference.id() + " to semantic schema v2 or remove this page"));
|
||||
continue;
|
||||
}
|
||||
|
||||
Role role = semantics.orElseThrow().role();
|
||||
ParsedSymbol parsed = new ParsedSymbol(index, reference, semantics.orElseThrow());
|
||||
symbols.add(parsed);
|
||||
if (singular(role)) {
|
||||
ParsedSymbol previous = singular.putIfAbsent(role, parsed);
|
||||
if (previous != null) {
|
||||
Code code = previous.semantics().value().equals(parsed.semantics().value())
|
||||
? Code.DUPLICATE : Code.CONFLICT;
|
||||
diagnostics.add(new Diagnostic(code, index,
|
||||
"Remove this " + role.id() + " page; position " + (previous.index() + 1)
|
||||
+ " already supplies that category"));
|
||||
continue;
|
||||
}
|
||||
} else if (role == Role.FEATURE && !features.add(reference.id())) {
|
||||
diagnostics.add(new Diagnostic(Code.DUPLICATE, index,
|
||||
"Remove the repeated feature page " + reference.id()));
|
||||
continue;
|
||||
}
|
||||
if (role == Role.BIOME) biomeCount++;
|
||||
int stage = stage(role);
|
||||
if (stage < lastStage) {
|
||||
diagnostics.add(new Diagnostic(modifier(role) ? Code.MISPLACED_MODIFIER : Code.OUT_OF_ORDER,
|
||||
index, "Move this " + role.id() + " page before later grammar categories"));
|
||||
} else {
|
||||
lastStage = stage;
|
||||
}
|
||||
}
|
||||
if (panels == 0) diagnostics.add(new Diagnostic(Code.MISSING_PANEL, -1,
|
||||
"Add a Link Panel as the first page"));
|
||||
if (symbols.isEmpty()) return new Result(symbols, diagnostics);
|
||||
|
||||
ParsedSymbol controller = singular.get(Role.BIOME_CONTROLLER);
|
||||
if (controller != null && controller.semantics().value() instanceof ChoiceValue choice
|
||||
&& choice.id().equals("native") && biomeCount > 0) {
|
||||
diagnostics.add(new Diagnostic(Code.CONFLICT, controller.index(),
|
||||
"Native biome distribution cannot use authored biome pages"));
|
||||
} else if (controller != null && controller.semantics().value() instanceof ChoiceValue choice
|
||||
&& choice.id().equals("single") && biomeCount > 1) {
|
||||
diagnostics.add(new Diagnostic(Code.CONFLICT, controller.index(),
|
||||
"Single-biome distribution accepts only one authored biome page"));
|
||||
}
|
||||
for (Role required : List.of(Role.TERRAIN, Role.BIOME_CONTROLLER, Role.WEATHER,
|
||||
Role.LIGHTING, Role.CELESTIAL)) {
|
||||
if (!singular.containsKey(required)) diagnostics.add(new Diagnostic(Code.INCOMPLETE, -1,
|
||||
"The Age compiler will fill the missing " + required.id() + " branch from the Age seed"));
|
||||
}
|
||||
if (controller != null && controller.semantics().value() instanceof ChoiceValue choice) {
|
||||
int minimum = switch (choice.id()) {
|
||||
case "single" -> 1;
|
||||
case "tiled", "grid" -> 2;
|
||||
case "native" -> 0;
|
||||
default -> 3;
|
||||
};
|
||||
if (biomeCount < minimum) diagnostics.add(new Diagnostic(Code.INCOMPLETE, -1,
|
||||
"The Age compiler will fill " + (minimum - biomeCount) + " missing biome page(s)"));
|
||||
}
|
||||
return new Result(symbols, diagnostics);
|
||||
}
|
||||
|
||||
private static boolean singular(Role role) {
|
||||
return switch (role) {
|
||||
case TERRAIN, BIOME_CONTROLLER, WEATHER, LIGHTING, CELESTIAL -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean modifier(Role role) {
|
||||
return role == Role.PERIOD_MODIFIER || role == Role.ANGLE_MODIFIER || role == Role.PHASE_MODIFIER;
|
||||
}
|
||||
|
||||
private static int stage(Role role) {
|
||||
return switch (role) {
|
||||
case TERRAIN -> 0;
|
||||
case BIOME -> 1;
|
||||
case BIOME_CONTROLLER -> 2;
|
||||
case WEATHER -> 3;
|
||||
case LIGHTING -> 4;
|
||||
case PERIOD_MODIFIER, ANGLE_MODIFIER, PHASE_MODIFIER -> 5;
|
||||
case CELESTIAL -> 6;
|
||||
case FEATURE -> 7;
|
||||
};
|
||||
}
|
||||
|
||||
public enum Code {
|
||||
TOO_MANY, MISSING_PANEL, PANEL_ORDER, DUPLICATE_PANEL, UNRESOLVED, UNSUPPORTED,
|
||||
DUPLICATE, CONFLICT, OUT_OF_ORDER, MISPLACED_MODIFIER, INCOMPLETE, UNSUPPORTED_PROFILE
|
||||
}
|
||||
|
||||
public record Diagnostic(Code code, int index, String message) {
|
||||
public Diagnostic {
|
||||
Objects.requireNonNull(code, "code");
|
||||
Objects.requireNonNull(message, "message");
|
||||
}
|
||||
|
||||
public boolean error() { return code != Code.INCOMPLETE; }
|
||||
}
|
||||
|
||||
public record ParsedSymbol(int index, SymbolReference reference, SymbolSemantics semantics) {
|
||||
public ParsedSymbol {
|
||||
Objects.requireNonNull(reference, "reference");
|
||||
Objects.requireNonNull(semantics, "semantics");
|
||||
}
|
||||
}
|
||||
|
||||
public record Result(List<ParsedSymbol> symbols, List<Diagnostic> diagnostics) {
|
||||
public Result {
|
||||
symbols = List.copyOf(symbols);
|
||||
diagnostics = List.copyOf(diagnostics);
|
||||
}
|
||||
|
||||
public boolean randomFallback() { return symbols.isEmpty() && diagnostics.isEmpty(); }
|
||||
public boolean canCreate() { return diagnostics.stream().noneMatch(Diagnostic::error); }
|
||||
public Optional<Diagnostic> firstError() { return diagnostics.stream().filter(Diagnostic::error).findFirst(); }
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,17 @@
|
||||
"screen.rivencraft.book_binder.previous_pages": "Scroll pages left (Left Arrow)",
|
||||
"screen.rivencraft.book_binder.next_pages": "Scroll pages right (Right Arrow)",
|
||||
"screen.rivencraft.book_binder.select_hint": "Right-click page to select",
|
||||
"screen.rivencraft.book_binder.grammar.too_many": "Too many pages for a new Age; remove excess pages",
|
||||
"screen.rivencraft.book_binder.grammar.missing_panel": "Add a Link Panel as the first page",
|
||||
"screen.rivencraft.book_binder.grammar.panel_order": "Page %s: move the Link Panel to the first position",
|
||||
"screen.rivencraft.book_binder.grammar.duplicate_panel": "Page %s: remove the extra Link Panel",
|
||||
"screen.rivencraft.book_binder.grammar.unresolved": "Page %s: missing symbol definition; restore its data pack or remove it",
|
||||
"screen.rivencraft.book_binder.grammar.unsupported": "Page %s: this symbol needs semantic schema v2; update its data pack or remove it",
|
||||
"screen.rivencraft.book_binder.grammar.unsupported_profile": "Page %s: its Age profile is unavailable; restore the data pack or remove this page",
|
||||
"screen.rivencraft.book_binder.grammar.duplicate": "Page %s: remove the duplicate symbol",
|
||||
"screen.rivencraft.book_binder.grammar.conflict": "Page %s: replace the conflicting symbol",
|
||||
"screen.rivencraft.book_binder.grammar.out_of_order": "Page %s: move this symbol before later categories",
|
||||
"screen.rivencraft.book_binder.grammar.misplaced_modifier": "Page %s: move this modifier before its celestial page",
|
||||
"screen.rivencraft.writing_desk.ink": "Ink: %s/%s",
|
||||
"screen.rivencraft.writing_desk.search": "Search",
|
||||
"screen.rivencraft.writing_desk.sort": "Sort pages by name (A–Z)",
|
||||
@@ -58,6 +69,7 @@
|
||||
"message.rivencraft.descriptive_book.unwritten": "This Descriptive Book is unwritten",
|
||||
"message.rivencraft.descriptive_book.created": "Created Age: %s",
|
||||
"message.rivencraft.descriptive_book.unavailable": "That Age is unavailable",
|
||||
"message.rivencraft.descriptive_book.invalid_writing": "Writing cannot create an Age: %s",
|
||||
"message.rivencraft.descriptive_book.unsafe": "No safe destination was found in that Age",
|
||||
"message.rivencraft.descriptive_book.linked_first": "Linked to %s — a Return Link was created",
|
||||
"message.rivencraft.descriptive_book.linked": "Linked to %s",
|
||||
@@ -108,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",
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
Reference in new issue
Block a user