Public Access
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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.
|
All required GameTests should pass before distributing a build.
|
||||||
|
|
||||||
GameTests use `build/gametest-run/world`, separate from the normal development
|
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.
|
world. Gradle starts each default run with a fresh world and removes it after
|
||||||
Override the limit with `-PgameTestMaxWorldMiB=NUMBER`. A caller-supplied
|
a successful run. Failed worlds are retained under
|
||||||
`-PgameTestRunDir` is never removed automatically.
|
`build/gametest-run/failed-worlds/` for inspection until the next successful
|
||||||
|
run. Logs and configuration are kept. A caller-supplied `-PgameTestRunDir`
|
||||||
|
is never removed automatically.
|
||||||
|
|
||||||
To run the suite in a fresh temporary directory instead, use:
|
To run the suite in a fresh temporary directory instead, use:
|
||||||
|
|
||||||
|
|||||||
@@ -92,10 +92,13 @@ outputs a Descriptive Book once the title, cover, and Link Panel are present.
|
|||||||
Inputs are consumed only when the result is taken.
|
Inputs are consumed only when the result is taken.
|
||||||
|
|
||||||
The completed book receives its Age identity when assembled. With only a Link
|
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
|
Panel, it describes a randomly generated Age. Authored writing is compiled once
|
||||||
book; the Descriptive Book screen's turned pages show ordered symbols and
|
into a versioned, server-owned Age plan. The plan freezes the Age seed, resolved
|
||||||
unresolved IDs. Until Milestone 5, symbols do not affect generation and written
|
symbol meanings, page order, and runtime profile, so later data-pack changes do
|
||||||
books use the same random Age fallback. The Descriptive Book screen follows
|
not reinterpret an existing Age. An authored terrain page selects its runtime
|
||||||
|
profile; 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
|
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
|
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
|
symbol pages appear before the final blank spread; their pictograms await
|
||||||
|
|||||||
+67
-30
@@ -17,7 +17,7 @@ tasks.named('wrapper', Wrapper).configure {
|
|||||||
version = mod_version
|
version = mod_version
|
||||||
group = mod_group_id
|
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')
|
List<String> selectedArchivedGameTestSuites = providers.gradleProperty('withArchivedGameTests')
|
||||||
.map { it.toBoolean() }.orElse(false).get() ? archivedGameTestSuites
|
.map { it.toBoolean() }.orElse(false).get() ? archivedGameTestSuites
|
||||||
: providers.gradleProperty('archivedGameTestSuites').orElse('').get()
|
: providers.gradleProperty('archivedGameTestSuites').orElse('').get()
|
||||||
@@ -148,42 +148,79 @@ neoForge {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// GameTests generate Ages, so their dedicated world can grow quickly across runs.
|
// Every default run gets a fresh world. Failed worlds stay available until a
|
||||||
// Never auto-delete a caller-supplied gameTestRunDir or a normal dev world.
|
// successful run; caller-supplied directories are never managed here.
|
||||||
long gameTestWorldLimitMiB = providers.gradleProperty('gameTestMaxWorldMiB').orElse('512').get().toLong()
|
|
||||||
if (gameTestWorldLimitMiB <= 0) {
|
|
||||||
throw new GradleException('gameTestMaxWorldMiB must be a positive number')
|
|
||||||
}
|
|
||||||
boolean customGameTestRunDir = providers.gradleProperty('gameTestRunDir').isPresent()
|
boolean customGameTestRunDir = providers.gradleProperty('gameTestRunDir').isPresent()
|
||||||
File dedicatedGameTestDir = layout.buildDirectory.dir('gametest-run').get().asFile.canonicalFile
|
File dedicatedGameTestBuildDir = layout.buildDirectory.get().asFile
|
||||||
|
File dedicatedGameTestDir = layout.buildDirectory.dir('gametest-run').get().asFile
|
||||||
File dedicatedGameTestWorld = new File(dedicatedGameTestDir, 'world')
|
File dedicatedGameTestWorld = new File(dedicatedGameTestDir, 'world')
|
||||||
def cleanOversizedGameTestWorld = tasks.register('cleanOversizedGameTestWorld') {
|
File gameTestSuccessMarker = new File(dedicatedGameTestDir, '.last-gametest-succeeded')
|
||||||
|
def prepareGameTestWorld = tasks.register('prepareGameTestWorld') {
|
||||||
|
onlyIf { !customGameTestRunDir }
|
||||||
doLast {
|
doLast {
|
||||||
if (customGameTestRunDir) {
|
java.nio.file.Files.deleteIfExists(gameTestSuccessMarker.toPath())
|
||||||
getLogger().lifecycle('Skipping automatic GameTest world cleanup for custom gameTestRunDir')
|
File preserved = GameTestWorlds.preserve(dedicatedGameTestBuildDir, dedicatedGameTestDir)
|
||||||
return
|
if (preserved != null) logger.lifecycle('Preserved GameTest world for inspection at {}', preserved)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
def worldDir = dedicatedGameTestWorld
|
def finishGameTestWorld = tasks.register('finishGameTestWorld') {
|
||||||
if (!worldDir.isDirectory() || java.nio.file.Files.isSymbolicLink(worldDir.toPath())) {
|
onlyIf { !customGameTestRunDir }
|
||||||
return
|
doLast {
|
||||||
}
|
if (gameTestSuccessMarker.exists()) {
|
||||||
|
GameTestWorlds.clean(dedicatedGameTestBuildDir, dedicatedGameTestDir)
|
||||||
def paths = java.nio.file.Files.walk(worldDir.toPath()).withCloseable { it.toList() }
|
java.nio.file.Files.delete(gameTestSuccessMarker.toPath())
|
||||||
long bytes = paths.sum(0L) { path ->
|
} else {
|
||||||
java.nio.file.Files.isRegularFile(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)
|
File preserved = GameTestWorlds.preserve(dedicatedGameTestBuildDir, dedicatedGameTestDir)
|
||||||
? java.nio.file.Files.size(path) : 0L
|
if (preserved != null) logger.lifecycle('Preserved GameTest world for inspection at {}', preserved)
|
||||||
}
|
|
||||||
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) }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tasks.named('runGameTestServer').configure {
|
tasks.named('runGameTestServer').configure {
|
||||||
dependsOn(cleanOversizedGameTestWorld)
|
dependsOn(prepareGameTestWorld)
|
||||||
|
finalizedBy(finishGameTestWorld)
|
||||||
|
doLast {
|
||||||
|
if (!customGameTestRunDir) {
|
||||||
|
GameTestWorlds.check(dedicatedGameTestBuildDir, dedicatedGameTestDir)
|
||||||
|
java.nio.file.Files.createFile(gameTestSuccessMarker.toPath())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class GameTestWorlds {
|
||||||
|
static void check(File buildDir, File runDir) {
|
||||||
|
[buildDir, runDir, new File(runDir, 'world'), new File(runDir, 'failed-worlds')].each { path ->
|
||||||
|
if (java.nio.file.Files.isSymbolicLink(path.toPath())) {
|
||||||
|
throw new GradleException("Refusing to manage a symlinked GameTest path: ${path}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static File preserve(File buildDir, File runDir) {
|
||||||
|
File world = new File(runDir, 'world')
|
||||||
|
if (!world.exists()) return null
|
||||||
|
check(buildDir, runDir)
|
||||||
|
if (!world.isDirectory()) throw new GradleException("Expected a GameTest world directory: ${world}")
|
||||||
|
File failures = new File(runDir, 'failed-worlds')
|
||||||
|
java.nio.file.Files.createDirectories(failures.toPath())
|
||||||
|
String snapshot = java.time.format.DateTimeFormatter.ofPattern('yyyyMMdd-HHmmss-SSS')
|
||||||
|
.format(java.time.LocalDateTime.now()) + '-' + java.util.UUID.randomUUID()
|
||||||
|
File destination = new File(failures, snapshot)
|
||||||
|
java.nio.file.Files.move(world.toPath(), destination.toPath())
|
||||||
|
return destination
|
||||||
|
}
|
||||||
|
|
||||||
|
static void clean(File buildDir, File runDir) {
|
||||||
|
check(buildDir, runDir)
|
||||||
|
[new File(runDir, 'world'), new File(runDir, 'failed-worlds')].each { root ->
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sets up a dependency configuration called 'localRuntime'.
|
// Sets up a dependency configuration called 'localRuntime'.
|
||||||
|
|||||||
+15
-12
@@ -1,15 +1,15 @@
|
|||||||
# GameTest suites
|
# 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
|
cover core linking, deterministic Age definition, writing persistence, legacy
|
||||||
data migration, workstation transactions, and forged/replayed menu actions.
|
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
|
```shell
|
||||||
./gradlew runGameTestServer
|
./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
|
completed milestone details such as every Age terrain profile, Notebook and
|
||||||
Desk surface interactions, refill edge cases, book assembly controls, and
|
Desk surface interactions, refill edge cases, book assembly controls, and
|
||||||
workstation break/drop behavior. Run only the relevant archive alongside the
|
workstation break/drop behavior. Run only the relevant archive alongside the
|
||||||
@@ -17,11 +17,11 @@ core tests when investigating an issue:
|
|||||||
|
|
||||||
```shell
|
```shell
|
||||||
./gradlew runGameTestServer -ParchivedGameTestSuites=desk
|
./gradlew runGameTestServer -ParchivedGameTestSuites=desk
|
||||||
./gradlew runGameTestServer -ParchivedGameTestSuites=linking,binder
|
./gradlew runGameTestServer -ParchivedGameTestSuites=grammar,binder
|
||||||
```
|
```
|
||||||
|
|
||||||
Available suite names are `linking`, `writing`, `desk`, `binder`, `mixer`, and
|
Available suite names are `linking`, `writing`, `grammar`, `desk`, `binder`, `mixer`, and
|
||||||
`recipe`. Run all 64 Rivencraft tests (66 including NeoForge's two) before a
|
`recipe`. Run all 68 Rivencraft tests (70 including NeoForge's two) before a
|
||||||
release or after broad cross-system changes:
|
release or after broad cross-system changes:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
@@ -34,9 +34,12 @@ 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.
|
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
|
GameTest Ages are created in `build/gametest-run/world`, not in a development
|
||||||
client save. The Gradle task removes that **dedicated** world automatically if
|
client save. Every default GameTest invocation starts with a fresh world. If
|
||||||
it exceeds 512 MiB; override the threshold with `-PgameTestMaxWorldMiB=128`,
|
tests fail, Gradle moves the world under `build/gametest-run/failed-worlds/`
|
||||||
for example. Cleanup never targets a custom `-PgameTestRunDir` or a player
|
for inspection. A retry starts fresh but keeps those failed worlds; the next
|
||||||
world. A fresh test world can also help diagnose a slow or stalled worldgen
|
successful run removes them and its own world. A forcibly killed run may leave
|
||||||
run. The full suite should still be run before shipping changes in the
|
`world` behind; the next run preserves it as a failure snapshot before starting.
|
||||||
archived systems.
|
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.
|
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.
|
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,11 @@
|
|||||||
|
# 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. Age loading uses the frozen runtime profile and does not need the original symbol definition or runtime-profile JSON. Existing bound books without plans are not reinterpreted. Page-free and Link-Panel-only books keep the pre-existing random path. Biome, lighting, weather, celestial, and feature effects are retained in the plan but will be applied in issues #33–#35; instability remains Milestone 6 work.
|
||||||
+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.
|
# 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
|
mod_license=LGPL-3.0-or-later
|
||||||
# The mod version. Rivencraft uses the x.y.z.b policy documented in README.md.
|
# 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.3.0
|
||||||
immersive_portals_version=6.0.7
|
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.
|
# 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.
|
# This should match the base package used for the mod sources.
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ import java.util.List;
|
|||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import net.dnorberg.rivencraft.book.AgeReference;
|
import net.dnorberg.rivencraft.book.AgeReference;
|
||||||
import net.dnorberg.rivencraft.book.AgeRegistrySavedData;
|
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.item.PageItem;
|
||||||
import net.dnorberg.rivencraft.registry.ModBlockEntities;
|
import net.dnorberg.rivencraft.registry.ModBlockEntities;
|
||||||
import net.dnorberg.rivencraft.registry.ModDataComponents;
|
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.NotebookContents;
|
||||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||||
import net.dnorberg.rivencraft.writing.PageContent;
|
import net.dnorberg.rivencraft.writing.PageContent;
|
||||||
|
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||||
|
import net.dnorberg.rivencraft.writing.SymbolSemantics;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.core.HolderLookup;
|
import net.minecraft.core.HolderLookup;
|
||||||
import net.minecraft.core.NonNullList;
|
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
|
if (!page.isEmpty() && (!validPage(page) || !PageItem.isUsableWriting(page) || page.getCount() != 1
|
||||||
|| PageItem.content(page).kind() == PageContent.Kind.BLANK)) return false;
|
|| 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() {
|
public ItemStack previewBook() {
|
||||||
@@ -117,15 +173,9 @@ public final class BookBinderBlockEntity extends BlockEntity implements Containe
|
|||||||
pendingAgeId = UUID.randomUUID();
|
pendingAgeId = UUID.randomUUID();
|
||||||
setChanged();
|
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());
|
ItemStack book = new ItemStack(ModItems.DESCRIPTIVE_BOOK.get());
|
||||||
book.set(ModDataComponents.AGE_REFERENCE.get(), new AgeReference(pendingAgeId, title));
|
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));
|
book.set(DataComponents.CUSTOM_NAME, Component.literal(title));
|
||||||
return book;
|
return book;
|
||||||
}
|
}
|
||||||
@@ -135,7 +185,7 @@ public final class BookBinderBlockEntity extends BlockEntity implements Containe
|
|||||||
if (!canAssemble()) return false;
|
if (!canAssemble()) return false;
|
||||||
if (pendingAgeId == null) pendingAgeId = UUID.randomUUID();
|
if (pendingAgeId == null) pendingAgeId = UUID.randomUUID();
|
||||||
if (level instanceof ServerLevel serverLevel)
|
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);
|
items.get(COVER).shrink(1);
|
||||||
if (items.get(COVER).isEmpty()) items.set(COVER, ItemStack.EMPTY);
|
if (items.get(COVER).isEmpty()) items.set(COVER, ItemStack.EMPTY);
|
||||||
items.get(LINK_PANEL).shrink(1);
|
items.get(LINK_PANEL).shrink(1);
|
||||||
|
|||||||
@@ -16,12 +16,13 @@ public record AgeDefinition(
|
|||||||
long createdGameTime,
|
long createdGameTime,
|
||||||
ResourceLocation dimensionId,
|
ResourceLocation dimensionId,
|
||||||
BlockPos spawn,
|
BlockPos spawn,
|
||||||
AgeTraits traits
|
AgeTraits traits,
|
||||||
|
AgeGenerationPlan plan
|
||||||
) {
|
) {
|
||||||
public static final ResourceLocation RANDOM_VANILLA_PROFILE = ResourceLocation.fromNamespaceAndPath(
|
public static final ResourceLocation RANDOM_VANILLA_PROFILE = ResourceLocation.fromNamespaceAndPath(
|
||||||
Rivencraft.MOD_ID, "random_vanilla"
|
Rivencraft.MOD_ID, "random_vanilla"
|
||||||
);
|
);
|
||||||
public static final int CURRENT_GENERATION_VERSION = 13;
|
public static final int CURRENT_GENERATION_VERSION = 14;
|
||||||
|
|
||||||
public AgeDefinition {
|
public AgeDefinition {
|
||||||
Objects.requireNonNull(id, "id");
|
Objects.requireNonNull(id, "id");
|
||||||
@@ -29,6 +30,16 @@ public record AgeDefinition(
|
|||||||
Objects.requireNonNull(generationProfile, "generationProfile");
|
Objects.requireNonNull(generationProfile, "generationProfile");
|
||||||
Objects.requireNonNull(dimensionId, "dimensionId");
|
Objects.requireNonNull(dimensionId, "dimensionId");
|
||||||
Objects.requireNonNull(traits, "traits");
|
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) {
|
public static ResourceLocation dimensionId(UUID ageId) {
|
||||||
@@ -59,6 +70,6 @@ public record AgeDefinition(
|
|||||||
|
|
||||||
public AgeDefinition withSpawn(BlockPos spawn) {
|
public AgeDefinition withSpawn(BlockPos spawn) {
|
||||||
return new AgeDefinition(id, name, seed, generationProfile, generationVersion,
|
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 java.util.Collections;
|
||||||
import net.dnorberg.rivencraft.Rivencraft;
|
import net.dnorberg.rivencraft.Rivencraft;
|
||||||
import net.dnorberg.rivencraft.compat.ImmersivePortalsChunkLoaders;
|
import net.dnorberg.rivencraft.compat.ImmersivePortalsChunkLoaders;
|
||||||
|
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.core.GlobalPos;
|
import net.minecraft.core.GlobalPos;
|
||||||
import net.minecraft.core.Holder;
|
import net.minecraft.core.Holder;
|
||||||
@@ -73,7 +74,12 @@ public final class AgeDimensionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static Optional<LinkTarget> resolve(ServerPlayer player, AgeReference reference) {
|
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);
|
ServerLevel level = ensureLoaded(player.getServer(), definition);
|
||||||
if (level == null) {
|
if (level == null) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
@@ -261,7 +267,8 @@ public final class AgeDimensionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static ChunkGenerator createGenerator(MinecraftServer server, AgeDefinition age) {
|
private static ChunkGenerator createGenerator(MinecraftServer server, AgeDefinition age) {
|
||||||
AgeRuntimeProfile profile = AgeRuntimeProfiles.resolve(age.generationProfile());
|
AgeRuntimeProfile profile = age.plan() == null ? AgeRuntimeProfiles.resolve(age.generationProfile())
|
||||||
|
: age.plan().runtimeProfile();
|
||||||
if (profile.terrain() == AgeRuntimeProfile.Terrain.FLAT) {
|
if (profile.terrain() == AgeRuntimeProfile.Terrain.FLAT) {
|
||||||
return new FlatLevelSource(FlatLevelGeneratorSettings.getDefault(
|
return new FlatLevelSource(FlatLevelGeneratorSettings.getDefault(
|
||||||
server.registryAccess().lookupOrThrow(Registries.BIOME),
|
server.registryAccess().lookupOrThrow(Registries.BIOME),
|
||||||
@@ -385,7 +392,8 @@ public final class AgeDimensionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static DimensionType createDimensionType(MinecraftServer server, AgeDefinition age) {
|
private static DimensionType createDimensionType(MinecraftServer server, AgeDefinition age) {
|
||||||
AgeRuntimeProfile profile = AgeRuntimeProfiles.resolve(age.generationProfile());
|
AgeRuntimeProfile profile = age.plan() == null ? AgeRuntimeProfiles.resolve(age.generationProfile())
|
||||||
|
: age.plan().runtimeProfile();
|
||||||
DimensionType base = server.registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE)
|
DimensionType base = server.registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE)
|
||||||
.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, profile.dimensionType())).value();
|
.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, profile.dimensionType())).value();
|
||||||
AgeTraits.Lighting lighting = age.traits().lighting();
|
AgeTraits.Lighting lighting = age.traits().lighting();
|
||||||
|
|||||||
@@ -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;
|
package net.dnorberg.rivencraft.book;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.List;
|
||||||
import net.dnorberg.rivencraft.Rivencraft;
|
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.core.BlockPos;
|
||||||
import net.minecraft.gametest.framework.GameTest;
|
import net.minecraft.gametest.framework.GameTest;
|
||||||
import net.minecraft.gametest.framework.GameTestHelper;
|
import net.minecraft.gametest.framework.GameTestHelper;
|
||||||
@@ -18,6 +22,54 @@ public final class AgePersistenceGameTests {
|
|||||||
private 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")
|
@GameTest(template = "empty")
|
||||||
public static void everyTraitCombinationRoundTripsWithoutRerolling(GameTestHelper helper) {
|
public static void everyTraitCombinationRoundTripsWithoutRerolling(GameTestHelper helper) {
|
||||||
ListTag entries = new ListTag();
|
ListTag entries = new ListTag();
|
||||||
@@ -89,6 +141,8 @@ public final class AgePersistenceGameTests {
|
|||||||
"Definitions predating named dimensions must retain the UUID-derived dimension");
|
"Definitions predating named dimensions must retain the UUID-derived dimension");
|
||||||
helper.assertValueEqual(definition.traits(), AgeTraits.LEGACY_DEFAULTS,
|
helper.assertValueEqual(definition.traits(), AgeTraits.LEGACY_DEFAULTS,
|
||||||
"Definitions predating traits must receive stable 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());
|
CompoundTag serialized = migrated.save(new CompoundTag(), helper.getLevel().registryAccess());
|
||||||
AgeDefinition reloaded = AgeRegistrySavedData.load(serialized, 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.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.core.HolderLookup;
|
import net.minecraft.core.HolderLookup;
|
||||||
import net.minecraft.nbt.CompoundTag;
|
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_Y_TAG = "SpawnY";
|
||||||
private static final String SPAWN_Z_TAG = "SpawnZ";
|
private static final String SPAWN_Z_TAG = "SpawnZ";
|
||||||
private static final String TRAITS_TAG = "Traits";
|
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 BIOME_DISTRIBUTION_TAG = "BiomeDistribution";
|
||||||
private static final String LIGHTING_TAG = "Lighting";
|
private static final String LIGHTING_TAG = "Lighting";
|
||||||
private static final String WEATHER_TAG = "Weather";
|
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. */
|
/** Resolves a book identity, creating its deterministic random definition exactly once. */
|
||||||
public static AgeDefinition resolveOrCreate(ServerLevel level, AgeReference reference) {
|
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();
|
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) {
|
public Optional<AgeDefinition> find(UUID ageId) {
|
||||||
@@ -78,7 +84,8 @@ public final class AgeRegistrySavedData extends SavedData {
|
|||||||
return updated;
|
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());
|
AgeDefinition existing = ages.get(reference.id());
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
return existing;
|
return existing;
|
||||||
@@ -87,16 +94,19 @@ public final class AgeRegistrySavedData extends SavedData {
|
|||||||
String name = normalizedName(reference.name());
|
String name = normalizedName(reference.name());
|
||||||
ResourceLocation dimensionId = availableDimensionId(name);
|
ResourceLocation dimensionId = availableDimensionId(name);
|
||||||
long seed = ageSeed(worldSeed, dimensionId);
|
long seed = ageSeed(worldSeed, dimensionId);
|
||||||
|
ResourceLocation seedProfile = AgeRuntimeProfiles.select(seed);
|
||||||
|
AgeGenerationPlan plan = AgeGenerationPlan.compile(writing, seed, seedProfile);
|
||||||
AgeDefinition created = new AgeDefinition(
|
AgeDefinition created = new AgeDefinition(
|
||||||
reference.id(),
|
reference.id(),
|
||||||
name,
|
name,
|
||||||
seed,
|
seed,
|
||||||
AgeRuntimeProfiles.select(seed),
|
plan == null || plan.authoredTerrain() == null ? seedProfile : plan.authoredTerrain(),
|
||||||
AgeDefinition.CURRENT_GENERATION_VERSION,
|
AgeDefinition.CURRENT_GENERATION_VERSION,
|
||||||
createdGameTime,
|
createdGameTime,
|
||||||
dimensionId,
|
dimensionId,
|
||||||
null,
|
null,
|
||||||
AgeTraits.select(seed)
|
AgeTraits.select(seed),
|
||||||
|
plan
|
||||||
);
|
);
|
||||||
ages.put(created.id(), created);
|
ages.put(created.id(), created);
|
||||||
setDirty();
|
setDirty();
|
||||||
@@ -138,7 +148,9 @@ public final class AgeRegistrySavedData extends SavedData {
|
|||||||
entry.getLong(CREATED_TIME_TAG),
|
entry.getLong(CREATED_TIME_TAG),
|
||||||
dimensionId,
|
dimensionId,
|
||||||
spawn,
|
spawn,
|
||||||
readTraits(entry)
|
readTraits(entry),
|
||||||
|
entry.contains(PLAN_TAG, CompoundTag.TAG_COMPOUND)
|
||||||
|
? AgeGenerationPlan.load(entry.getCompound(PLAN_TAG)) : null
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
@@ -171,6 +183,7 @@ public final class AgeRegistrySavedData extends SavedData {
|
|||||||
traits.putFloat(CELESTIAL_ANGLE_TAG, age.traits().celestialAngle());
|
traits.putFloat(CELESTIAL_ANGLE_TAG, age.traits().celestialAngle());
|
||||||
traits.putFloat(CELESTIAL_PHASE_TAG, age.traits().celestialPhase());
|
traits.putFloat(CELESTIAL_PHASE_TAG, age.traits().celestialPhase());
|
||||||
entry.put(TRAITS_TAG, traits);
|
entry.put(TRAITS_TAG, traits);
|
||||||
|
if (age.plan() != null) entry.put(PLAN_TAG, age.plan().save());
|
||||||
serializedAges.add(entry);
|
serializedAges.add(entry);
|
||||||
});
|
});
|
||||||
tag.put(AGES_TAG, serializedAges);
|
tag.put(AGES_TAG, serializedAges);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package net.dnorberg.rivencraft.client.screen;
|
package net.dnorberg.rivencraft.client.screen;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
import net.dnorberg.rivencraft.Rivencraft;
|
import net.dnorberg.rivencraft.Rivencraft;
|
||||||
import net.dnorberg.rivencraft.block.entity.BookBinderBlockEntity;
|
import net.dnorberg.rivencraft.block.entity.BookBinderBlockEntity;
|
||||||
import net.dnorberg.rivencraft.item.PageItem;
|
import net.dnorberg.rivencraft.item.PageItem;
|
||||||
@@ -32,6 +33,7 @@ public final class BookBinderScreen extends AbstractContainerScreen<BookBinderMe
|
|||||||
|
|
||||||
private EditBox titleInput;
|
private EditBox titleInput;
|
||||||
private int firstVisible;
|
private int firstVisible;
|
||||||
|
private int lastGrammarErrorStripIndex = -1;
|
||||||
private boolean stripClickPendingRelease;
|
private boolean stripClickPendingRelease;
|
||||||
|
|
||||||
public BookBinderScreen(BookBinderMenu menu, Inventory inventory, Component title) {
|
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) {
|
@Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) {
|
||||||
super.render(graphics, mouseX, mouseY, partialTick);
|
super.render(graphics, mouseX, mouseY, partialTick);
|
||||||
firstVisible = Math.min(firstVisible, maxFirstVisible());
|
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,
|
graphics.enableScissor(leftPos + STRIP_X + 8, topPos + STRIP_Y,
|
||||||
leftPos + STRIP_X + STRIP_WIDTH - 8, topPos + STRIP_Y + STRIP_HEIGHT);
|
leftPos + STRIP_X + STRIP_WIDTH - 8, topPos + STRIP_Y + STRIP_HEIGHT);
|
||||||
int count = visiblePageCount();
|
int count = visiblePageCount();
|
||||||
@@ -97,6 +106,16 @@ public final class BookBinderScreen extends AbstractContainerScreen<BookBinderMe
|
|||||||
}
|
}
|
||||||
graphics.disableScissor();
|
graphics.disableScissor();
|
||||||
drawScrollEnds(graphics);
|
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 (mouseY >= topPos + STRIP_Y && mouseY < topPos + STRIP_Y + STRIP_HEIGHT) {
|
||||||
if (firstVisible > 0 && mouseX >= leftPos + STRIP_X && mouseX < leftPos + STRIP_X + 8)
|
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);
|
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;
|
return;
|
||||||
}
|
}
|
||||||
int hovered = pageIndexAt(mouseX, mouseY);
|
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);
|
graphics.renderTooltip(font, pageAtIndex(hovered), mouseX, mouseY);
|
||||||
else renderTooltip(graphics, 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),
|
case SYMBOL, UNRESOLVED_SYMBOL -> graphics.blit(NotebookScreen.symbolTexture(page),
|
||||||
x + 1, y + 5, 24, 24, 0, 0, 128, 128, 128, 128);
|
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) {
|
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.NotebookContents;
|
||||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||||
import net.dnorberg.rivencraft.writing.SymbolReference;
|
import net.dnorberg.rivencraft.writing.SymbolReference;
|
||||||
|
import net.dnorberg.rivencraft.writing.SymbolCatalog;
|
||||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.gametest.framework.GameTest;
|
import net.minecraft.gametest.framework.GameTest;
|
||||||
@@ -86,12 +87,41 @@ public final class BookBinderGameTests {
|
|||||||
restored.loadWithComponents(saved, helper.getLevel().registryAccess());
|
restored.loadWithComponents(saved, helper.getLevel().registryAccess());
|
||||||
helper.assertValueEqual(PageItem.content(restored.getItem(BookBinderBlockEntity.FIRST_PAGE))
|
helper.assertValueEqual(PageItem.content(restored.getItem(BookBinderBlockEntity.FIRST_PAGE))
|
||||||
.symbol().orElseThrow(), missing, "Reload must preserve the removed data-pack symbol ID");
|
.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()),
|
helper.assertTrue(restored.getItem(BookBinderBlockEntity.FIRST_PAGE).is(ModItems.PAGE.get()),
|
||||||
"Rejected writing must remain recoverable as a Page");
|
"Rejected writing must remain recoverable as a Page");
|
||||||
helper.succeed();
|
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) {
|
public static void assemblyIsAtomicAndRetainsPageOrder(GameTestHelper helper) {
|
||||||
BookBinderBlockEntity binder = place(helper);
|
BookBinderBlockEntity binder = place(helper);
|
||||||
binder.setTitle("A New Age");
|
binder.setTitle("A New Age");
|
||||||
|
|||||||
@@ -47,6 +47,11 @@ public final class CoreGameTests {
|
|||||||
WritingDataGameTests.semanticSchemaIsServerOnlyBoundedAndV1Compatible(helper);
|
WritingDataGameTests.semanticSchemaIsServerOnlyBoundedAndV1Compatible(helper);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GameTest(template = "empty")
|
||||||
|
public static void orderedWritingGrammar(GameTestHelper helper) {
|
||||||
|
WritingGrammarGameTests.orderedGrammarAcceptsPartialWritingAndDiagnosesInvalidSequences(helper);
|
||||||
|
}
|
||||||
|
|
||||||
@GameTest(template = "empty")
|
@GameTest(template = "empty")
|
||||||
public static void notebookPersistence(GameTestHelper helper) {
|
public static void notebookPersistence(GameTestHelper helper) {
|
||||||
WritingDataGameTests.notebookContentsPreserveOrderGapsNamesAndUnknownPages(helper);
|
WritingDataGameTests.notebookContentsPreserveOrderGapsNamesAndUnknownPages(helper);
|
||||||
@@ -82,6 +87,11 @@ public final class CoreGameTests {
|
|||||||
BookBinderGameTests.assemblyIsAtomicAndRetainsPageOrder(helper);
|
BookBinderGameTests.assemblyIsAtomicAndRetainsPageOrder(helper);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GameTest(template = "empty")
|
||||||
|
public static void binderRejectsConflictingGrammar(GameTestHelper helper) {
|
||||||
|
BookBinderGameTests.conflictingGrammarKeepsBinderInputsRecoverable(helper);
|
||||||
|
}
|
||||||
|
|
||||||
@GameTest(template = "empty")
|
@GameTest(template = "empty")
|
||||||
public static void binderRejectsForgedAndReplayedActions(GameTestHelper helper) {
|
public static void binderRejectsForgedAndReplayedActions(GameTestHelper helper) {
|
||||||
BookBinderGameTests.forgedBinderActionsAndReplayedOutputCannotDuplicateBook(helper);
|
BookBinderGameTests.forgedBinderActionsAndReplayedOutputCannotDuplicateBook(helper);
|
||||||
|
|||||||
@@ -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,10 +1,12 @@
|
|||||||
package net.dnorberg.rivencraft.menu;
|
package net.dnorberg.rivencraft.menu;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
import net.dnorberg.rivencraft.block.entity.BookBinderBlockEntity;
|
import net.dnorberg.rivencraft.block.entity.BookBinderBlockEntity;
|
||||||
import net.dnorberg.rivencraft.item.PageItem;
|
import net.dnorberg.rivencraft.item.PageItem;
|
||||||
import net.dnorberg.rivencraft.registry.ModItems;
|
import net.dnorberg.rivencraft.registry.ModItems;
|
||||||
import net.dnorberg.rivencraft.registry.ModMenus;
|
import net.dnorberg.rivencraft.registry.ModMenus;
|
||||||
import net.dnorberg.rivencraft.writing.PageContent;
|
import net.dnorberg.rivencraft.writing.PageContent;
|
||||||
|
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
import net.minecraft.world.Container;
|
import net.minecraft.world.Container;
|
||||||
import net.minecraft.world.SimpleContainer;
|
import net.minecraft.world.SimpleContainer;
|
||||||
@@ -32,6 +34,8 @@ public final class BookBinderMenu extends AbstractContainerMenu {
|
|||||||
private final SimpleContainer result = new SimpleContainer(1);
|
private final SimpleContainer result = new SimpleContainer(1);
|
||||||
private final boolean clientSide;
|
private final boolean clientSide;
|
||||||
private int selectedPage = -1;
|
private int selectedPage = -1;
|
||||||
|
private int grammarErrorCode = -1;
|
||||||
|
private int grammarErrorStripIndex = -1;
|
||||||
|
|
||||||
public BookBinderMenu(int id, Inventory inventory, RegistryFriendlyByteBuf data) {
|
public BookBinderMenu(int id, Inventory inventory, RegistryFriendlyByteBuf data) {
|
||||||
this(id, inventory, inventory.player.level().getBlockEntity(data.readBlockPos())
|
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 int get() { return selectedPage; }
|
||||||
@Override public void set(int value) { selectedPage = value; }
|
@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.COVER, 8, 27, 64));
|
||||||
addSlot(new BinderSlot(BookBinderBlockEntity.LINK_PANEL, -1000, -1000, 1));
|
addSlot(new BinderSlot(BookBinderBlockEntity.LINK_PANEL, -1000, -1000, 1));
|
||||||
addSlot(new BinderSlot(BookBinderBlockEntity.NOTEBOOK, -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 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 String title() { return binder == null ? "" : binder.title(); }
|
||||||
public boolean setTitle(Player player, String title) {
|
public boolean setTitle(Player player, String title) {
|
||||||
if (clientSide || !stillValid(player) || title == null
|
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.AgeReference;
|
||||||
import net.dnorberg.rivencraft.book.AgeRegistrySavedData;
|
import net.dnorberg.rivencraft.book.AgeRegistrySavedData;
|
||||||
import net.dnorberg.rivencraft.book.AgeDimensionService;
|
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.block.entity.BookStandBlockEntity;
|
||||||
import net.dnorberg.rivencraft.client.ClientLinkPreviewHandler;
|
import net.dnorberg.rivencraft.client.ClientLinkPreviewHandler;
|
||||||
import net.dnorberg.rivencraft.client.ClientBookInteractionHandler;
|
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.SymbolCatalog;
|
||||||
import net.dnorberg.rivencraft.writing.SymbolDisplayMetadata;
|
import net.dnorberg.rivencraft.writing.SymbolDisplayMetadata;
|
||||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||||
|
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||||
import net.minecraft.core.component.DataComponents;
|
import net.minecraft.core.component.DataComponents;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.core.GlobalPos;
|
import net.minecraft.core.GlobalPos;
|
||||||
@@ -133,10 +136,28 @@ public final class ModNetworking {
|
|||||||
return;
|
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());
|
WRITING_BOOKS.add(access.stack());
|
||||||
try {
|
try {
|
||||||
AgeReference reference = new AgeReference(UUID.randomUUID(), title);
|
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);
|
player.displayClientMessage(Component.translatable("message.rivencraft.descriptive_book.unavailable"), true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.previous_pages": "Scroll pages left (Left Arrow)",
|
||||||
"screen.rivencraft.book_binder.next_pages": "Scroll pages right (Right 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.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.ink": "Ink: %s/%s",
|
||||||
"screen.rivencraft.writing_desk.search": "Search",
|
"screen.rivencraft.writing_desk.search": "Search",
|
||||||
"screen.rivencraft.writing_desk.sort": "Sort pages by name (A–Z)",
|
"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.unwritten": "This Descriptive Book is unwritten",
|
||||||
"message.rivencraft.descriptive_book.created": "Created Age: %s",
|
"message.rivencraft.descriptive_book.created": "Created Age: %s",
|
||||||
"message.rivencraft.descriptive_book.unavailable": "That Age is unavailable",
|
"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.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_first": "Linked to %s — a Return Link was created",
|
||||||
"message.rivencraft.descriptive_book.linked": "Linked to %s",
|
"message.rivencraft.descriptive_book.linked": "Linked to %s",
|
||||||
|
|||||||
Reference in new issue
Block a user