Compare commits

...
7 Commits
Author SHA1 Message Date
dnorberg dd219bb58a Completed issue 71 and allowed village pages to be placed in illegal biomes adding +100 instability
Build / build (push) Canceled after 0s
2026-10-10 03:41:16 -04:00
dnorberg b48cc8a6ce Align instability documentation with current runtime (#74)
Build / build (push) Canceled after 0s
2026-10-10 02:07:04 -04:00
dnorberg 779699d7a9 Port bounded meteor, burning, and erosion effects (#70)
Build / build (push) Canceled after 0s
2026-10-09 14:59:08 -04:00
dnorberg 33b9bde302 Add Legacy-rate bounded Age lightning and explosions (#69)
Build / build (push) Canceled after 0s
2026-10-09 13:16:46 -04:00
dnorberg a9a8b3cdd5 Port bounded colored decay and align Legacy defaults (#68)
Build / build (push) Canceled after 0s
2026-10-09 12:56:30 -04:00
dnorberg 066ef2b758 Implement Legacy-inspired Age status instability effects (#67)
Build / build (push) Canceled after 0s
2026-10-09 04:13:55 -04:00
dnorberg 8b32735c2e Add bounded per-Age instability provider runtime (#66)
Build / build (push) Canceled after 0s
2026-10-09 01:56:39 -04:00
69 changed files with 3090 additions and 76 deletions

No files matched your search

+7 -3
View File
@@ -8,9 +8,13 @@ The bootstrap, books/linking, Ages, writing-system, and Age-grammar milestones a
The writing system uses a data-pack symbol catalog and persistent The writing system uses a data-pack symbol catalog and persistent
ordered-writing model. Linking Books and Descriptive Books create persistent ordered-writing model. Linking Books and Descriptive Books create persistent
Ages from either authored supported symbols or seeded random completion. Ages from either authored supported symbols or seeded random completion.
Instability and the remaining unsupported Legacy symbol effects have not been Milestone 6 instability work is in progress: Ages persist frozen instability
ported yet. The [Milestone 5 acceptance record](docs/MILESTONE_5_ACCEPTANCE.md) scores and provider plans, and the bounded runtime implements status effects,
lists the supported grammar, optional integrations, and limits. colored decay, lightning, explosions, meteors, burning, and erosion. The
[Milestone 5 acceptance record](docs/MILESTONE_5_ACCEPTANCE.md) lists the
supported grammar, optional integrations, and limits; the
[instability runtime policy](docs/INSTABILITY_RUNTIME.md) records the current
effects and modern safety boundaries.
Milestone 4 now includes stackable blank Pages plus server-created symbol, Milestone 4 now includes stackable blank Pages plus server-created symbol,
unresolved-symbol, and baseline link-panel states. Page visuals follow the unresolved-symbol, and baseline link-panel states. Page visuals follow the
+7
View File
@@ -0,0 +1,7 @@
# Age arrival cloud platform
Newly created Ages now place a 5×5 solid cloud platform instead of cobblestone at their saved spawn. The block has full collision, passes skylight, renders translucently, has no loot table, and cannot be obtained with pick-block. Existing Ages retain their already-placed platform; this change does not overwrite a player's saved world.
The block texture is `assets/rivencraft/textures/block/cloud_platform.png`, verified at exactly 16×16 RGBA. Legacy's supplied assets contain no cloud-block texture, so this one was generated with the built-in image tool, then reduced by nearest-neighbor sampling. The final prompt requested a seamless Minecraft block-face pixel-art tile with 2–3 chunky white, icy-blue, and powder-blue cloud swirls, genuine transparent holes between them, strong 16×16-scale contrast, and no background or text.
The separate [decay provider](INSTABILITY_DECAY.md) protects the saved spawn area by position, so its protection remains in force regardless of the platform's material.
+1 -1
View File
@@ -199,7 +199,7 @@ eligible biomes for Tiled/Grid and Tiny–Huge. The eligible pool comes from the
terrain's biome preset, or `#rivencraft:cave_biomes` for Cave terrain, so future terrain's biome preset, or `#rivencraft:cave_biomes` for Cave terrain, so future
biome integrations can expand it without changing the count rule. Single uses biome integrations can expand it without changing the count rule. Single uses
one; Native uses its preset biome pool. This random-age maximum does not truncate one; Native uses its preset biome pool. This random-age maximum does not truncate
authored pages: the Binder's 27 symbol-page positions bound an authored book. authored pages: the Binder's 252 symbol-page positions bound an authored book. Legacy's Binder itself had no explicit page-count check; this remains a fixed-slot storage ceiling.
Native cannot be paired with explicit biome pages. Legacy filled Tiny–Huge to Native cannot be paired with explicit biome pages. Legacy filled Tiny–Huge to
three; Rivencraft deliberately uses two so a pair of written biome pages stays three; Rivencraft deliberately uses two so a pair of written biome pages stays
exactly as written. exactly as written.
+1
View File
@@ -28,6 +28,7 @@ project's GNU LGPL v3 license. Rivencraft itself uses the same license.
| `assets/rivencraft/textures/block/{small,medium,large}_crystal_bud.png`, `crystal_cluster.png` | Minecraft 1.21.1 `textures/block/{small,medium,large}_amethyst_bud.png`, `amethyst_cluster.png` | Minecraft 1.21.1 | Original 16×16 alpha masks and silhouettes preserved; hue shifted toward Legacy blue, with brighter saturation; exported as 8-bit RGBA (not indexed PNG) | | `assets/rivencraft/textures/block/{small,medium,large}_crystal_bud.png`, `crystal_cluster.png` | Minecraft 1.21.1 `textures/block/{small,medium,large}_amethyst_bud.png`, `amethyst_cluster.png` | Minecraft 1.21.1 | Original 16×16 alpha masks and silhouettes preserved; hue shifted toward Legacy blue, with brighter saturation; exported as 8-bit RGBA (not indexed PNG) |
| `assets/rivencraft/textures/item/crystal_shard.png` | Original sprite generated with OpenAI ImageGen from the Legacy crystal palette | 2026-10-05 | Cropped and nearest-neighbor scaled to 16×16 | | `assets/rivencraft/textures/item/crystal_shard.png` | Original sprite generated with OpenAI ImageGen from the Legacy crystal palette | 2026-10-05 | Cropped and nearest-neighbor scaled to 16×16 |
| `assets/rivencraft/sounds/linking/link-fissure.ogg` | `assets/mystcraft/sounds/linking/link-fissure.ogg` | Legacy 0.13.7.06 local extraction | Namespace/path rename only; plays when a Star Fissure returns an entity home | | `assets/rivencraft/sounds/linking/link-fissure.ogg` | `assets/mystcraft/sounds/linking/link-fissure.ogg` | Legacy 0.13.7.06 local extraction | Namespace/path rename only; plays when a Star Fissure returns an entity home |
| `assets/rivencraft/sounds/entity/meteor/roar.ogg` | `assets/mystcraft/sounds/entity/meteor/roar.ogg` | Legacy 0.13.7.06 local extraction | Byte-identical copy under the Rivencraft namespace; plays during the bounded meteor descent |
Mystcraft Legacy identifies XCompWiz as its project developer and includes the Mystcraft Legacy identifies XCompWiz as its project developer and includes the
full LGPL v3 text in its root `LICENSE` file. Rivencraft's root `LICENSE` full LGPL v3 text in its root `LICENSE` file. Rivencraft's root `LICENSE`
+13
View File
@@ -0,0 +1,13 @@
# Colored decay (Milestone 6, issue #68)
Legacy defines seven decay block-state colors and has a texture/model for every one: black, red, green, blue, purple, yellow, and white. That does not mean all seven are active instability hazards. Its active provider deck registers blue, purple, red, and white. Black has a decay handler and provider class, but its provider registration is commented out; green and yellow have visual states without registered spread handlers. Rivencraft currently implements the four active provider colors. Their 16×16 textures are exact copies of the local Mystcraft 1.12.2-0.13.7.06 assets at `assets/mystcraft/textures/blocks/decay_{blue,purple,red,white}.png`. Legacy's `blockdecay.json` and `blockdecay_*.json` map these to cube-all models; Rivencraft uses the same mapping.
The local Legacy bytecode (`EffectDecayBasic`, `DecayHandlerSpreading`, and the four color handlers) seeds decay in a chunk, then spreads to six neighbors. Blue prefers softer blocks, red uses explosion resistance, purple is slower, and white converts almost anything and damages entities on contact. Rivencraft preserves the four colors, six-neighbor growth, relative conversion tendencies, and white contact damage. It adapts the exact difficulty formulas to modern block hardness and safety checks; fluids are not replaced, and provider attempts are deterministic from the Age seed and persisted attempt counter.
Decay requires both `instability.world_mutation=true` and `instability_decay.enabled=true` in the server config. Both now default to true, matching Legacy's enabled-by-default Age instability and provider registration. Existing config files retain their saved values, including `false`; change them explicitly to opt in after updating an existing installation. At most `instability_decay.max_attempts_per_call` neighbors (default four) are examined, each within radius one, and at most one block can be replaced per provider run. The shared Age action budget may lower that further. Only chunks already loaded and supplied by the scheduler are touched; no cross-dimension or force-loading path exists. A per-Age `rivencraft_decay` saved data file stores a bounded frontier (1024 positions per color) and attempt counter. Disabling decay stops seeding, spreading, and white contact damage; existing blocks remain so re-enabling can resume.
Decay rejects the saved Age spawn and its nearby 5×5 arrival platform (with a two-block margin), block entities, fluids, unbreakable blocks, vanilla portal/command/structure infrastructure, blocks in `#minecraft:portals`, all non-decay Rivencraft blocks, and blocks in `#rivencraft:decay_protected`. Data packs can append other mods' protected blocks to that tag. A fake-player break event is posted before replacement, and a placement event after it; a cancellation prevents or restores the change. As with other fake-player automation, protection mods need to handle NeoForge block events for this safeguard to apply.
GameTests cover persistence, frontier deduplication, selected-chunk limits, and Overworld isolation. A real-client check should enable both settings in a disposable Age, observe growth, leave/reload that Age, then disable decay and verify growth stops. Also test a claim-protected block and a block entity if a protection mod is installed.
For current test builds, an operator standing in an Age can use `/rivencraft age decay pulse white 32` (or `blue`, `purple`, `red`). This performs at most 32 budgeted provider calls in the player's already-loaded chunk and reports how many blocks converted. It does not edit the saved Age plan or instability score. Repeat the command to observe spread, leave/reload the Age to check persistence, then disable decay and confirm the command refuses to act. This test hook remains useful because the provisional authored-page scoring does not yet provide a reliable route to the Legacy eating deck's 15,000-point gate.
+15
View File
@@ -0,0 +1,15 @@
# Environmental instability (#70)
The local Mystcraft Legacy 0.13.7.06 bytecode was audited for `EffectMeteor`, `EntityMeteor`, `EffectScorched`, `EffectErosion`, and their providers. The active deck registers `meteors` in destructive and `burning` (scorching) in harsh. Erosion's provider is present in bytecode but not registered in the active deck. Its old chunk-population lake routines are not run at Age creation in Rivencraft; ordinary authored lake features already own generation. The old erosion tick spread a neighboring water/lava or Forge fluid block into a random non-liquid position, excluding downward neighbors and block containers.
Rivencraft keeps the active `meteors` and `burning` provider IDs in frozen Age plans. Erosion does not become a deck card. For this test slice, `instability_erosion.enabled` defaults **on** as an explicit adaptation requested by the user. It runs only in Ages whose frozen instability score reaches the destructive deck threshold (10,000), and may be disabled independently. Existing Age plans are not rerolled.
Legacy's meteor spawned at Y=500, fell as a custom entity, broke blocks along its path, and made multiple large explosions on impact. Modern Ages can have different build heights and dynamic dimensions. Rivencraft instead records one bounded active descent per Age (16 globally), starting no more than 48 blocks above the loaded surface. Server particles show the trajectory and the byte-identical Legacy `entity/meteor/roar.ogg` plays near the impact. A single strength-3 impact reuses the capped explosion/protection hooks from #69. There is no persistent projectile entity or custom model; stopping/unloading a dimension cancels a descent rather than replaying it on restart. The saved per-Age attempt sequence and cooldown prevent immediate repeated rolls. The adaptation is intentionally less destructive than Legacy's chain of explosions.
Scorching checks at most eight loaded chunks and eight living-entity candidates per chunk per scheduler pass, igniting at most the configured target count. Targets must be open to sky; survival/adventure players are included by default as in Legacy, while creative/spectator players and spawn safety positions are excluded. Fire duration is four seconds per provider level, capped at twelve seconds. This affects entities, not blocks, and does not request distant chunks.
Erosion inspects at most eight already-loaded candidate positions per pass and can replace at most one safe block with an adjacent source fluid. It excludes block entities, protected/critical Rivencraft blocks, portals, spawn safety positions, and unloaded neighboring chunks. Break and place events with a fake player permit claim/protection hooks to veto a change; rejected placement is rolled back. World mutation and `mobGriefing` must also be enabled. The modern Y range is taken from the Age level rather than Legacy's fixed 0–127 sample.
The server config has independent meteor enable/block damage/player damage/fire/caps, scorching enable/player targeting/cap, and erosion enable switches. Meteor frequency preserves Legacy's 1/50,000 chance per chunk-tick across nearby loaded chunks, capped to one active descent per Age. Visual/audio effects still run when meteor block damage is disabled. No client-only class is loaded on a dedicated server. The reused roar sound is recorded in [asset provenance](ASSET_PROVENANCE.md); Legacy has no separate meteor texture in the supplied asset tree.
Operator checks in a loaded, sufficiently unstable Age: `/rivencraft age environment pulse meteor` starts one protected descent (200-tick cooldown), `/rivencraft age environment pulse burning` ignites the issuing survival player only when open to sky and outside spawn protection, and `/rivencraft age environment pulse erosion` converts the block being looked at if a source fluid touches its side or top. The burning test reports when rain or water would immediately extinguish the fire. Place water or lava next to a plain stone block and aim at the stone to test erosion. These commands refuse to run in the Overworld and still honor enable switches, protection hooks, and world-mutation policy. Natural meteor occurrence is intentionally rare, as in Legacy.
+19
View File
@@ -0,0 +1,19 @@
# Instability provider runtime (Milestone 6, issue #66)
Each new Age stores an `InstabilityPlan` beside its frozen `Instability` score. The version-1 plan contains provider IDs and levels. Selection uses the saved score rounded down to a 500-point step and the Age seed. It independently walks Legacy's basic, harsh, destructive, eating, and death decks with their audited entry costs (0, 2,500, 10,000, 15,000, 20,000), shuffling each deck deterministically before paying its weighted card costs. The source card weights and default provider costs are copied from the user's local Mystcraft 0.13.7.06 `InstabilityData` class. This preserves Legacy's multiple-deck behavior, but does not claim byte-for-byte reproduction of its historical Java RNG state, difficulty multiplier, config overrides, or 400-chunk block profiling delay.
The saved provider IDs are independent of installed handlers. A missing optional handler leaves its ID and level intact and is skipped at runtime. A syntactically invalid saved ID or unsupported plan version fails loading explicitly; an unknown but valid ID is preserved and logged once when encountered. Disabling instability or world mutation never rewrites a saved score or provider plan. Saves from #64 with a frozen score but no provider plan are selected once from that score and Age seed, then marked dirty for persistence. Older pre-score Ages remain neutral and inert.
The server scheduler runs only for loaded `rivencraft:age/*` levels with a player present and an Age definition. It uses only chunks already loaded near those players, never requests a chunk, and rotates among eligible Ages when the per-tick cap is reached. Configuration bounds the cooldown (minimum 20 ticks), active Ages, handlers and actions per Age, effective provider level, and examined loaded chunks. A handler must claim a shared action permit before each effect. A throwing handler is logged and quarantined temporarily without stopping the server. World-mutating handlers are enabled by default to match Legacy; the setting can still disable them. These limits are guards for upcoming providers, not proof that an arbitrary third-party handler cannot misuse world APIs.
Issue #67 registers the non-world-mutating potion handlers; see [status-effect policy](INSTABILITY_STATUS_EFFECTS.md). Issue #68 adds configurable [colored decay](INSTABILITY_DECAY.md), enabled by default for newly generated configs. Issue #69 adds lightning and explosions; issue #70 adds [meteor, scorching, and erosion](INSTABILITY_ENVIRONMENTAL.md). The runtime rejects Overworld and preview dimension IDs; its player requirement excludes unattended snapshot chunk loaders. GameTests cover deterministic selection, save round-trips, score-only migration, unknown IDs, scope checks, fair admission, and action caps.
# Lightning and explosions (#69)
The `lightning` and `explosions` cards now run only in loaded Rivencraft Ages with players. Legacy rolled once per chunk per tick: explosions at 1/1000 and lightning at 1/5000 during thunder or 1/100000 otherwise. Each selected hazard card gets an independent roll every scheduler pass, rather than waiting for the rotating two-provider sample. The roll uses up to 81 already-loaded chunks near Age players and the exact probability of at least one Legacy opportunity over that many chunk-ticks. It permits at most one event per hazard type per pass. A per-Age saved sequence and last-event time prevent the same roll/event from replaying after a restart. Lightning also skips an existing bolt at the target.
Legacy used a real lightning bolt and a flaming, block-damaging strength-3 explosion. Both remain enabled by default. Unlike Legacy, the bolt is visual-only and its damage/fire are applied through separate bounded paths. The explosion uses NeoForge's normal explosion hooks plus break-event checks, with a calculator that restricts destruction to one already-loaded chunk, protects spawn, block entities, portals, decay-protected blocks and Rivencraft infrastructure, and caps affected blocks and entity damage. The visual/audio explosion still occurs when griefing is disabled. `mobGriefing` and `doFireTick` gate block changes and ignition; survival/adventure player damage is separately configurable. These are deliberate modern server-safety differences from Legacy.
Server config `instability_hazards` controls enablement, block damage, player damage, fire, interval, maximum nearby loaded chunks, maximum destroyed blocks, damaged entities, damage per entity, and explosion radius. `instability.world_mutation=false` also suppresses block damage and fire without suppressing visuals or entity damage. No hazard is dispatched into preview, Overworld, or another Age.
For an operator smoke test inside an Age, `/rivencraft age hazard pulse lightning` and `/rivencraft age hazard pulse explosion` force one event in a safe loaded chunk. They still honor the Age scope, enable switch, cooldown, spawn exclusion, game rules and damage policies. Repeat after `minimum_gap_ticks` (default 20 ticks); run the same command in the Overworld to verify that it refuses to fire. The earlier 200-tick `min_interval_ticks` test key is retired; existing configs receive the new default when NeoForge corrects them.
+4 -2
View File
@@ -2,8 +2,10 @@
Every newly created Age now gets a version-1 `Instability` compound inside its server-owned `rivencraft_ages` saved definition. It contains the total `Score` and an ordered `Breakdown` of reason, original page index (zero-based, or -1 for an Age-wide cause), points, and explanation. `AgeRegistrySavedData.instability(UUID)` is the read-only server query. No client tooltip or live data-pack lookup is needed to read a saved score. Every newly created Age now gets a version-1 `Instability` compound inside its server-owned `rivencraft_ages` saved definition. It contains the total `Score` and an ordered `Breakdown` of reason, original page index (zero-based, or -1 for an Age-wide cause), points, and explanation. `AgeRegistrySavedData.instability(UUID)` is the read-only server query. No client tooltip or live data-pack lookup is needed to read a saved score.
The baseline is explicitly zero for page-free and Link-Panel-only random Ages, and for authored Ages. Incomplete writing receives seed-based completion and a zero-point explanatory entry. Supported writing defects use the provisional Milestone 6 grammar costs: duplicate/conflicting single-choice pages +500, out-of-order or misplaced pages +100. Legacy's audited bright-lighting symbol adds +500 whether authored or seed-selected. Other balance costs are not guessed for symbols that Rivencraft has not implemented. The score is not yet an active hazard or effect selection. The baseline is explicitly zero for page-free and Link-Panel-only random Ages, and for authored Ages. Incomplete writing receives seed-based completion and a zero-point explanatory entry. Supported writing defects use the provisional Milestone 6 grammar costs: duplicate/conflicting single-choice pages +500, out-of-order or misplaced pages +100. Legacy's audited Bright Lighting symbol adds +500 for every occurrence, including a seed-generated controller. Mineshafts, Nether Fortresses, Strongholds, and Villages add +100 for the fourth and every later occurrence. By project balance decision, Bastions, Trial Chambers, Ancient Cities, Shipwrecks, Ocean Ruins, Pillager Outposts, Ruined Portals, Nether Fossils, Buried Treasure, and Trail Ruins follow that same rule. The first three occurrences and all other audited Legacy feature symbols have no direct page cost. An authored structure may override its vanilla biome eligibility; every structure-page occurrence forced into an unsupported selected biome adds +100. Seed completion still prefers compatible biomes and therefore avoids that cost when it can. Other modern-only features remain neutral. The frozen score selects a deterministic, persisted provider plan through the Milestone 6 runtime. Registered handlers apply that plan only inside loaded Rivencraft Ages and remain subject to the documented scheduler and effect-specific safety bounds.
The score is calculated after the Age plan and effective traits are chosen, then saved with the Age identity before its dimension is generated. The same UUID returns the existing definition, including the same score, on repeated use. Spawn updates preserve it. Reload only deserializes the frozen breakdown; it never reruns the current grammar or catalog. An older Age definition without `Instability` is migrated to a persisted version-1 neutral score of zero, rather than retroactively scoring its writing. A future scoring-rule change must introduce an explicit new schema/migration policy, not silently reinterpret existing Ages. The score is calculated after the Age plan and effective traits are chosen, then saved with the Age identity before its dimension is generated. The same UUID returns the existing definition, including the same score, on repeated use. Spawn updates preserve it. Reload only deserializes the frozen breakdown; it never reruns the current grammar or catalog. An older Age definition without `Instability` is migrated to a persisted version-1 neutral score of zero, rather than retroactively scoring its writing. A future scoring-rule change must introduce an explicit new schema/migration policy, not silently reinterpret existing Ages. Issue #66 added the frozen provider selection; issues #67–#70 added the current handlers. See the [runtime policy](INSTABILITY_RUNTIME.md).
Unknown or unsupported pages remain invalid for *new* Ages. Their absence from a later registry does not change an already saved score. Focused GameTests cover stable/defective writing, random baseline and bright lighting, repeated identity, save round-trip, and missing-symbol/old-save behavior. Unknown or unsupported pages remain invalid for *new* Ages. Their absence from a later registry does not change an already saved score. Focused GameTests cover stable/defective writing, random baseline and bright lighting, repeated identity, save round-trip, and missing-symbol/old-save behavior.
`/rivencraft age instability` inspects the Age containing the command source; an optional dimension ID inspects an unloaded or different registered Age. It reports immutable base score, stability bonus, runtime penalty, and effective score. The pinned Legacy tree defines player-death and player-presence bonus classes but does not register them as default providers, so Rivencraft leaves player-driven modifiers disabled: bonus and penalty are zero and effective equals base. There is therefore no mutable bonus save to migrate in this release. No death, PvP event, player identity, or dimension transition can transfer stability between Ages. Any future opt-in mechanic must persist separately from `Instability`, define caps and reset behavior, and must not rewrite the generation plan or frozen provider plan.
+9
View File
@@ -0,0 +1,9 @@
# Age status effects (Milestone 6, issue #67)
This slice activates the Legacy potion cards selected and saved by issue #66. The user-provided Mystcraft 0.13.7.06 `EffectPotion` chooses a random living entity in a chunk section. A local card requires sky visibility; a global card does not. `EffectPotionEnemy` excludes players. Its amplifier is selected level minus one. The defaults in `InstabilityData` give blindness and nausea 60 ticks, mining fatigue/hunger/poison/slowness/weakness 80 ticks, wither 30 ticks, and enemy regeneration/resistance 200 ticks. Rivencraft preserves those durations, sky rules, and level-to-amplifier mapping, subject to the server's lower duration/level caps.
General debuffs can affect survival/adventure players and other living entities, as Legacy did. The two enemy buffs affect hostile mobs only; Legacy affected any non-player living entity, so excluding passive animals is a deliberate modern adaptation. Creative and spectator players are exempt per issue #67, although the inspected Legacy potion class did not have that exemption. Existing effects from vanilla or another mod are never overwritten.
The issue #66 scheduler chooses an already-loaded chunk near a player, at most the configured number of provider calls and action claims per Age run. This provider queries at most `max_candidates_per_attempt` living entities in that chunk, picks one deterministically from the bounded candidates, and claims an action before applying. It holds at most `max_active_per_age` short-lived, owned-effect leases. It neither force-loads chunks nor scans all entities or chunks. Exact target RNG therefore intentionally differs from Legacy's random chunk-section walk; the target types, local/global distinction, duration, and strength are retained.
The server config can disable all status effects, player targets, general non-player targets, or hostile buffs, and can lower active leases, candidates, and duration. Leaving an Age, logging out, disabling effects, or stopping the server removes only an effect instance this provider actually installed; it will not remove a replacement from another mod. Leases also expire automatically after their short duration. The runtime never runs in the Overworld or a preview dimension. Automated tests cover mappings, target eligibility, creative/spectator exemption, and Overworld isolation. In-game multiplayer, Age-to-Age travel, and restart checks remain useful because GameTests do not create a second dynamic Age for this slice.
+17 -11
View File
@@ -1,6 +1,6 @@
# Mystcraft Legacy instability audit (Milestone 6, issue #63) # Mystcraft Legacy instability audit (Milestone 6, issue #63)
This is a behavior contract for Milestone 6, **not a completed runtime instability system**. It compares the user-provided 0.13.7.06 class files at `/home/dnorberg/Documents/mystcraft-src/mystcraft-1.12.2-0.13.7.06/` with [Mystcraft Legacy source at commit `9bc8ddc`](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae). Values below are source defaults, not a claim that every historical config or server used them. Rivencraft 0.5.1.0 saves a provisional writing-instability score and repaired active-page order, but has no hazard loop yet. This is the behavior contract used to implement Milestone 6. It is pinned to [Mystcraft Legacy source at commit `9bc8ddc`](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae). Values below are source defaults, not a claim that every historical config or server used them. Rivencraft now persists frozen writing-instability scores and provider plans and runs the implemented providers through a bounded, Age-scoped scheduler. The audit remains authoritative for Legacy behavior; the linked runtime documents identify modern adaptations and remaining gaps.
## Score, grammar, and selection in Legacy ## Score, grammar, and selection in Legacy
@@ -15,6 +15,10 @@ Legacy's [`AgeController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9b
| Unsupported/unmatched page | Legacy logs unmatched symbols during reconstruction and skips their logic; its `AgeData.getBaseInstability()` still has a TODO for calculating instability from pages. This is not a sound compatibility contract. | Remains fatal for *new* books until semantic and runtime support exists; never silently erase the page or pretend its effect applied. Existing saved books retain their IDs. | | Unsupported/unmatched page | Legacy logs unmatched symbols during reconstruction and skips their logic; its `AgeData.getBaseInstability()` still has a TODO for calculating instability from pages. This is not a sound compatibility contract. | Remains fatal for *new* books until semantic and runtime support exists; never silently erase the page or pretend its effect applied. Existing saved books retain their IDs. |
| Other penalties/bonuses | `AgeController.addInstability(int)` is available to symbol logic. The base/book score is persisted as a `short`; Legacy's [`InstabilityBonusManager`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/bonus/InstabilityBonusManager.java) also has dynamic player death/behavior components. | Persist a versioned score breakdown for Age writing and environmental contributions. Do not infer death/troll mechanics from the mere existence of Legacy classes. | | Other penalties/bonuses | `AgeController.addInstability(int)` is available to symbol logic. The base/book score is persisted as a `short`; Legacy's [`InstabilityBonusManager`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/bonus/InstabilityBonusManager.java) also has dynamic player death/behavior components. | Persist a versioned score breakdown for Age writing and environmental contributions. Do not infer death/troll mechanics from the mere existence of Legacy classes. |
The complete Legacy `instabilityModifier` audit found direct feature-page costs only for Mineshafts, Nether Fortresses, Strongholds, and Villages. Their first three occurrences cost zero; the fourth and every later occurrence adds 100. Every other Legacy feature class inherited `SymbolBase`'s zero modifier. Rivencraft applies that exact rule to the four matching pages. By project balance decision, Bastions, Trial Chambers, Ancient Cities, Shipwrecks, Ocean Ruins, Pillager Outposts, Ruined Portals, Nether Fossils, Buried Treasure, and Trail Ruins use the same repeat rule. Matching Legacy features such as Caves, Crystal Formations, Dense Ores, Dungeons, Floating Islands, Huge Trees, Deep/Surface Lakes, Obelisks, Ravines, Skylands, Spheres, Spikes, Star Fissures, and Tendrils have no direct page cost. Legacy could still derive instability later from excess profiled blocks, especially ores, but that separate 400-chunk profiling system is intentionally not ported. Other modern-only Rivencraft features remain neutral.
Bright Lighting adds 500 for every authored occurrence. A generated Bright Lighting controller also adds 500. This is independent of the 500-point extra-controller cost, so two authored Bright Lighting pages produce 1,500 total: 500 for each symbol and 500 for the repeated controller.
Source for controller and modifier defaults: [`InstabilityData`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityData.java), [`AgeController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/AgeController.java). The local 0.13.7.06 `Modifier.class` confirms `dangling_default=100`. Legacy grammar **ranks** weight which missing symbols are selected; they are not a direct instability score or deck tier. See [grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md) and [random weights](RANDOM_AGE_WEIGHTS.md). Source for controller and modifier defaults: [`InstabilityData`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityData.java), [`AgeController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/AgeController.java). The local 0.13.7.06 `Modifier.class` confirms `dangling_default=100`. Legacy grammar **ranks** weight which missing symbols are selected; they are not a direct instability score or deck tier. See [grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md) and [random weights](RANDOM_AGE_WEIGHTS.md).
[`InstabilityController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityController.java) rounds its working score toward zero to the current smallest registered positive provider cost (500 by default), then rebuilds active effects when that rounded score changes. Each seeded deck preserves its saved card order; new cards are shuffled with the Age seed. For each deck it subtracts the deck entry cost, then walks cards in order, paying each provider activation cost until the next card cannot be afforded. A provider's occurrences become its level. **Deck costs are gates, not mutually exclusive severity bands**: at high score multiple decks can contribute effects. Provider `.enabled` config can remove cards. The actual effect set cannot be inferred from a score alone without the saved deck orders and enabled providers ([`Deck`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/Deck.java), [`InstabilityManager`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityManager.java)). [`InstabilityController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityController.java) rounds its working score toward zero to the current smallest registered positive provider cost (500 by default), then rebuilds active effects when that rounded score changes. Each seeded deck preserves its saved card order; new cards are shuffled with the Age seed. For each deck it subtracts the deck entry cost, then walks cards in order, paying each provider activation cost until the next card cannot be afforded. A provider's occurrences become its level. **Deck costs are gates, not mutually exclusive severity bands**: at high score multiple decks can contribute effects. Provider `.enabled` config can remove cards. The actual effect set cannot be inferred from a score alone without the saved deck orders and enabled providers ([`Deck`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/Deck.java), [`InstabilityManager`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityManager.java)).
@@ -35,25 +39,27 @@ These entry costs are from [`InstabilityData.initialize()`](https://github.com/M
| Family | Legacy behavior | M6 disposition | | Family | Legacy behavior | M6 disposition |
| --- | --- | --- | | --- | --- | --- |
| Player and hostile-mob potions | Local/global blindness, fatigue, hunger, nausea, poison, slowness, weakness, wither; hostile regeneration/resistance ([`EffectPotion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectPotion.java)). | Implement in #67 with server-only, Age-scoped entity targeting and rate limits. No effects in preview/snapshot worlds. | | Player and hostile-mob potions | Local/global blindness, fatigue, hunger, nausea, poison, slowness, weakness, wither; hostile regeneration/resistance ([`EffectPotion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectPotion.java)). | Implemented in #67 with server-only, Age-scoped entity targeting and rate limits. No effects run in preview/snapshot worlds. |
| Colored decay | Blue, purple, red, white providers place advancing decay and extra-tick it; black provider is commented out. Decay handlers differ in spread/consumption ([providers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/providers), [handlers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/decay)). | Implement bounded, reversible-by-admin world mutation in #68; exact 1.12 spread/update rates require adaptation and tests. Exclude protected spawn/portal areas. Black/green/yellow are **not** proven active Legacy providers. | | Colored decay | Blue, purple, red, white providers place advancing decay and extra-tick it; black provider is commented out. Decay handlers differ in spread/consumption ([providers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/providers), [handlers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/decay)). | Implemented in #68 as bounded world mutation with protected spawn/portal areas and configurable shutdown. Black/green/yellow remain excluded because they are **not** proven active Legacy providers. |
| Lightning and explosions | Random per-chunk strike/explosion attempts ([`EffectLightning`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectLightning.java), [`EffectExplosions`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectExplosions.java)). | Implement in #69 with explicit block-damage and fire policy; no effect outside the Age. | | Lightning and explosions | Random per-chunk strike/explosion attempts ([`EffectLightning`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectLightning.java), [`EffectExplosions`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectExplosions.java)). | Implemented in #69 with separate damage/fire/griefing policies and loaded-Age bounds; see `INSTABILITY_RUNTIME.md`. |
| Meteor, scorching | Meteor entity spawn and sky-exposed entity ignition ([`EffectMeteor`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectMeteor.java), [`EffectScorched`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectScorched.java)). | #70: modern meteor entity/impact needs an explicit damage budget; scorching can use modern fire/damage checks. Legacy `meteor/roar.ogg` is available. | | Meteor, scorching | Meteor entity spawn and sky-exposed entity ignition ([`EffectMeteor`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectMeteor.java), [`EffectScorched`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectScorched.java)). | #70 implements a bounded meteor descent/impact and the active `burning` card; see `INSTABILITY_ENVIRONMENTAL.md`. Legacy `meteor/roar.ogg` is reused. |
| Crumble and erosion | Crumble maps blocks to weaker states; erosion spreads adjacent fluids and has extra lake-generation methods ([`EffectCrumble`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectCrumble.java), [`EffectErosion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectErosion.java)). | #70: bounded block palette and protected-area checks. Erosion's provider is commented out in Legacy registration: treat it as deliberate opt-in adaptation, not baseline parity. | | Crumble and erosion | Crumble maps blocks to weaker states; erosion spreads adjacent fluids and has extra lake-generation methods ([`EffectCrumble`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectCrumble.java), [`EffectErosion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectErosion.java)). | #70 implements guarded fluid spread. Erosion's provider is absent from the active Legacy deck; it is deliberately enabled by default in this test slice without adding a saved deck card, per user request. |
| Extra ticks | Registered alongside blue/purple/red/white decay, targeting decay blocks ([`EffectExtraTicks`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectExtraTicks.java)). | Implement only as a bounded decay helper in #68; do not accelerate arbitrary blocks/block entities. | | Extra ticks | Registered alongside blue/purple/red/white decay, targeting decay blocks ([`EffectExtraTicks`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectExtraTicks.java)). | Implement only as a bounded decay helper in #68; do not accelerate arbitrary blocks/block entities. |
| Other dormant code | Black decay, global burning, bedrock crumble, erosion provider are commented out. | Defer unless a later issue explicitly requests them. An authored symbol requiring one must fail clearly until supported. | | Other dormant code | Black decay, global burning, bedrock crumble, erosion provider are commented out; ordinary `burning` (scorching) remains active. | Erosion has been explicitly requested for #70 testing. The other dormant variants remain deferred; an authored symbol requiring one must fail clearly until supported. |
Assets in the supplied local tree: `assets/mystcraft/textures/blocks/decay_{black,blue,green,purple,red,white,yellow}.png`, corresponding decay block/item model JSON, and `assets/mystcraft/sounds/entity/meteor/roar.ogg`. Before importing, review attribution/license and fit modern 16×16 assets. Texture availability does not make an effect active. Use current Minecraft effects/sounds where adaptation is cleaner; no new artwork is needed for this audit. Assets in the supplied local tree: `assets/mystcraft/textures/blocks/decay_{black,blue,green,purple,red,white,yellow}.png`, corresponding decay block/item model JSON, and `assets/mystcraft/sounds/entity/meteor/roar.ogg`. Before importing, review attribution/license and fit modern 16×16 assets. Texture availability does not make an effect active. Use current Minecraft effects/sounds where adaptation is cleaner; no new artwork is needed for this audit.
## Rivencraft boundary and proposed safety contract ## Rivencraft boundary and current safety contract
[`WritingGrammar`](../src/main/java/net/dnorberg/rivencraft/writing/WritingGrammar.java) classifies `INCOMPLETE` as seeded completion and supported writing defects as accepted instability. `AgeGenerationPlan.compile()` freezes the original writing, repaired active-page indexes, and a provisional writing-instability score before world generation. #64 now persists a versioned score breakdown; saved provider/deck choice remains future work. The plan must not mutate an already-created Age when a data pack changes. Server-side settings may disable execution, but should not rewrite the saved authored score. [`WritingGrammar`](../src/main/java/net/dnorberg/rivencraft/writing/WritingGrammar.java) classifies `INCOMPLETE` as seeded completion and supported writing defects as accepted instability. `AgeGenerationPlan.compile()` freezes the original writing, repaired active-page indexes, and a provisional writing-instability score before world generation. #64 persists the versioned score breakdown, and #66 derives and persists the provider/deck choice from that frozen score. The plan must not mutate an already-created Age when a data pack changes. Server-side settings may disable execution, but do not rewrite the saved authored score or provider plan.
For #65, **eligible-to-become-unstable** means a known, supported page whose semantics and resulting world are still deterministic: repeated/conflicting single-choice pages and otherwise valid out-of-order or misplaced pages. The implementation retains every original page, uses the last single-choice page, sorts active categories, and saves 500 per extra/conflicting choice or 100 per misplaced page. These are provisional Rivencraft values, not a full port of every `IAgeSymbol.instabilityModifier`. Missing branches are explicitly classified as zero-cost seeded completion; legal repeated feature/material pages are not automatically errors. **Remain fatal**: missing/duplicate/misordered Link Panel, over-capacity book, unresolved or schema-v1 display-only symbol, unsupported weather/angle/runtime profile/biome/feature, unavailable required optional mod, and any combination the compiler cannot represent safely. Binder and unbound-book previews distinguish blocked writing, seeded completion, and accepted instability before binding; the server revalidates on output. This intentionally differs from Legacy's silent unmatched-symbol skip, universal controller cost assumptions, and modifier-specific dangling costs. A full symbol-specific Legacy penalty port remains a separate balance task, not a claim of parity in this slice. For #65, **eligible-to-become-unstable** means a known, supported page whose semantics and resulting world are still deterministic: repeated/conflicting single-choice pages and otherwise valid out-of-order or misplaced pages. The implementation retains every original page, uses the last single-choice page, sorts active categories, and saves 500 per extra/conflicting choice or 100 per misplaced page. Issue #71 adds the audited Bright Lighting and repeat-structure modifiers described above. Missing branches are explicitly classified as zero-cost seeded completion; legal repeated feature/material pages are not automatically errors, though a fourth matching Legacy structure now receives its source-defined cost. **Remain fatal**: missing/duplicate/misordered Link Panel, over-capacity book, unresolved or schema-v1 display-only symbol, unsupported weather/angle/runtime profile/biome/feature, unavailable required optional mod, and any combination the compiler cannot represent safely. Binder and unbound-book previews distinguish blocked writing, seeded completion, and accepted instability before binding; the server revalidates on output. This intentionally differs from Legacy's silent unmatched-symbol skip, universal controller cost assumptions, and modifier-specific dangling costs.
Legacy includes `PlayerKilledBonus` and `PlayerTrollPenalty` classes, but the pinned source contains no default provider registration for either. Rivencraft does not activate death, PvP, player-presence, or cross-dimension credit from dormant classes. Consequently #71 has no mutable per-Age bonus state to migrate, cap, reset, or persist: the stability bonus and runtime penalty are both zero, and the effective score equals the frozen base score. `/rivencraft age instability [dimension]` reports those four values and the disabled policy explicitly. This prevents unrelated players, deaths in other dimensions, and repeated deaths from changing an Age. A future opt-in policy must use separate versioned saved data and define its cap/reset rules before it can alter runtime selection.
Automated #65 checks cover classification, preserved input slots on rejection, and an accepted unstable preview. The live output/one-time Age creation check is assigned to in-game testing because the GameTest storage phase stalled when that transaction ran; the test world is not retained. Automated #65 checks cover classification, preserved input slots on rejection, and an accepted unstable preview. The live output/one-time Age creation check is assigned to in-game testing because the GameTest storage phase stalled when that transaction ran; the test world is not retained.
Proposed server defaults for #66–#72 (to confirm during implementation): instability scoring on for newly created Ages; passive entity effects on; world-mutating hazards **off by default** until an operator opts in; explicit per-Age toggle and separate per-family switches. Enforce a central work budget rather than letting every loaded chunk and provider roll independently: default at most one hazard attempt per Age per 20 ticks, one block mutation per successful attempt, and no forced chunk loads. Budgets should be configurable with hard upper bounds, including active Ages, target radius, tick interval, block changes/explosions/meteor impacts, entity effect attempts, and decay spread. Never target another dimension, unloaded chunk, book preview/snapshot, protected spawn/link platform, or portal. Stop safely when the Age unloads or settings change. These are **Rivencraft proposals**, not Legacy defaults or code that exists today; implementation issues must test/adjust them, especially multiple concurrent Ages. Expose score breakdown, selected effects, enablement, and budget suppression in server diagnostics (#72). Issue #66 established a server-only scheduler with bounded per-Age actions, provider calls, levels, cooldowns, loaded-chunk candidates, and rotating active-Age admission. Issues #67–#70 registered the current status, decay, lightning, explosion, meteor, burning, and erosion handlers with protected spawn/link platforms, portal exclusions, and provider-specific damage or spread limits. Instability and world-mutating handlers are enabled by default for newly generated configs to match Legacy's active default; operators can disable them without changing a saved Age. The bounds and protection hooks are **Rivencraft safety adaptations**, not Legacy defaults. Score breakdown, selected effects, enablement, and budget suppression remain part of diagnostics issue #72. See the [runtime policy](INSTABILITY_RUNTIME.md).
M6 owns scoring, selection, effects, controls, and regression. M7 still owns portal/transport and broader polish; M6 must not depend on new M7 structures. An illegal biome/terrain combination that is presently unrepresentable remains a generation failure until a separate, safe compiler path exists; instability must not be used to disguise absent worldgen support. Existing pre-release saves need explicit migration behavior in #73 rather than a silent rescore. M6 owns scoring, selection, effects, controls, and regression. M7 still owns portal/transport and broader polish; M6 must not depend on new M7 structures. An illegal biome/terrain combination that is presently unrepresentable remains a generation failure until a separate, safe compiler path exists; instability must not be used to disguise absent worldgen support. Existing pre-release saves need explicit migration behavior in #73 rather than a silent rescore.
+18 -1
View File
@@ -5,6 +5,22 @@ The world-generation, dimension, registry, networking, and rendering APIs have
changed substantially, so the work is divided into independently testable changed substantially, so the work is divided into independently testable
milestones. milestones.
## Porting principles
The primary goal is to reproduce verified Mystcraft Legacy behavior as closely
as practical. Legacy source and the supplied 0.13.7.06 build are the behavioral
reference for grammar, probabilities, ordering, defaults, visuals, and gameplay
effects. A difference should be deliberate and documented rather than inferred
from modern implementation convenience.
Minecraft 1.21.1 has different world heights, registries, threading, networking,
data-pack APIs, and server protection expectations. Where an exact port would be
unsafe, technically impossible, or incompatible with current Minecraft,
Rivencraft preserves the player-visible intent while using bounded modern
mechanics. New features may extend Legacy when they fit Age writing and linking,
but extensions must be identified separately from compatibility behavior and
must not silently change existing saved Ages.
## Project tracking ## Project tracking
Gitea is the source of truth for project status: Gitea is the source of truth for project status:
@@ -42,7 +58,8 @@ acceptance issue and all required implementation issues are complete.
TerraBlender and Serene Seasons integration. **Complete for the supported TerraBlender and Serene Seasons integration. **Complete for the supported
subset.** See the [acceptance record](MILESTONE_5_ACCEPTANCE.md) and subset.** See the [acceptance record](MILESTONE_5_ACCEPTANCE.md) and
[Legacy grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md). [Legacy grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md).
6. **Instability** — deterministic validation and server-safe effects. Start with the 6. **Instability** — deterministic validation and server-safe effects. **In
progress.** Start with the
[Legacy instability audit](LEGACY_INSTABILITY_AUDIT.md), which separates [Legacy instability audit](LEGACY_INSTABILITY_AUDIT.md), which separates
source behavior from proposed 1.21.1 safety limits. source behavior from proposed 1.21.1 safety limits.
7. **Structures and polish** — libraries, crystals, portals, recipes, models, 7. **Structures and polish** — libraries, crystals, portals, recipes, models,
+3 -3
View File
@@ -87,10 +87,10 @@ placement. The surface draws the native 30×40 portrait page region from
Legacy's book UI atlas; symbols are layered at a uniform scale, while the Legacy's book UI atlas; symbols are layered at a uniform scale, while the
square item models remain unchanged in inventories. square item models remain unchanged in inventories.
A Notebook holds 27 ordered positions. Its pages, names, gaps, and unresolved A Notebook holds 252 ordered positions. Its pages, names, gaps, and unresolved
IDs are saved on the item, so moving the Notebook between an inventory, Desk, IDs are saved on the item, so moving the Notebook between an inventory, Desk,
and Binder does not rearrange them. A loose Page in a Desk tab exposes just one and Binder does not rearrange them. A loose Page in a Desk tab exposes just one
position; a Notebook exposes all 27. The Desk has 88 persistent collection position; a Notebook exposes all 252. The Desk has 88 persistent collection
tabs, shown four at a time. Use the up/down tab controls to move by four, put tabs, shown four at a time. Use the up/down tab controls to move by four, put
paper and Ink Vials in their input slots, select a stored page, and take the paper and Ink Vials in their input slots, select a stored page, and take the
copy from the virtual output. Taking it spends one paper and the configured copy from the virtual output. Taking it spends one paper and the configured
@@ -100,7 +100,7 @@ copying. Moving a page within the Desk or dragging it into the inventory removes
the original only when the destination accepts it. the original only when the destination accepts it.
The Book Binder takes a leather or empty-Notebook cover, an Age title, one Link The Book Binder takes a leather or empty-Notebook cover, an Age title, one Link
Panel, and optionally up to 27 ordered written Pages. A filled Notebook can be Panel, and optionally up to 252 ordered written Pages. A filled Notebook can be
imported at a chosen strip position; the empty Notebook remains recoverable. imported at a chosen strip position; the empty Notebook remains recoverable.
The preview result is virtual. Taking the completed Descriptive Book commits the The preview result is virtual. Taking the completed Descriptive Book commits the
inputs once, creates its Age identity, and saves schema-versioned inputs once, creates its Age identity, and saves schema-versioned
+2 -2
View File
@@ -2,11 +2,11 @@
`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. `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. New Binder writing has at most one Link Panel plus 252 symbol pages (the current fixed-slot save-format ceiling, not a Legacy gameplay limit). 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; season; lighting; sky effects; zero or more period or phase modifiers; one celestial page; then zero or more features, each optionally preceded by a compatible material page. Biome pages precede the controller that consumes them, and celestial modifiers precede the celestial page. Terrain, controller, weather, season, lighting, sky, and celestial are single-choice categories; identical repeats are duplicates and differing values conflict. Repeated modifiers, biome pages, feature pages, and material pages are intentional and retain their order. An unpaired material page receives a seeded compatible feature during compilation. Angle modifiers remain recognized in the schema but are rejected at binding until a sky renderer can apply sun tilt. 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; season; lighting; sky effects; zero or more period or phase modifiers; one celestial page; then zero or more features, each optionally preceded by a compatible material page. Biome pages precede the controller that consumes them, and celestial modifiers precede the celestial page. Terrain, controller, weather, season, lighting, sky, and celestial are single-choice categories; identical repeats are duplicates and differing values conflict. Repeated modifiers, biome pages, feature pages, and material pages are intentional and retain their order. An unpaired material page receives a seeded compatible feature during compilation. Angle modifiers remain recognized in the schema but are rejected at binding until a sky renderer can apply sun tilt.
Missing terrain, controller, weather, lighting, celestial, or the controller's minimum biome count is an **incomplete** warning, not an error: the compiler retains seed-selected traits for missing branches. An omitted terrain page uses a seed-selected profile compatible with authored feature pages, so changing the Age name cannot accidentally select Flat, Void, or Cave terrain for Rocks or Lakes. If no profile can support the writing, binding still rejects it. Native consumes no authored biome pages; Single consumes one; Tiled/Grid and Tiny–Huge require two, with seeded filler when pages are missing. From 0.5.1.0, known misplaced or repeated pages no longer block creation: the book keeps its original order, while the server repairs category order, uses the last single-choice controller, and stores a writing-instability score in the Age plan. A conflicting/repeated choice adds 500; an out-of-order page or misplaced modifier adds 100. Native ignores surplus authored biome pages and Single uses the first, with the conflict recorded as instability. These are Rivencraft's provisional penalties, not a claim of exact Legacy values for every symbol. Incorrectly placed pages are **not** red-highlighted; their warning remains available as a tooltip. Unknown IDs, schema-v1 display-only symbols, unavailable dependencies/profiles, unsupported semantic effects or feature/material pairs, missing/extra Link Panels, and oversized writing still reject a new Age. The Binder disables output for those fatal errors and shows a red page indication where applicable. Rejected inputs remain removable. Missing terrain, controller, weather, lighting, celestial, or the controller's minimum biome count is an **incomplete** warning, not an error: the compiler retains seed-selected traits for missing branches. An omitted terrain page uses a seed-selected profile compatible with authored feature pages, so changing the Age name cannot accidentally select Flat, Void, or Cave terrain for Rocks or Lakes. If no profile can support the writing, binding still rejects it. Native consumes no authored biome pages; Single consumes one; Tiled/Grid and Tiny–Huge require two, with seeded filler when pages are missing. From 0.5.1.0, known misplaced or repeated pages no longer block creation: the book keeps its original order, while the server repairs category order, uses the last single-choice controller, and stores a writing-instability score in the Age plan. A conflicting/repeated choice adds 500; an out-of-order page or misplaced modifier adds 100. Native ignores surplus authored biome pages and Single uses the first, with the conflict recorded as instability. Audited Legacy symbol modifiers also add 500 for each Bright Lighting page and 100 for each Mineshafts, Nether Fortresses, Strongholds, or Villages occurrence after the third. Modern structures configured with the same rule are Bastions, Trial Chambers, Ancient Cities, Shipwrecks, Ocean Ruins, Pillager Outposts, Ruined Portals, Nether Fossils, Buried Treasure, and Trail Ruins. Every repeated structure page increases that structure's placement rate: probability-based structures multiply their chance, grid-based structures use a denser grid, and Strongholds add more positions to each ring and more positions overall. One page retains the vanilla placement rate. Authored structures can generate outside their vanilla biome set; each structure-page occurrence that requires this override adds 100 instability. Seed completion selects compatible biomes where possible. Other feature pages have no direct symbol cost. Incorrectly placed pages are **not** red-highlighted; their warning remains available as a tooltip. Unknown IDs, schema-v1 display-only symbols, unavailable dependencies/profiles, unsupported semantic effects or feature/material pairs, missing/extra Link Panels, and oversized writing still reject a new Age. The Binder disables output for those fatal errors and shows a red page indication where applicable. Rejected inputs remain removable.
The plan stores the original writing order, the authoritative semantic value of each resolved symbol, the active repaired-page indexes, the writing-instability score, the Age seed, and a copy of the selected runtime profile. An explicit terrain page overrides random terrain selection; an omitted terrain uses a seed-selected compatible profile. The built-in Standard, Amplified, Cave, Island, Flat, and Void terrain pages select their matching generation resources. Age loading uses the frozen runtime profile and does not need the original symbol definition or runtime-profile JSON, though its referenced noise, biome-preset, and dimension-type registry entries must remain available. Existing bound books without plans are not reinterpreted. Page-free and Link-Panel-only books keep the pre-existing random path. Biome and environment pages affect new Ages, and the supported feature subset below is compiled into the same frozen plan. Runtime effects for a nonzero writing-instability score are not implemented yet. The plan stores the original writing order, the authoritative semantic value of each resolved symbol, the active repaired-page indexes, the writing-instability score, the Age seed, and a copy of the selected runtime profile. An explicit terrain page overrides random terrain selection; an omitted terrain uses a seed-selected compatible profile. The built-in Standard, Amplified, Cave, Island, Flat, and Void terrain pages select their matching generation resources. Age loading uses the frozen runtime profile and does not need the original symbol definition or runtime-profile JSON, though its referenced noise, biome-preset, and dimension-type registry entries must remain available. Existing bound books without plans are not reinterpreted. Page-free and Link-Panel-only books keep the pre-existing random path. Biome and environment pages affect new Ages, and the supported feature subset below is compiled into the same frozen plan. Runtime effects for a nonzero writing-instability score are not implemented yet.
+1 -1
View File
@@ -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.5.3.0 mod_version=0.5.8.4
immersive_portals_version=6.0.7 immersive_portals_version=6.0.7
terrablender_version=4.1.0.8 terrablender_version=4.1.0.8
serene_seasons_version_id=B6nTjh4b serene_seasons_version_id=B6nTjh4b
@@ -21,6 +21,11 @@ import net.dnorberg.rivencraft.config.RivencraftClientConfig;
import net.dnorberg.rivencraft.compat.SereneSeasonsCompatibility; import net.dnorberg.rivencraft.compat.SereneSeasonsCompatibility;
import net.dnorberg.rivencraft.book.AgeDimensionService; import net.dnorberg.rivencraft.book.AgeDimensionService;
import net.dnorberg.rivencraft.book.AgeWeatherService; import net.dnorberg.rivencraft.book.AgeWeatherService;
import net.dnorberg.rivencraft.book.AgeInstabilityRuntime;
import net.dnorberg.rivencraft.book.AgeStatusEffectProviders;
import net.dnorberg.rivencraft.book.AgeDecayProviders;
import net.dnorberg.rivencraft.book.AgeHazardProviders;
import net.dnorberg.rivencraft.book.AgeEnvironmentalProviders;
import net.dnorberg.rivencraft.book.AgeRuntimeProfiles; import net.dnorberg.rivencraft.book.AgeRuntimeProfiles;
import net.dnorberg.rivencraft.writing.SymbolCatalog; import net.dnorberg.rivencraft.writing.SymbolCatalog;
import net.neoforged.bus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
@@ -37,6 +42,10 @@ public final class Rivencraft {
public Rivencraft(IEventBus modEventBus, ModContainer modContainer) { public Rivencraft(IEventBus modEventBus, ModContainer modContainer) {
AgeDimensionService.register(); AgeDimensionService.register();
AgeStatusEffectProviders.register();
AgeDecayProviders.register();
AgeHazardProviders.register();
AgeEnvironmentalProviders.register();
modContainer.registerConfig(ModConfig.Type.SERVER, RivencraftConfig.SPEC); modContainer.registerConfig(ModConfig.Type.SERVER, RivencraftConfig.SPEC);
modContainer.registerConfig(ModConfig.Type.CLIENT, RivencraftClientConfig.SPEC); modContainer.registerConfig(ModConfig.Type.CLIENT, RivencraftClientConfig.SPEC);
modEventBus.addListener(ModNetworking::register); modEventBus.addListener(ModNetworking::register);
@@ -52,11 +61,21 @@ public final class Rivencraft {
ModCreativeTabs.register(modEventBus); ModCreativeTabs.register(modEventBus);
NeoForge.EVENT_BUS.addListener(BookStandConversionHandler::onRightClickBlock); NeoForge.EVENT_BUS.addListener(BookStandConversionHandler::onRightClickBlock);
NeoForge.EVENT_BUS.addListener(AgeWeatherService::onLevelTickPost); NeoForge.EVENT_BUS.addListener(AgeWeatherService::onLevelTickPost);
NeoForge.EVENT_BUS.addListener(AgeInstabilityRuntime::onLevelTickPost);
NeoForge.EVENT_BUS.addListener(AgeEnvironmentalProviders::onLevelTickPost);
NeoForge.EVENT_BUS.addListener(AgeEnvironmentalProviders::onLevelUnload);
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onServerTickPost);
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onEntityTravel);
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onPlayerChangedDimension);
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onPlayerLoggedOut);
NeoForge.EVENT_BUS.addListener(SereneSeasonsCompatibility::onLevelTickPost); NeoForge.EVENT_BUS.addListener(SereneSeasonsCompatibility::onLevelTickPost);
NeoForge.EVENT_BUS.addListener(AgeCelestialAngleSync::onPlayerLoggedIn); NeoForge.EVENT_BUS.addListener(AgeCelestialAngleSync::onPlayerLoggedIn);
NeoForge.EVENT_BUS.addListener(AgeCelestialAngleSync::onPlayerChangedDimension); NeoForge.EVENT_BUS.addListener(AgeCelestialAngleSync::onPlayerChangedDimension);
NeoForge.EVENT_BUS.addListener(AgeLifecycleEvents::onPlayerLoggedOut); NeoForge.EVENT_BUS.addListener(AgeLifecycleEvents::onPlayerLoggedOut);
NeoForge.EVENT_BUS.addListener(AgeLifecycleEvents::onServerStopping); NeoForge.EVENT_BUS.addListener(AgeLifecycleEvents::onServerStopping);
NeoForge.EVENT_BUS.addListener(AgeInstabilityRuntime::onServerStopping);
NeoForge.EVENT_BUS.addListener(AgeEnvironmentalProviders::onServerStopping);
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onServerStopping);
NeoForge.EVENT_BUS.addListener(RivencraftCommands::register); NeoForge.EVENT_BUS.addListener(RivencraftCommands::register);
NeoForge.EVENT_BUS.addListener(AgeRuntimeProfiles::register); NeoForge.EVENT_BUS.addListener(AgeRuntimeProfiles::register);
NeoForge.EVENT_BUS.addListener(SymbolCatalog::register); NeoForge.EVENT_BUS.addListener(SymbolCatalog::register);
@@ -0,0 +1,36 @@
package net.dnorberg.rivencraft.block;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
/** Solid footing for Age arrivals, rendered as a translucent cloud. */
public final class CloudPlatformBlock extends Block {
public CloudPlatformBlock(Properties properties) {
super(properties);
}
@Override
public ItemStack getCloneItemStack(LevelReader level, BlockPos pos, BlockState state) {
return ItemStack.EMPTY;
}
@Override
protected boolean skipRendering(BlockState state, BlockState adjacent, Direction side) {
return adjacent.is(this) || super.skipRendering(state, adjacent, side);
}
@Override
protected boolean propagatesSkylightDown(BlockState state, BlockGetter level, BlockPos pos) {
return true;
}
@Override
protected int getLightBlock(BlockState state, BlockGetter level, BlockPos pos) {
return 0;
}
}
@@ -0,0 +1,46 @@
package net.dnorberg.rivencraft.block;
import net.dnorberg.rivencraft.book.AgeInstabilityRuntime;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.minecraft.core.BlockPos;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.EnumProperty;
/** The four colored decay variants selected by the current instability deck. */
public final class DecayBlock extends Block {
public static final EnumProperty<Color> COLOR = EnumProperty.create("color", Color.class);
public DecayBlock(Properties properties) {
super(properties);
registerDefaultState(stateDefinition.any().setValue(COLOR, Color.BLUE));
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(COLOR);
}
@Override
public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) {
if (!level.isClientSide && state.getValue(COLOR) == Color.WHITE
&& RivencraftConfig.decayEnabled() && RivencraftConfig.instabilityWorldMutation()
&& AgeInstabilityRuntime.isAgeDimension(level.dimension().location())) {
entity.hurt(level.damageSources().magic(), 1.0F);
}
super.stepOn(level, pos, state, entity);
}
public enum Color implements StringRepresentable {
BLUE, PURPLE, RED, WHITE;
@Override
public String getSerializedName() {
return name().toLowerCase(java.util.Locale.ROOT);
}
}
}
@@ -88,6 +88,9 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List<R
Random countRandom = new Random(seed ^ 0x42494F4D45434F55L); Random countRandom = new Random(seed ^ 0x42494F4D45434F55L);
while (target < maximum && countRandom.nextInt(3) != 0) target++; while (target < maximum && countRandom.nextInt(3) != 0) target++;
} }
completeStructureBiomes(writing, registries, availableBiomes, authored, distribution,
selected, distinct, seed);
target = Math.max(target, distinct.size());
// An authored Void Age must not acquire The Void as an unrequested second biome. // An authored Void Age must not acquire The Void as an unrequested second biome.
List<ResourceLocation> filler = profile.terrain() == AgeRuntimeProfile.Terrain.VOID && !authored.isEmpty() List<ResourceLocation> filler = profile.terrain() == AgeRuntimeProfile.Terrain.VOID && !authored.isEmpty()
? new ArrayList<>() : new ArrayList<>(availableBiomes); ? new ArrayList<>() : new ArrayList<>(availableBiomes);
@@ -103,6 +106,59 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List<R
return new AgeBiomeSelection(distribution, selected); return new AgeBiomeSelection(distribution, selected);
} }
/** Seed-completed biome branches must be able to host every authored structure page. */
private static void completeStructureBiomes(WritingGrammar.Result writing, RegistryAccess registries,
List<ResourceLocation> available,
List<ResourceLocation> authored,
AgeTraits.BiomeDistribution distribution,
List<ResourceLocation> selected,
Set<ResourceLocation> distinct,
long seed) {
List<Set<ResourceLocation>> requirements = writing.symbols().stream()
.filter(symbol -> symbol.semantics().role() == SymbolSemantics.Role.FEATURE)
.map(symbol -> ((SymbolSemantics.ResourceValue) symbol.semantics().value()).id())
.filter(AgeStructureSelection::feature)
.filter(feature -> !AgeStructureSelection.dungeons(feature))
.distinct()
.map(feature -> AgeStructureSelection.compatibleBiomes(feature, registries))
.filter(requirement -> !requirement.isEmpty())
.toList();
if (requirements.isEmpty()) return;
if (distribution == AgeTraits.BiomeDistribution.SINGLE) {
if (!authored.isEmpty()) return;
List<ResourceLocation> candidates = available.stream()
.filter(candidate -> requirements.stream().allMatch(requirement -> requirement.contains(candidate)))
.toList();
if (candidates.isEmpty()) return;
ResourceLocation selectedBiome = deterministicChoice(candidates, seed, 0x5354525543544249L);
selected.clear();
distinct.clear();
selected.add(selectedBiome);
distinct.add(selectedBiome);
return;
}
for (int index = 0; index < requirements.size(); index++) {
Set<ResourceLocation> requirement = requirements.get(index);
if (selected.stream().anyMatch(requirement::contains)) continue;
List<ResourceLocation> candidates = available.stream()
.filter(requirement::contains)
.filter(candidate -> !distinct.contains(candidate))
.toList();
if (candidates.isEmpty()) continue;
ResourceLocation selectedBiome = deterministicChoice(candidates, seed, 0x5354525543544249L + index);
selected.add(selectedBiome);
distinct.add(selectedBiome);
}
}
private static ResourceLocation deterministicChoice(List<ResourceLocation> choices, long seed, long salt) {
List<ResourceLocation> shuffled = new ArrayList<>(choices);
java.util.Collections.shuffle(shuffled, new Random(seed ^ salt));
return shuffled.getFirst();
}
public static List<ResourceLocation> eligible(RegistryAccess registries, AgeRuntimeProfile profile) { public static List<ResourceLocation> eligible(RegistryAccess registries, AgeRuntimeProfile profile) {
var registry = registries.lookupOrThrow(Registries.BIOME); var registry = registries.lookupOrThrow(Registries.BIOME);
if (isCave(profile)) { if (isCave(profile)) {
@@ -0,0 +1,87 @@
package net.dnorberg.rivencraft.book;
import java.util.List;
import java.util.UUID;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.block.DecayBlock;
import net.minecraft.core.BlockPos;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.ChunkPos;
import net.neoforged.neoforge.gametest.GameTestHolder;
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
@GameTestHolder(Rivencraft.MOD_ID)
@PrefixGameTestTemplate(false)
public final class AgeDecayGameTests {
private AgeDecayGameTests() {}
@GameTest(template = "empty")
public static void frontierRoundTripsWithoutDuplicates(GameTestHelper helper) {
AgeDecaySavedData data = new AgeDecaySavedData();
BlockPos first = new BlockPos(3, 70, 5);
data.add(DecayBlock.Color.BLUE, first);
data.add(DecayBlock.Color.BLUE, first);
data.add(DecayBlock.Color.WHITE, new BlockPos(-4, 64, 9));
helper.assertValueEqual(data.frontier(DecayBlock.Color.BLUE).size(), 1,
"One frontier block must not be stored twice");
helper.assertValueEqual(data.nextAttempt(), 0L, "First attempt starts at zero");
AgeDecaySavedData restored = AgeDecaySavedData.load(
data.save(new CompoundTag(), helper.getLevel().registryAccess()),
helper.getLevel().registryAccess());
helper.assertValueEqual(restored.nextAttempt(), 1L, "Attempt sequence survives reload");
helper.assertValueEqual(restored.frontier(DecayBlock.Color.BLUE).getFirst(), first,
"Blue frontier survives reload");
helper.assertValueEqual(restored.frontier(DecayBlock.Color.WHITE).size(), 1,
"White frontier survives reload independently");
restored.remove(DecayBlock.Color.BLUE, first);
helper.assertTrue(restored.frontier(DecayBlock.Color.BLUE).isEmpty(),
"Removed frontier is not scheduled for further spread");
helper.succeed();
}
@GameTest(template = "empty")
public static void targetMustRemainInChosenLoadedChunk(GameTestHelper helper) {
BlockPos center = helper.absolutePos(new BlockPos(1, 1, 1));
ChunkPos chunk = new ChunkPos(center);
helper.assertTrue(AgeDecayProviders.isLoadedTarget(helper.getLevel(), List.of(chunk), center),
"An already-loaded target inside the selected chunk is eligible");
BlockPos outside = new BlockPos((chunk.x + 1) << 4, center.getY(), center.getZ());
helper.assertTrue(!AgeDecayProviders.isLoadedTarget(helper.getLevel(), List.of(chunk), outside),
"Spread cannot cross into a chunk absent from this Age run");
helper.succeed();
}
@GameTest(template = "empty")
public static void overworldCannotRunDecayProvider(GameTestHelper helper) {
UUID ageId = UUID.randomUUID();
AgeDefinition age = new AgeDefinition(ageId, "Decay isolation", 100L, AgeGenerationProfiles.STANDARD,
AgeDefinition.CURRENT_GENERATION_VERSION, 0L, AgeDefinition.dimensionId(ageId), null,
AgeTraits.LEGACY_DEFAULTS);
AgeInstabilityRuntime.Budget budget = new AgeInstabilityRuntime.Budget(1);
var context = new AgeInstabilityRuntime.Context(helper.getLevel(), age,
List.of(new ChunkPos(helper.absolutePos(new BlockPos(1, 1, 1)))),
helper.getLevel().getServer().getTickCount(), budget);
AgeDecayProviders.apply(context, ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, "decayblue"), 1);
helper.assertValueEqual(budget.remaining(), 1, "Overworld decay cannot claim an Age action");
helper.succeed();
}
@GameTest(template = "empty")
public static void savedSpawnAndPlatformAreProtected(GameTestHelper helper) {
UUID ageId = UUID.randomUUID();
BlockPos spawn = new BlockPos(0, 65, 0);
AgeDefinition age = new AgeDefinition(ageId, "Protected arrival", 100L, AgeGenerationProfiles.STANDARD,
AgeDefinition.CURRENT_GENERATION_VERSION, 0L, AgeDefinition.dimensionId(ageId), spawn,
AgeTraits.LEGACY_DEFAULTS);
helper.assertTrue(AgeDecayProviders.isSpawnProtected(age, spawn.below().offset(2, 0, 2)),
"Arrival platform must not decay");
helper.assertTrue(AgeDecayProviders.isSpawnProtected(age, spawn.offset(4, 0, 4)),
"The protective margin must not decay");
helper.assertTrue(!AgeDecayProviders.isSpawnProtected(age, spawn.offset(5, 0, 0)),
"Spawn protection is bounded");
helper.succeed();
}
}
@@ -0,0 +1,202 @@
package net.dnorberg.rivencraft.book;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.block.DecayBlock;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.dnorberg.rivencraft.registry.ModBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.Heightmap;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.common.util.BlockSnapshot;
import net.neoforged.neoforge.common.util.FakePlayerFactory;
import net.neoforged.neoforge.event.level.BlockEvent;
/** Bounded, per-Age decay seeding and six-direction Legacy-style spreading. */
public final class AgeDecayProviders {
public static final TagKey<Block> PROTECTED = TagKey.create(Registries.BLOCK,
ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, "decay_protected"));
private static final Map<ResourceLocation, DecayBlock.Color> COLORS = Map.of(
id("decayblue"), DecayBlock.Color.BLUE,
id("decaypurple"), DecayBlock.Color.PURPLE,
id("decayred"), DecayBlock.Color.RED,
id("decaywhite"), DecayBlock.Color.WHITE);
private static final Direction[] DIRECTIONS = Direction.values();
private AgeDecayProviders() {}
public static void register() {
COLORS.keySet().forEach(id -> AgeInstabilityRuntime.register(id, true, AgeDecayProviders::apply));
}
/** Operator test hook; never changes the Age's saved instability score or provider plan. */
public static int pulseForTesting(ServerPlayer player, DecayBlock.Color color, int count) {
ServerLevel level = player.serverLevel();
if (!RivencraftConfig.decayEnabled() || !RivencraftConfig.instabilityWorldMutation()
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|| !level.getChunkSource().hasChunk(player.chunkPosition().x, player.chunkPosition().z)) return -1;
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
if (age == null) return -1;
ResourceLocation id = id("decay" + color.getSerializedName());
int changed = 0;
for (int i = 0; i < Math.min(count, 32); i++) {
AgeInstabilityRuntime.Budget budget = new AgeInstabilityRuntime.Budget(1);
apply(new AgeInstabilityRuntime.Context(level, age, List.of(player.chunkPosition()),
level.getServer().getTickCount(), budget), id, 1);
changed += 1 - budget.remaining();
}
return changed;
}
static void apply(AgeInstabilityRuntime.Context context, ResourceLocation id, int level) {
if (!RivencraftConfig.decayEnabled() || !RivencraftConfig.instabilityWorldMutation()
|| !AgeInstabilityRuntime.isAgeDimension(context.level().dimension().location())
|| !context.age().dimensionId().equals(context.level().dimension().location())
|| context.loadedChunks().isEmpty()) return;
DecayBlock.Color color = COLORS.get(id);
if (color == null) return;
AgeDecaySavedData data = AgeDecaySavedData.get(context.level());
Random random = new Random(context.age().seed() ^ data.nextAttempt() * 0x9E3779B97F4A7C15L
^ id.hashCode());
List<BlockPos> frontier = data.frontier(color);
BlockPos source = selectLoadedSource(context.level(), context.loadedChunks(), frontier, random);
if (source == null) {
seed(context, color, data, random);
return;
}
BlockState sourceState = context.level().getBlockState(source);
if (!sourceState.is(ModBlocks.DECAY.get()) || sourceState.getValue(DecayBlock.COLOR) != color) {
data.remove(color, source);
return;
}
for (int attempt = 0; attempt < RivencraftConfig.decayMaxAttempts(); attempt++) {
BlockPos target = source.relative(DIRECTIONS[random.nextInt(DIRECTIONS.length)]);
if (!isLoadedTarget(context.level(), context.loadedChunks(), target)
|| isSpawnProtected(context.age(), target)) continue;
BlockState prior = context.level().getBlockState(target);
if (!canReplace(context.level(), target, prior, color)) continue;
int difficulty = conversionDifficulty(context.level(), target, prior, color);
if (random.nextInt(difficulty) != 0) continue;
if (replace(context, target, prior, color)) data.add(color, target);
return;
}
}
private static void seed(AgeInstabilityRuntime.Context context, DecayBlock.Color color,
AgeDecaySavedData data, Random random) {
ChunkPos chunk = context.loadedChunks().get(random.nextInt(context.loadedChunks().size()));
int x = chunk.getMinBlockX() + random.nextInt(16);
int z = chunk.getMinBlockZ() + random.nextInt(16);
BlockPos pos = new BlockPos(x,
context.level().getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x, z) - 1, z);
if (!isLoadedTarget(context.level(), context.loadedChunks(), pos)
|| isSpawnProtected(context.age(), pos)) return;
BlockState prior = context.level().getBlockState(pos);
if (canReplace(context.level(), pos, prior, color) && replace(context, pos, prior, color)) {
data.add(color, pos);
}
}
private static BlockPos selectLoadedSource(ServerLevel level, List<ChunkPos> chunks,
List<BlockPos> frontier, Random random) {
if (frontier.isEmpty()) return null;
int start = random.nextInt(frontier.size());
for (int i = 0; i < Math.min(frontier.size(), 16); i++) {
BlockPos pos = frontier.get((start + i) % frontier.size());
if (isLoadedTarget(level, chunks, pos)) return pos;
}
return null;
}
static boolean isLoadedTarget(ServerLevel level, List<ChunkPos> chunks, BlockPos pos) {
return level.isInWorldBounds(pos) && level.getChunkSource().hasChunk(pos.getX() >> 4, pos.getZ() >> 4)
&& chunks.contains(new ChunkPos(pos));
}
static boolean isSpawnProtected(AgeDefinition age, BlockPos pos) {
BlockPos spawn = age.spawn();
return spawn != null && Math.abs(pos.getX() - spawn.getX()) <= 4
&& Math.abs(pos.getZ() - spawn.getZ()) <= 4
&& pos.getY() >= spawn.getY() - 2 && pos.getY() <= spawn.getY() + 4;
}
static boolean canReplace(ServerLevel level, BlockPos pos, BlockState prior, DecayBlock.Color color) {
if (!AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|| !level.isInWorldBounds(pos) || !level.getChunkSource().hasChunk(pos.getX() >> 4, pos.getZ() >> 4)
|| prior.is(PROTECTED) || prior.is(BlockTags.PORTALS)
|| prior.hasBlockEntity() || level.getBlockEntity(pos) != null
|| prior.getDestroySpeed(level, pos) < 0 || !prior.getFluidState().isEmpty()
|| isCritical(prior)) return false;
return !prior.is(ModBlocks.DECAY.get()) || prior.getValue(DecayBlock.COLOR) != color;
}
private static boolean isCritical(BlockState prior) {
return prior.is(Blocks.BEDROCK) || prior.is(Blocks.BARRIER)
|| prior.is(Blocks.END_PORTAL) || prior.is(Blocks.END_PORTAL_FRAME)
|| prior.is(Blocks.END_GATEWAY) || prior.is(Blocks.NETHER_PORTAL)
|| prior.is(Blocks.COMMAND_BLOCK) || prior.is(Blocks.CHAIN_COMMAND_BLOCK)
|| prior.is(Blocks.REPEATING_COMMAND_BLOCK) || prior.is(Blocks.STRUCTURE_BLOCK)
|| prior.is(Blocks.JIGSAW) || prior.is(Blocks.LIGHT)
|| prior.is(Blocks.REINFORCED_DEEPSLATE)
|| prior.getBlock() != ModBlocks.DECAY.get()
&& net.minecraft.core.registries.BuiltInRegistries.BLOCK.getKey(prior.getBlock())
.getNamespace().equals(Rivencraft.MOD_ID);
}
static int conversionDifficulty(ServerLevel level, BlockPos pos, BlockState state, DecayBlock.Color color) {
if (state.isAir()) return switch (color) {
case BLUE, RED -> 20;
case PURPLE -> 8;
case WHITE -> 50;
};
if (state.is(ModBlocks.DECAY.get())) return color == DecayBlock.Color.WHITE ? 1 : 5;
float hardness = Math.min(1000.0F, Math.max(0.0F, state.getDestroySpeed(level, pos)));
return switch (color) {
case BLUE -> Math.max(1, (int) hardness * 2);
case RED -> Math.max(1, (int) hardness);
case PURPLE -> Math.max(1, ((int) hardness + 1) * 10);
case WHITE -> 1;
};
}
private static boolean replace(AgeInstabilityRuntime.Context context, BlockPos pos, BlockState prior,
DecayBlock.Color color) {
ServerLevel level = context.level();
// A fake player gives claim/protection listeners the Age and exact block position.
var actor = FakePlayerFactory.getMinecraft(level);
actor.setPos(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
if (!prior.isAir()) {
var breakEvent = new BlockEvent.BreakEvent(level, pos, prior, actor);
NeoForge.EVENT_BUS.post(breakEvent);
if (breakEvent.isCanceled()) return false;
}
if (level.getBlockState(pos) != prior || !context.budget().claim()) return false;
var snapshot = BlockSnapshot.create(level.dimension(), level, pos);
BlockState decay = ModBlocks.DECAY.get().defaultBlockState().setValue(DecayBlock.COLOR, color);
if (!level.setBlock(pos, decay, 3)) return false;
var placeEvent = new BlockEvent.EntityPlaceEvent(snapshot, prior, actor);
NeoForge.EVENT_BUS.post(placeEvent);
if (placeEvent.isCanceled()) {
snapshot.restore();
return false;
}
return true;
}
private static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
}
}
@@ -0,0 +1,81 @@
package net.dnorberg.rivencraft.book;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import net.dnorberg.rivencraft.block.DecayBlock;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.datafix.DataFixTypes;
import net.minecraft.world.level.saveddata.SavedData;
/** Small, per-Age frontier and deterministic attempt counter; never stores chunk references. */
public final class AgeDecaySavedData extends SavedData {
private static final int MAX_FRONTIER_PER_COLOR = 1024;
private static final Factory<AgeDecaySavedData> FACTORY = new Factory<>(AgeDecaySavedData::new,
AgeDecaySavedData::load, DataFixTypes.SAVED_DATA_MAP_DATA);
private final EnumMap<DecayBlock.Color, List<BlockPos>> frontiers = new EnumMap<>(DecayBlock.Color.class);
private long attempts;
public AgeDecaySavedData() {
for (DecayBlock.Color color : DecayBlock.Color.values()) frontiers.put(color, new ArrayList<>());
}
public static AgeDecaySavedData get(ServerLevel level) {
return level.getDataStorage().computeIfAbsent(FACTORY, "rivencraft_decay");
}
public long nextAttempt() {
setDirty();
return attempts++;
}
public List<BlockPos> frontier(DecayBlock.Color color) {
return frontiers.get(color);
}
public void add(DecayBlock.Color color, BlockPos pos) {
List<BlockPos> frontier = frontiers.get(color);
if (frontier.contains(pos)) return;
if (frontier.size() >= MAX_FRONTIER_PER_COLOR) frontier.remove(0);
frontier.add(pos.immutable());
setDirty();
}
public void remove(DecayBlock.Color color, BlockPos pos) {
if (frontiers.get(color).remove(pos)) setDirty();
}
@Override
public CompoundTag save(CompoundTag tag, HolderLookup.Provider registries) {
tag.putLong("Attempts", attempts);
for (DecayBlock.Color color : DecayBlock.Color.values()) {
ListTag positions = new ListTag();
for (BlockPos pos : frontiers.get(color)) {
CompoundTag entry = new CompoundTag();
entry.putInt("X", pos.getX());
entry.putInt("Y", pos.getY());
entry.putInt("Z", pos.getZ());
positions.add(entry);
}
tag.put(color.getSerializedName(), positions);
}
return tag;
}
static AgeDecaySavedData load(CompoundTag tag, HolderLookup.Provider registries) {
AgeDecaySavedData data = new AgeDecaySavedData();
data.attempts = Math.max(0L, tag.getLong("Attempts"));
for (DecayBlock.Color color : DecayBlock.Color.values()) {
ListTag positions = tag.getList(color.getSerializedName(), CompoundTag.TAG_COMPOUND);
for (int index = 0; index < Math.min(positions.size(), MAX_FRONTIER_PER_COLOR); index++) {
CompoundTag entry = positions.getCompound(index);
data.frontiers.get(color).add(new BlockPos(entry.getInt("X"), entry.getInt("Y"), entry.getInt("Z")));
}
}
return data;
}
}
@@ -22,7 +22,8 @@ public record AgeDefinition(
AgeGenerationPlan plan, AgeGenerationPlan plan,
@Nullable AgeSeasonMode seasonMode, @Nullable AgeSeasonMode seasonMode,
List<AgeFeatureSelection.Choice> randomFeatures, List<AgeFeatureSelection.Choice> randomFeatures,
AgeInstability instability AgeInstability instability,
AgeInstabilityPlan instabilityPlan
) { ) {
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"
@@ -36,6 +37,7 @@ public record AgeDefinition(
Objects.requireNonNull(dimensionId, "dimensionId"); Objects.requireNonNull(dimensionId, "dimensionId");
Objects.requireNonNull(traits, "traits"); Objects.requireNonNull(traits, "traits");
Objects.requireNonNull(instability, "instability"); Objects.requireNonNull(instability, "instability");
Objects.requireNonNull(instabilityPlan, "instabilityPlan");
randomFeatures = List.copyOf(randomFeatures); randomFeatures = List.copyOf(randomFeatures);
if (plan != null && !randomFeatures.isEmpty()) { if (plan != null && !randomFeatures.isEmpty()) {
throw new IllegalArgumentException("Authored Ages cannot also have random features"); throw new IllegalArgumentException("Authored Ages cannot also have random features");
@@ -75,6 +77,16 @@ public record AgeDefinition(
dimensionId, spawn, traits, plan, seasonMode, randomFeatures, AgeInstability.legacyNeutral()); dimensionId, spawn, traits, plan, seasonMode, randomFeatures, AgeInstability.legacyNeutral());
} }
public AgeDefinition(UUID id, String name, long seed, ResourceLocation generationProfile,
int generationVersion, long createdGameTime, ResourceLocation dimensionId,
BlockPos spawn, AgeTraits traits, AgeGenerationPlan plan,
@Nullable AgeSeasonMode seasonMode, List<AgeFeatureSelection.Choice> randomFeatures,
AgeInstability instability) {
this(id, name, seed, generationProfile, generationVersion, createdGameTime,
dimensionId, spawn, traits, plan, seasonMode, randomFeatures, instability,
AgeInstabilityPlan.empty());
}
public static ResourceLocation dimensionId(UUID ageId) { public static ResourceLocation dimensionId(UUID ageId) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, "age/" + ageId); return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, "age/" + ageId);
} }
@@ -103,6 +115,7 @@ 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, plan, seasonMode, randomFeatures, instability); createdGameTime, dimensionId, spawn.immutable(), traits, plan, seasonMode,
randomFeatures, instability, instabilityPlan);
} }
} }
@@ -13,6 +13,7 @@ import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Random; import java.util.Random;
import net.dnorberg.rivencraft.Rivencraft; import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.registry.ModBlocks;
import net.dnorberg.rivencraft.compat.ImmersivePortalsChunkLoaders; import net.dnorberg.rivencraft.compat.ImmersivePortalsChunkLoaders;
import net.dnorberg.rivencraft.compat.SereneSeasonsCompatibility; import net.dnorberg.rivencraft.compat.SereneSeasonsCompatibility;
import net.dnorberg.rivencraft.compat.TerraBlenderBiomes; import net.dnorberg.rivencraft.compat.TerraBlenderBiomes;
@@ -228,7 +229,7 @@ public final class AgeDimensionService {
for (int x = -PLATFORM_RADIUS; x <= PLATFORM_RADIUS; x++) { for (int x = -PLATFORM_RADIUS; x <= PLATFORM_RADIUS; x++) {
for (int z = -PLATFORM_RADIUS; z <= PLATFORM_RADIUS; z++) { for (int z = -PLATFORM_RADIUS; z <= PLATFORM_RADIUS; z++) {
BlockPos floor = floorCenter.offset(x, 0, z); BlockPos floor = floorCenter.offset(x, 0, z);
level.setBlock(floor, Blocks.COBBLESTONE.defaultBlockState(), 2); level.setBlock(floor, ModBlocks.CLOUD_PLATFORM.get().defaultBlockState(), 2);
for (int y = 1; y <= 4; y++) { for (int y = 1; y <= 4; y++) {
level.setBlock(floor.above(y), Blocks.AIR.defaultBlockState(), 2); level.setBlock(floor.above(y), Blocks.AIR.defaultBlockState(), 2);
} }
@@ -0,0 +1,292 @@
package net.dnorberg.rivencraft.book;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.WeakHashMap;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.block.DecayBlock;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.dnorberg.rivencraft.registry.ModSounds;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.AABB;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.common.util.BlockSnapshot;
import net.neoforged.neoforge.common.util.FakePlayerFactory;
import net.neoforged.neoforge.event.level.BlockEvent;
import net.neoforged.neoforge.event.level.LevelEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.neoforged.neoforge.event.tick.LevelTickEvent;
/** Meteor, active Legacy burning, and test-enabled Legacy erosion. */
public final class AgeEnvironmentalProviders {
private static final ResourceLocation METEORS = id("meteors");
private static final ResourceLocation BURNING = id("burning");
private static final ResourceLocation EROSION = id("erosion");
private static final int METEOR_FLIGHT_TICKS = 30;
private static final int MAX_ACTIVE_AGES = 16;
private static final Direction[] FLUID_SIDES = {
Direction.UP, Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST
};
private static final Map<ServerLevel, Meteor> ACTIVE = new WeakHashMap<>();
private AgeEnvironmentalProviders() {}
public static void register() {
AgeInstabilityRuntime.register(METEORS, false, AgeEnvironmentalProviders::apply);
AgeInstabilityRuntime.register(BURNING, false, AgeEnvironmentalProviders::apply);
AgeInstabilityRuntime.register(EROSION, true, AgeEnvironmentalProviders::apply);
}
/** Operator test pulse; bypasses chance but never Age, loading, policy, or cooldown checks. */
public static int pulseForTesting(ServerPlayer player, String effect) {
ServerLevel level = player.serverLevel();
if (!AgeInstabilityRuntime.isAgeDimension(level.dimension().location())) return -1;
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
if (age == null) return -1;
List<ChunkPos> chunks = AgeHazardProviders.loadedChunksNearPlayers(level, 16);
if (chunks.isEmpty()) return 0;
var context = new AgeInstabilityRuntime.Context(level, age, chunks,
level.getServer().getTickCount(), new AgeInstabilityRuntime.Budget(1));
return switch (effect) {
case "meteor" -> RivencraftConfig.meteorEnabled() && scheduleMeteor(context, 1, true) ? 1 : 0;
case "burning" -> {
if (!RivencraftConfig.scorchEnabled() || !RivencraftConfig.scorchPlayers()
|| !eligibleScorch(context, player)) yield 0;
// Vanilla extinguishes this fire on the next entity tick in rain or water.
// Report that explicitly instead of claiming the test pulse worked.
if (player.isInWaterRainOrBubble()) yield -2;
player.igniteForSeconds(4);
yield 1;
}
case "erosion" -> {
if (!RivencraftConfig.erosionEnabled() || !AgeHazardProviders.canMutate(level)
|| age.instability().score() < InstabilityProviderCatalog.Deck.DESTRUCTIVE.entryCost()
|| !(player.pick(6.0, 0.0F, false) instanceof BlockHitResult hit)) yield 0;
BlockPos pos = hit.getBlockPos();
yield erodeAt(context, pos) ? 1 : 0;
}
default -> -1;
};
}
static boolean isEnvironmental(ResourceLocation id) {
return METEORS.equals(id) || BURNING.equals(id) || EROSION.equals(id);
}
static void tickPlanned(ServerLevel level, AgeDefinition age, long tick) {
List<AgeInstabilityPlan.ProviderLevel> cards = age.instabilityPlan().providers().stream()
.filter(card -> isEnvironmental(card.id())).toList();
boolean optInErosion = RivencraftConfig.erosionEnabled()
&& age.instability().score() >= InstabilityProviderCatalog.Deck.DESTRUCTIVE.entryCost();
if (cards.isEmpty() && !optInErosion) return;
List<ChunkPos> chunks = AgeHazardProviders.loadedChunksNearPlayers(level,
RivencraftConfig.hazardsMaxChunks());
if (chunks.isEmpty()) return;
for (AgeInstabilityPlan.ProviderLevel card : cards) {
int maximum = BURNING.equals(card.id()) ? RivencraftConfig.scorchMaxTargets() : 1;
var context = new AgeInstabilityRuntime.Context(level, age, chunks, tick,
new AgeInstabilityRuntime.Budget(maximum));
AgeInstabilityRuntime.invoke(context, card.id(), card.level());
}
if (optInErosion && cards.stream().noneMatch(card -> EROSION.equals(card.id()))) {
var context = new AgeInstabilityRuntime.Context(level, age, chunks, tick,
new AgeInstabilityRuntime.Budget(1));
AgeInstabilityRuntime.invoke(context, EROSION, 1);
}
}
static void apply(AgeInstabilityRuntime.Context context, ResourceLocation id, int effectiveLevel) {
if (!matchesAge(context.age(), context.level().dimension().location())
|| context.loadedChunks().isEmpty()) return;
if (METEORS.equals(id)) scheduleMeteor(context, effectiveLevel, false);
else if (BURNING.equals(id)) scorch(context, effectiveLevel);
else if (EROSION.equals(id)) erode(context);
}
static boolean matchesAge(AgeDefinition age, ResourceLocation dimension) {
return AgeInstabilityRuntime.isAgeDimension(dimension) && age.dimensionId().equals(dimension);
}
private static boolean scheduleMeteor(AgeInstabilityRuntime.Context context, int effectiveLevel, boolean force) {
if (!RivencraftConfig.meteorEnabled() || ACTIVE.containsKey(context.level())
|| ACTIVE.size() >= MAX_ACTIVE_AGES) return false;
AgeHazardSavedData data = AgeHazardSavedData.get(context.level());
long gameTime = context.level().getGameTime();
if (!data.meteorReady(gameTime, 200)) return false;
Random random = new Random(context.age().seed() ^ data.nextAttempt() * 0xD1B54A32D192ED03L
^ METEORS.hashCode());
if (!force && random.nextDouble() >= AgeHazardProviders.legacyChance(context.loadedChunks().size(),
RivencraftConfig.instabilityCooldown(), effectiveLevel, 50000)) return false;
int start = random.nextInt(context.loadedChunks().size());
for (int offset = 0; offset < Math.min(16, context.loadedChunks().size()); offset++) {
ChunkPos chunk = context.loadedChunks().get((start + offset) % context.loadedChunks().size());
int x = chunk.getMinBlockX() + 6 + random.nextInt(4);
int z = chunk.getMinBlockZ() + 6 + random.nextInt(4);
int surfaceY = context.level().getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x, z);
BlockPos impact = new BlockPos(x, surfaceY, z);
if (surfaceY >= context.level().getMaxBuildHeight() - 8
|| !AgeHazardProviders.safeTarget(context, impact, 8)) continue;
if (!context.budget().claim()) return false;
int startY = Math.min(context.level().getMaxBuildHeight() - 2, surfaceY + 48);
data.recordMeteor(gameTime);
ACTIVE.put(context.level(), new Meteor(chunk, impact, startY, METEOR_FLIGHT_TICKS));
context.level().playSound(null, impact, ModSounds.METEOR_ROAR.get(), SoundSource.WEATHER, 2.0F, 1.0F);
return true;
}
return false;
}
public static void onLevelTickPost(LevelTickEvent.Post event) {
if (!(event.getLevel() instanceof ServerLevel level)) return;
Meteor meteor = ACTIVE.get(level);
if (meteor == null) return;
if (!RivencraftConfig.instabilityEnabled() || !RivencraftConfig.meteorEnabled()
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|| level.players().isEmpty()
|| !level.getChunkSource().hasChunk(meteor.chunk().x, meteor.chunk().z)) {
ACTIVE.remove(level);
return;
}
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
if (age == null) {
ACTIVE.remove(level);
return;
}
int remaining = meteor.remaining() - 1;
if (remaining <= 0) {
ACTIVE.remove(level); // clear before impact so an exception cannot replay it
AgeHazardProviders.explodeBounded(level, age, meteor.chunk(), meteor.impact(),
RivencraftConfig.meteorBlockDamage(), RivencraftConfig.meteorPlayerDamage(),
RivencraftConfig.meteorFire(), RivencraftConfig.meteorMaxBlocks(),
RivencraftConfig.meteorMaxEntities(), RivencraftConfig.meteorMaxDamage(), 3);
return;
}
double progress = 1.0 - remaining / (double) METEOR_FLIGHT_TICKS;
double y = meteor.startY() + (meteor.impact().getY() - meteor.startY()) * progress;
double x = meteor.impact().getX() + 0.5 + (1.0 - progress) * 2.0;
double z = meteor.impact().getZ() + 0.5 + (1.0 - progress) * 2.0;
level.sendParticles(ParticleTypes.FLAME, x, y, z, 5, 0.25, 0.25, 0.25, 0.01);
level.sendParticles(ParticleTypes.LARGE_SMOKE, x, y, z, 2, 0.3, 0.3, 0.3, 0.02);
ACTIVE.put(level, new Meteor(meteor.chunk(), meteor.impact(), meteor.startY(), remaining));
}
public static void onServerStopping(ServerStoppingEvent event) {
ACTIVE.clear(); // an interrupted descent is cancelled, never replayed after restart
}
public static void onLevelUnload(LevelEvent.Unload event) {
if (event.getLevel() instanceof ServerLevel level) ACTIVE.remove(level);
}
private static void scorch(AgeInstabilityRuntime.Context context, int effectiveLevel) {
if (!RivencraftConfig.scorchEnabled() || RivencraftConfig.scorchMaxTargets() == 0) return;
ServerLevel level = context.level();
Random random = new Random(context.age().seed() ^ AgeHazardSavedData.get(level).nextAttempt()
* 0x9E3779B97F4A7C15L ^ BURNING.hashCode());
int start = random.nextInt(context.loadedChunks().size());
int affected = 0;
for (int offset = 0; offset < Math.min(8, context.loadedChunks().size()); offset++) {
ChunkPos chunk = context.loadedChunks().get((start + offset) % context.loadedChunks().size());
AABB bounds = new AABB(chunk.getMinBlockX(), level.getMinBuildHeight(), chunk.getMinBlockZ(),
chunk.getMaxBlockX() + 1, level.getMaxBuildHeight(), chunk.getMaxBlockZ() + 1);
List<LivingEntity> candidates = new ArrayList<>();
level.getEntities(EntityTypeTest.forClass(LivingEntity.class), bounds,
entity -> eligibleScorch(context, entity), candidates, 8);
candidates.sort(Comparator.comparing(Entity::getUUID));
for (LivingEntity entity : candidates) {
if (affected >= RivencraftConfig.scorchMaxTargets() || context.budget().remaining() == 0) return;
// Legacy sampled each chunk each tick with a 1/10 gate. With 20 ticks/pass this
// gives at least one opportunity for nearly every inspected loaded chunk.
if (random.nextDouble() >= AgeHazardProviders.legacyChance(1,
RivencraftConfig.instabilityCooldown(), 1, 10)) continue;
if (!context.budget().claim()) return;
entity.igniteForSeconds(Math.min(12, 4 * effectiveLevel));
affected++;
break;
}
}
}
private static boolean eligibleScorch(AgeInstabilityRuntime.Context context, LivingEntity entity) {
if (!entity.isAlive() || entity.isRemoved() || entity.level() != context.level()
|| !context.level().canSeeSky(entity.blockPosition())
|| AgeDecayProviders.isSpawnProtected(context.age(), entity.blockPosition())) return false;
if (entity instanceof Player player) return RivencraftConfig.scorchPlayers()
&& !player.isCreative() && !player.isSpectator();
return true;
}
private static void erode(AgeInstabilityRuntime.Context context) {
if (!RivencraftConfig.erosionEnabled() || !AgeHazardProviders.canMutate(context.level())) return;
ServerLevel level = context.level();
Random random = new Random(context.age().seed() ^ AgeHazardSavedData.get(level).nextAttempt()
* 0xC2B2AE3D27D4EB4FL ^ EROSION.hashCode());
for (int attempt = 0; attempt < 8; attempt++) {
ChunkPos chunk = context.loadedChunks().get(random.nextInt(context.loadedChunks().size()));
int x = chunk.getMinBlockX() + random.nextInt(16);
int z = chunk.getMinBlockZ() + random.nextInt(16);
int y = level.getMinBuildHeight() + 1 + random.nextInt(level.getHeight() - 2);
if (erodeAt(context, new BlockPos(x, y, z))) return;
}
}
private static boolean erodeAt(AgeInstabilityRuntime.Context context, BlockPos pos) {
ServerLevel level = context.level();
if (!AgeDecayProviders.isLoadedTarget(level, context.loadedChunks(), pos)
|| AgeDecayProviders.isSpawnProtected(context.age(), pos)) return false;
BlockState prior = level.getBlockState(pos);
if (!AgeDecayProviders.canReplace(level, pos, prior, DecayBlock.Color.BLUE)) return false;
for (Direction direction : FLUID_SIDES) {
BlockPos neighbor = pos.relative(direction);
if (!AgeDecayProviders.isLoadedTarget(level, context.loadedChunks(), neighbor)) continue;
var fluid = level.getFluidState(neighbor);
if (fluid.isSource() && replaceFluid(context, pos, prior, fluid.createLegacyBlock())) return true;
}
return false;
}
private static boolean replaceFluid(AgeInstabilityRuntime.Context context, BlockPos pos,
BlockState prior, BlockState fluidBlock) {
ServerLevel level = context.level();
var actor = FakePlayerFactory.getMinecraft(level);
actor.setPos(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
if (!prior.isAir()) {
var breaking = new BlockEvent.BreakEvent(level, pos, prior, actor);
NeoForge.EVENT_BUS.post(breaking);
if (breaking.isCanceled()) return false;
}
if (level.getBlockState(pos) != prior || !context.budget().claim()) return false;
var snapshot = BlockSnapshot.create(level.dimension(), level, pos);
if (!level.setBlock(pos, fluidBlock, 3)) return false;
var placing = new BlockEvent.EntityPlaceEvent(snapshot, prior, actor);
NeoForge.EVENT_BUS.post(placing);
if (placing.isCanceled()) {
snapshot.restore();
return false;
}
return true;
}
private static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
}
private record Meteor(ChunkPos chunk, BlockPos impact, int startY, int remaining) {}
}
@@ -0,0 +1,329 @@
package net.dnorberg.rivencraft.book;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.BlockTags;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LightningBolt;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.ExplosionDamageCalculator;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.AABB;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.common.util.FakePlayerFactory;
import net.neoforged.neoforge.event.level.BlockEvent;
/** Legacy hazard cards, with one loaded-chunk event and explicit damage budgets. */
public final class AgeHazardProviders {
private static final ResourceLocation LIGHTNING = id("lightning");
private static final ResourceLocation EXPLOSIONS = id("explosions");
private AgeHazardProviders() {}
public static void register() {
// Visuals and entity damage remain available when block mutation is disabled.
AgeInstabilityRuntime.register(LIGHTNING, false, AgeHazardProviders::apply);
AgeInstabilityRuntime.register(EXPLOSIONS, false, AgeHazardProviders::apply);
}
static boolean isHazard(ResourceLocation id) {
return LIGHTNING.equals(id) || EXPLOSIONS.equals(id);
}
/** Roll every selected hazard card each scheduler pass, independently of other providers. */
static void tickPlanned(ServerLevel level, AgeDefinition age, long tick) {
if (!RivencraftConfig.hazardsEnabled()) return;
List<AgeInstabilityPlan.ProviderLevel> hazards = age.instabilityPlan().providers().stream()
.filter(provider -> isHazard(provider.id())).toList();
if (hazards.isEmpty()) return;
List<ChunkPos> chunks = loadedChunksNearPlayers(level, RivencraftConfig.hazardsMaxChunks());
if (chunks.isEmpty()) return;
for (AgeInstabilityPlan.ProviderLevel hazard : hazards) {
var context = new AgeInstabilityRuntime.Context(level, age, chunks, tick,
new AgeInstabilityRuntime.Budget(1));
AgeInstabilityRuntime.invoke(context, hazard.id(), hazard.level());
}
}
static List<ChunkPos> loadedChunksNearPlayers(ServerLevel level, int maximum) {
Set<ChunkPos> chunks = new LinkedHashSet<>();
List<ServerPlayer> players = level.players().stream()
.sorted(Comparator.comparing(Entity::getUUID)).toList();
for (int radius = 0; radius <= 4; radius++) {
for (int dx = -radius; dx <= radius; dx++) {
for (int dz = -radius; dz <= radius; dz++) {
if (Math.max(Math.abs(dx), Math.abs(dz)) != radius) continue;
for (ServerPlayer player : players) {
ChunkPos center = player.chunkPosition();
int x = center.x + dx;
int z = center.z + dz;
if (level.getChunkSource().hasChunk(x, z)) chunks.add(new ChunkPos(x, z));
if (chunks.size() >= maximum) return List.copyOf(chunks);
}
}
}
}
return List.copyOf(chunks);
}
/** Operator-only test pulse; skips the random roll, not Age, cooldown, or safety checks. */
public static int pulseForTesting(ServerPlayer player, boolean lightning) {
ServerLevel level = player.serverLevel();
if (!RivencraftConfig.hazardsEnabled()
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())) return -1;
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
if (age == null) return -1;
AgeHazardSavedData data = AgeHazardSavedData.get(level);
if (!data.ready(lightning, level.getGameTime(), RivencraftConfig.hazardsMinInterval())) return 0;
ChunkPos center = player.chunkPosition();
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {
ChunkPos chunk = new ChunkPos(center.x + dx, center.z + dz);
if (!level.getChunkSource().hasChunk(chunk.x, chunk.z)) continue;
int x = chunk.getMinBlockX() + 8;
int z = chunk.getMinBlockZ() + 8;
int y = lightning ? level.getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)
: player.getBlockY();
BlockPos pos = new BlockPos(x, y, z);
var context = new AgeInstabilityRuntime.Context(level, age, List.of(chunk),
level.getServer().getTickCount(), new AgeInstabilityRuntime.Budget(1));
if (!safeTarget(context, pos, 8)) continue;
data.nextAttempt();
data.record(lightning, level.getGameTime());
if (lightning) strike(level, age, chunk, pos);
else explode(level, age, chunk, pos);
return 1;
}
}
return 0;
}
static void apply(AgeInstabilityRuntime.Context context, ResourceLocation id, int effectiveLevel) {
ServerLevel level = context.level();
if (!RivencraftConfig.hazardsEnabled() || context.loadedChunks().isEmpty()
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|| !context.age().dimensionId().equals(level.dimension().location())) return;
boolean lightning = id.equals(LIGHTNING);
if (!lightning && !id.equals(EXPLOSIONS)) return;
AgeHazardSavedData data = AgeHazardSavedData.get(level);
long gameTime = level.getGameTime();
if (!data.ready(lightning, gameTime, RivencraftConfig.hazardsMinInterval())) return;
Random random = new Random(context.age().seed() ^ data.nextAttempt() * 0x9E3779B97F4A7C15L
^ id.hashCode());
int legacyDenominator = lightning ? level.isRaining() && level.isThundering() ? 5000 : 100000 : 1000;
// Legacy rolled once per chunk per tick; the shared scheduler visits this Age every >=20 ticks.
double chance = legacyChance(context.loadedChunks().size(), RivencraftConfig.instabilityCooldown(),
effectiveLevel, legacyDenominator);
if (random.nextDouble() >= chance) return;
ChunkPos chunk = context.loadedChunks().get(random.nextInt(context.loadedChunks().size()));
int margin = lightning ? 2 : 6;
int x = chunk.getMinBlockX() + margin + random.nextInt(16 - margin * 2);
int z = chunk.getMinBlockZ() + margin + random.nextInt(16 - margin * 2);
int y = lightning ? level.getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)
: level.getMinBuildHeight() + 1 + random.nextInt(level.getHeight() - 2);
BlockPos pos = new BlockPos(x, y, z);
if (!safeTarget(context, pos, 8) || !context.budget().claim()) return;
data.record(lightning, gameTime); // persist before dispatch so a restart cannot replay the event
if (lightning) strike(level, context.age(), chunk, pos);
else explode(level, context.age(), chunk, pos);
}
static double legacyChance(int loadedChunks, int intervalTicks, int copies, int denominator) {
if (loadedChunks <= 0 || intervalTicks <= 0 || copies <= 0 || denominator <= 0) return 0;
return 1.0 - Math.pow(1.0 - 1.0 / denominator, (double) loadedChunks * intervalTicks * copies);
}
static boolean safeTarget(AgeInstabilityRuntime.Context context, BlockPos pos, int spawnMargin) {
if (!AgeDecayProviders.isLoadedTarget(context.level(), context.loadedChunks(), pos)) return false;
BlockPos spawn = context.age().spawn();
return spawn == null || Math.abs(pos.getX() - spawn.getX()) > spawnMargin
|| Math.abs(pos.getZ() - spawn.getZ()) > spawnMargin;
}
private static void strike(ServerLevel level, AgeDefinition age, ChunkPos chunk, BlockPos pos) {
AABB bounds = new AABB(pos).inflate(2);
if (!level.getEntitiesOfClass(LightningBolt.class, bounds).isEmpty()) return;
LightningBolt bolt = EntityType.LIGHTNING_BOLT.create(level);
if (bolt == null) return;
bolt.setPos(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5);
bolt.setVisualOnly(true); // vanilla bolt damage/fire bypasses our explicit budgets
if (!level.addFreshEntity(bolt)) return;
List<LivingEntity> targets = level.getEntitiesOfClass(LivingEntity.class, bounds,
entity -> entity.isAlive() && entity.level() == level && eligibleEntity(entity));
targets.sort(Comparator.comparing(Entity::getUUID));
int count = 0;
for (LivingEntity target : targets) {
if (count++ >= RivencraftConfig.hazardsMaxEntities()) break;
if (RivencraftConfig.hazardsMaxDamage() > 0)
target.hurt(level.damageSources().lightningBolt(), Math.min(5, RivencraftConfig.hazardsMaxDamage()));
}
// Legacy lightning started fires. Keep it separately gated by block policy and game rule.
if (canMutate(level) && RivencraftConfig.hazardsFire()
&& level.getGameRules().getBoolean(GameRules.RULE_DOFIRETICK)
&& !AgeDecayProviders.isSpawnProtected(age, pos)
&& AgeDecayProviders.isLoadedTarget(level, List.of(chunk), pos)) ignite(level, pos);
}
private static void explode(ServerLevel level, AgeDefinition age, ChunkPos chunk, BlockPos pos) {
explodeBounded(level, age, chunk, pos, RivencraftConfig.hazardsBlockDamage(),
RivencraftConfig.hazardsPlayerDamage(), RivencraftConfig.hazardsFire(),
RivencraftConfig.hazardsMaxBlocks(), RivencraftConfig.hazardsMaxEntities(),
RivencraftConfig.hazardsMaxDamage(), RivencraftConfig.hazardsExplosionRadius());
}
/** Shared blast guard for meteor impacts; each effect supplies its own damage policy. */
static void explodeBounded(ServerLevel level, AgeDefinition age, ChunkPos chunk, BlockPos pos,
boolean blockDamage, boolean playerDamage, boolean ignite, int maxBlocks, int maxEntities,
int maxDamage, int radius) {
boolean grief = canMutate(level) && blockDamage && maxBlocks > 0;
boolean fire = grief && ignite
&& level.getGameRules().getBoolean(GameRules.RULE_DOFIRETICK);
Explosion explosion = level.explode(null, null, new BoundedExplosion(level, age, chunk, grief,
playerDamage, maxBlocks, maxEntities, maxDamage),
pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5,
radius, false,
grief ? Level.ExplosionInteraction.BLOCK : Level.ExplosionInteraction.NONE);
if (fire) {
int ignited = 0;
for (BlockPos affected : explosion.getToBlow()) {
if (ignited >= 4) break;
if (!AgeDecayProviders.isSpawnProtected(age, affected) && ignite(level, affected)) ignited++;
}
}
}
private static boolean ignite(ServerLevel level, BlockPos pos) {
if (!level.getBlockState(pos).isAir() || !Blocks.FIRE.defaultBlockState().canSurvive(level, pos))
return false;
var actor = FakePlayerFactory.getMinecraft(level);
actor.setPos(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5);
var snapshot = net.neoforged.neoforge.common.util.BlockSnapshot.create(level.dimension(), level, pos);
BlockState prior = level.getBlockState(pos);
if (!level.setBlock(pos, Blocks.FIRE.defaultBlockState(), 3)) return false;
var place = new BlockEvent.EntityPlaceEvent(snapshot, prior, actor);
NeoForge.EVENT_BUS.post(place);
if (place.isCanceled()) {
snapshot.restore();
return false;
}
return true;
}
static boolean canMutate(ServerLevel level) {
return RivencraftConfig.instabilityWorldMutation()
&& level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING);
}
private static boolean eligibleEntity(Entity entity) {
return eligibleEntity(entity, RivencraftConfig.hazardsPlayerDamage());
}
private static boolean eligibleEntity(Entity entity, boolean playerDamage) {
return !(entity instanceof Player player) || playerDamage
&& !player.isCreative() && !player.isSpectator();
}
private static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
}
private static final class BoundedExplosion extends ExplosionDamageCalculator {
private final ServerLevel level;
private final AgeDefinition age;
private final ChunkPos chunk;
private final boolean grief;
private final boolean playerDamage;
private final int maxBlocks;
private final int maxEntities;
private final int maxDamage;
private final Set<BlockPos> approved = new HashSet<>();
private final Set<UUID> damagedEntities = new HashSet<>();
private int damaged;
private BoundedExplosion(ServerLevel level, AgeDefinition age, ChunkPos chunk, boolean grief,
boolean playerDamage, int maxBlocks, int maxEntities, int maxDamage) {
this.level = level;
this.age = age;
this.chunk = chunk;
this.grief = grief;
this.playerDamage = playerDamage;
this.maxBlocks = maxBlocks;
this.maxEntities = maxEntities;
this.maxDamage = maxDamage;
}
@Override
public Optional<Float> getBlockExplosionResistance(Explosion explosion, BlockGetter reader,
BlockPos pos, BlockState state, FluidState fluid) {
if (!inLoadedChunk(pos)) return Optional.of(Float.MAX_VALUE);
return super.getBlockExplosionResistance(explosion, reader, pos, state, fluid);
}
@Override
public boolean shouldBlockExplode(Explosion explosion, BlockGetter reader, BlockPos pos,
BlockState state, float power) {
if (!grief || !inLoadedChunk(pos) || state.isAir() || state.hasBlockEntity()
|| state.is(Blocks.TNT)
|| state.is(AgeDecayProviders.PROTECTED) || state.is(BlockTags.PORTALS)
|| AgeDecayProviders.isSpawnProtected(age, pos)
|| state.getDestroySpeed(level, pos) < 0
|| BuiltInRegistries.BLOCK.getKey(state.getBlock()).getNamespace().equals(Rivencraft.MOD_ID)) return false;
if (approved.contains(pos)) return true;
if (approved.size() >= maxBlocks) return false;
var actor = FakePlayerFactory.getMinecraft(level);
actor.setPos(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
var event = new BlockEvent.BreakEvent(level, pos, state, actor);
NeoForge.EVENT_BUS.post(event);
if (event.isCanceled()) return false;
approved.add(pos.immutable());
return true;
}
@Override
public boolean shouldDamageEntity(Explosion explosion, Entity entity) {
if (damaged >= maxEntities || !eligibleEntity(entity, playerDamage)
|| maxDamage == 0) return false;
damaged++;
damagedEntities.add(entity.getUUID());
return true;
}
@Override
public float getEntityDamageAmount(Explosion explosion, Entity entity) {
return Math.min(super.getEntityDamageAmount(explosion, entity), maxDamage);
}
@Override
public float getKnockbackMultiplier(Entity entity) {
return damagedEntities.contains(entity.getUUID()) ? 1.0F : 0.0F;
}
private boolean inLoadedChunk(BlockPos pos) {
return level.isInWorldBounds(pos) && new ChunkPos(pos).equals(chunk)
&& level.getChunkSource().hasChunk(chunk.x, chunk.z);
}
}
}
@@ -0,0 +1,64 @@
package net.dnorberg.rivencraft.book;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.datafix.DataFixTypes;
import net.minecraft.world.level.saveddata.SavedData;
/** Per-Age hazard sequence and cooldowns survive unloads and server restarts. */
public final class AgeHazardSavedData extends SavedData {
private static final Factory<AgeHazardSavedData> FACTORY = new Factory<>(AgeHazardSavedData::new,
AgeHazardSavedData::load, DataFixTypes.SAVED_DATA_MAP_DATA);
private long attempts;
private long lastLightning = Long.MIN_VALUE;
private long lastExplosion = Long.MIN_VALUE;
private long lastMeteor = Long.MIN_VALUE;
public static AgeHazardSavedData get(ServerLevel level) {
return level.getDataStorage().computeIfAbsent(FACTORY, "rivencraft_hazards");
}
public long nextAttempt() {
setDirty();
return attempts++;
}
public boolean ready(boolean lightning, long gameTime, int interval) {
long last = lightning ? lastLightning : lastExplosion;
return last == Long.MIN_VALUE || gameTime < last || gameTime - last >= interval;
}
public void record(boolean lightning, long gameTime) {
if (lightning) lastLightning = gameTime;
else lastExplosion = gameTime;
setDirty();
}
public boolean meteorReady(long gameTime, int interval) {
return lastMeteor == Long.MIN_VALUE || gameTime < lastMeteor || gameTime - lastMeteor >= interval;
}
public void recordMeteor(long gameTime) {
lastMeteor = gameTime;
setDirty();
}
@Override
public CompoundTag save(CompoundTag tag, HolderLookup.Provider registries) {
tag.putLong("Attempts", attempts);
tag.putLong("LastLightning", lastLightning);
tag.putLong("LastExplosion", lastExplosion);
tag.putLong("LastMeteor", lastMeteor);
return tag;
}
static AgeHazardSavedData load(CompoundTag tag, HolderLookup.Provider registries) {
AgeHazardSavedData data = new AgeHazardSavedData();
data.attempts = Math.max(0L, tag.getLong("Attempts"));
if (tag.contains("LastLightning")) data.lastLightning = tag.getLong("LastLightning");
if (tag.contains("LastExplosion")) data.lastExplosion = tag.getLong("LastExplosion");
if (tag.contains("LastMeteor")) data.lastMeteor = tag.getLong("LastMeteor");
return data;
}
}
@@ -1,15 +1,38 @@
package net.dnorberg.rivencraft.book; package net.dnorberg.rivencraft.book;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import net.dnorberg.rivencraft.writing.WritingGrammar; import net.dnorberg.rivencraft.writing.WritingGrammar;
import net.minecraft.core.RegistryAccess;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.resources.ResourceLocation;
/** Frozen, server-owned score. Only new Age creation consults the current symbol catalog. */ /** Frozen, server-owned score. Only new Age creation consults the current symbol catalog. */
public record AgeInstability(int version, int score, List<Contribution> breakdown) { public record AgeInstability(int version, int score, List<Contribution> breakdown) {
public static final int CURRENT_VERSION = 1; public static final int CURRENT_VERSION = 1;
private static final int BRIGHT_LIGHTING_COST = 500;
private static final int EXCESS_LEGACY_STRUCTURE_COST = 100;
private static final int FORCED_STRUCTURE_BIOME_COST = 100;
private static final Map<ResourceLocation, String> COUNTED_STRUCTURES = Map.ofEntries(
Map.entry(id("mineshafts"), "Mineshafts"),
Map.entry(id("nether_fortresses"), "Nether Fortresses"),
Map.entry(id("strongholds"), "Strongholds"),
Map.entry(id("villages"), "Villages"),
Map.entry(id("bastions"), "Bastions"),
Map.entry(id("trial_chambers"), "Trial Chambers"),
Map.entry(id("ancient_cities"), "Ancient Cities"),
Map.entry(id("shipwrecks"), "Shipwrecks"),
Map.entry(id("ocean_ruins"), "Ocean Ruins"),
Map.entry(id("pillager_outposts"), "Pillager Outposts"),
Map.entry(id("ruined_portals"), "Ruined Portals"),
Map.entry(id("nether_fossils"), "Nether Fossils"),
Map.entry(id("buried_treasure"), "Buried Treasure"),
Map.entry(id("trail_ruins"), "Trail Ruins")
);
public AgeInstability { public AgeInstability {
if (version != CURRENT_VERSION) throw new IllegalArgumentException("Unsupported instability version " + version); if (version != CURRENT_VERSION) throw new IllegalArgumentException("Unsupported instability version " + version);
@@ -25,7 +48,7 @@ public record AgeInstability(int version, int score, List<Contribution> breakdow
List.of(new Contribution("legacy_neutral", -1, 0, "Age predates frozen instability scoring"))); List.of(new Contribution("legacy_neutral", -1, 0, "Age predates frozen instability scoring")));
} }
static AgeInstability compute(AgeGenerationPlan plan, AgeTraits traits) { static AgeInstability compute(AgeGenerationPlan plan, AgeTraits traits, RegistryAccess registries) {
Objects.requireNonNull(traits, "traits"); Objects.requireNonNull(traits, "traits");
List<Contribution> contributions = new ArrayList<>(); List<Contribution> contributions = new ArrayList<>();
if (plan == null) { if (plan == null) {
@@ -40,21 +63,69 @@ public record AgeInstability(int version, int score, List<Contribution> breakdow
contributions.add(new Contribution(diagnostic.code().name().toLowerCase(java.util.Locale.ROOT), contributions.add(new Contribution(diagnostic.code().name().toLowerCase(java.util.Locale.ROOT),
diagnostic.index(), diagnostic.instability(), diagnostic.message())); diagnostic.index(), diagnostic.instability(), diagnostic.message()));
} }
addAuditedSymbolCosts(plan, registries, contributions);
} }
// Legacy's bright-lighting symbol adds +500. Other balance costs are deferred // A missing lighting controller is seed-completed. Legacy runs the generated
// until their corresponding authored symbols and audited values exist. // symbol's own modifier, so a generated Bright Lighting choice still costs 500.
if (traits.lighting() == AgeTraits.Lighting.BRIGHT) { if (traits.lighting() == AgeTraits.Lighting.BRIGHT && (plan == null || plan.symbols().stream()
int pageIndex = plan == null ? -1 : plan.activeSymbols().stream() .noneMatch(symbol -> symbol.semantics().role()
.filter(symbol -> symbol.semantics().role() == net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING))) {
== net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING) contributions.add(new Contribution("bright_lighting", -1, BRIGHT_LIGHTING_COST,
.mapToInt(AgeGenerationPlan.ResolvedSymbol::index).findFirst().orElse(-1); "Seeded bright lighting"));
contributions.add(new Contribution("bright_lighting", pageIndex, 500,
pageIndex < 0 ? "Seeded bright lighting" : "Authored bright lighting"));
} }
return new AgeInstability(CURRENT_VERSION, return new AgeInstability(CURRENT_VERSION,
contributions.stream().mapToInt(Contribution::points).sum(), contributions); contributions.stream().mapToInt(Contribution::points).sum(), contributions);
} }
private static void addAuditedSymbolCosts(AgeGenerationPlan plan, RegistryAccess registries,
List<Contribution> contributions) {
Map<ResourceLocation, Integer> structureCounts = new HashMap<>();
for (AgeGenerationPlan.ResolvedSymbol symbol : plan.symbols()) {
if (symbol.semantics().role()
== net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING
&& symbol.semantics().value()
instanceof net.dnorberg.rivencraft.writing.SymbolSemantics.ChoiceValue choice
&& choice.id().equals("bright")) {
contributions.add(new Contribution("bright_lighting", symbol.index(), BRIGHT_LIGHTING_COST,
"Authored bright lighting"));
continue;
}
if (symbol.semantics().role()
!= net.dnorberg.rivencraft.writing.SymbolSemantics.Role.FEATURE
|| !(symbol.semantics().value()
instanceof net.dnorberg.rivencraft.writing.SymbolSemantics.ResourceValue resource)) continue;
String name = COUNTED_STRUCTURES.get(resource.id());
if (name == null) continue;
int count = structureCounts.merge(resource.id(), 1, Integer::sum);
if (!AgeStructureSelection.biomeCompatible(resource.id(), plan.biomeSelection(), registries)) {
contributions.add(new Contribution("forced_biome_" + resource.id().getPath(), symbol.index(),
FORCED_STRUCTURE_BIOME_COST,
name + " occurrence " + count + " is forced into an unsupported biome"));
}
int cost = featureCost(resource.id(), count);
if (cost > 0) {
contributions.add(new Contribution("excess_" + resource.id().getPath(), symbol.index(),
cost,
name + " occurrence " + count + " exceeds Legacy's first three free occurrences"));
}
}
}
static int featureCost(ResourceLocation feature, int occurrence) {
if (occurrence < 1) throw new IllegalArgumentException("Feature occurrence must be positive");
return COUNTED_STRUCTURES.containsKey(feature) && occurrence > 3
? EXCESS_LEGACY_STRUCTURE_COST : 0;
}
/** Current totals exposed to diagnostics. Player-driven mutable bonuses are deliberately disabled. */
public Totals totals() {
return new Totals(score, 0, 0, score);
}
private static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath("rivencraft", path);
}
public CompoundTag save() { public CompoundTag save() {
CompoundTag tag = new CompoundTag(); CompoundTag tag = new CompoundTag();
tag.putInt("Version", version); tag.putInt("Version", version);
@@ -92,4 +163,13 @@ public record AgeInstability(int version, int score, List<Contribution> breakdow
} }
} }
} }
public record Totals(int baseScore, int stabilityBonus, int instabilityPenalty, int effectiveScore) {
public Totals {
if (baseScore < 0 || stabilityBonus < 0 || instabilityPenalty < 0
|| effectiveScore != Math.max(0, baseScore + instabilityPenalty - stabilityBonus)) {
throw new IllegalArgumentException("Invalid instability totals");
}
}
}
} }
@@ -0,0 +1,78 @@
package net.dnorberg.rivencraft.book;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.resources.ResourceLocation;
/** Frozen provider selection; handler availability and server settings never reroll this plan. */
public record AgeInstabilityPlan(int version, List<ProviderLevel> providers) {
public static final int CURRENT_VERSION = 1;
public AgeInstabilityPlan {
if (version != CURRENT_VERSION) throw new IllegalArgumentException("Unsupported provider-plan version " + version);
providers = List.copyOf(providers);
if (providers.stream().map(ProviderLevel::id).distinct().count() != providers.size()) {
throw new IllegalArgumentException("Duplicate provider ID in saved Age plan");
}
}
public static AgeInstabilityPlan empty() { return new AgeInstabilityPlan(CURRENT_VERSION, List.of()); }
public static AgeInstabilityPlan select(AgeInstability instability, long ageSeed) {
int roundedScore = instability.score() / 500 * 500;
Map<ResourceLocation, Integer> levels = new LinkedHashMap<>();
for (InstabilityProviderCatalog.Deck deck : InstabilityProviderCatalog.Deck.values()) {
int remaining = roundedScore - deck.entryCost();
if (remaining <= 0) continue;
List<InstabilityProviderCatalog.Card> cards = new ArrayList<>(InstabilityProviderCatalog.cards(deck));
Collections.shuffle(cards, new Random(ageSeed ^ (0x9E3779B97F4A7C15L * (deck.ordinal() + 1))));
for (InstabilityProviderCatalog.Card card : cards) {
if (remaining < card.cost()) break;
remaining -= card.cost();
levels.merge(card.id(), 1, Integer::sum);
}
}
return new AgeInstabilityPlan(CURRENT_VERSION, levels.entrySet().stream()
.map(entry -> new ProviderLevel(entry.getKey(), entry.getValue())).toList());
}
public CompoundTag save() {
CompoundTag tag = new CompoundTag();
tag.putInt("Version", version);
ListTag entries = new ListTag();
for (ProviderLevel provider : providers) {
CompoundTag entry = new CompoundTag();
entry.putString("Id", provider.id().toString());
entry.putInt("Level", provider.level());
entries.add(entry);
}
tag.put("Providers", entries);
return tag;
}
public static AgeInstabilityPlan load(CompoundTag tag) {
ListTag entries = tag.getList("Providers", CompoundTag.TAG_COMPOUND);
List<ProviderLevel> providers = new ArrayList<>();
for (int index = 0; index < entries.size(); index++) {
CompoundTag entry = entries.getCompound(index);
ResourceLocation id = ResourceLocation.tryParse(entry.getString("Id"));
if (id == null) throw new IllegalArgumentException("Invalid saved instability provider ID at " + index);
providers.add(new ProviderLevel(id, entry.getInt("Level")));
}
return new AgeInstabilityPlan(tag.getInt("Version"), providers);
}
public record ProviderLevel(ResourceLocation id, int level) {
public ProviderLevel {
Objects.requireNonNull(id, "id");
if (level < 1 || level > 255) throw new IllegalArgumentException("Invalid provider level " + level);
}
}
}
@@ -0,0 +1,181 @@
package net.dnorberg.rivencraft.book;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.WeakHashMap;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.ChunkPos;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.neoforged.neoforge.event.tick.LevelTickEvent;
/** Server-only scheduler. Effect handlers are registered by later provider slices. */
public final class AgeInstabilityRuntime {
private static final Map<ResourceLocation, Handler> HANDLERS = new HashMap<>();
private static final Map<MinecraftServer, TickState> TICKS = new WeakHashMap<>();
private static final Map<ServerLevel, Map<ResourceLocation, Long>> FAILURES = new WeakHashMap<>();
private static final Set<ResourceLocation> UNKNOWN_LOGGED = new HashSet<>();
private AgeInstabilityRuntime() {}
/** Register once during mod setup. Missing optional handlers never alter saved provider IDs. */
public static void register(ResourceLocation id, boolean worldMutating, ProviderEffect effect) {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(effect, "effect");
if (HANDLERS.putIfAbsent(id, new Handler(worldMutating, effect)) != null) {
throw new IllegalArgumentException("Duplicate instability handler " + id);
}
}
public static void onLevelTickPost(LevelTickEvent.Post event) {
if (!(event.getLevel() instanceof ServerLevel level) || !RivencraftConfig.instabilityEnabled()
|| !isAgeDimension(level.dimension().location()) || level.players().isEmpty()) return;
MinecraftServer server = level.getServer();
long tick = server.getTickCount();
int cooldown = RivencraftConfig.instabilityCooldown();
if (tick % cooldown != 0) return;
TickState state = TICKS.computeIfAbsent(server, ignored -> new TickState());
if (state.tick != tick) {
state.tick = tick;
state.eligible = loadedPlayerAges(server);
}
if (!admitted(state.eligible, level.dimension().location(), tick / cooldown,
RivencraftConfig.instabilityMaxAges())) return;
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
if (age == null || age.instabilityPlan().providers().isEmpty()) return;
// Legacy's per-chunk hazards must not wait for the rotating two-provider sample.
AgeHazardProviders.tickPlanned(level, age, tick);
AgeEnvironmentalProviders.tickPlanned(level, age, tick);
List<ChunkPos> chunks = loadedChunksNearPlayers(level, RivencraftConfig.instabilityMaxChunks());
if (chunks.isEmpty()) return;
Budget budget = new Budget(RivencraftConfig.instabilityMaxActions());
Context context = new Context(level, age, chunks, tick, budget);
List<AgeInstabilityPlan.ProviderLevel> providers = age.instabilityPlan().providers();
int first = (int) Math.floorMod(tick / cooldown + age.seed(), providers.size());
int ran = 0;
for (int offset = 0; offset < providers.size() && ran < RivencraftConfig.instabilityMaxProviders()
&& budget.remaining() > 0; offset++) {
AgeInstabilityPlan.ProviderLevel provider = providers.get((first + offset) % providers.size());
if (AgeHazardProviders.isHazard(provider.id())
|| AgeEnvironmentalProviders.isEnvironmental(provider.id())) continue;
if (invoke(context, provider.id(), provider.level())) ran++;
}
}
/** Shared handler guard, including quarantine, for rotating and per-chunk provider lanes. */
static boolean invoke(Context context, ResourceLocation id, int level) {
Handler handler = HANDLERS.get(id);
if (handler == null) {
if (!InstabilityProviderCatalog.contains(id) && UNKNOWN_LOGGED.add(id)) {
Rivencraft.LOGGER.warn("Saved Age references unknown instability provider {}; skipping it", id);
}
return false;
}
if (handler.worldMutating() && !RivencraftConfig.instabilityWorldMutation()) return false;
long retryAfter = FAILURES.computeIfAbsent(context.level(), ignored -> new HashMap<>())
.getOrDefault(id, 0L);
if (context.serverTick() < retryAfter) return false;
try {
handler.effect().apply(context, id,
Math.min(level, RivencraftConfig.instabilityMaxLevel()));
} catch (RuntimeException exception) {
FAILURES.get(context.level()).put(id, context.serverTick()
+ Math.max(200L, RivencraftConfig.instabilityCooldown() * 10L));
Rivencraft.LOGGER.error("Instability provider {} failed in Age {}; temporarily quarantined",
id, context.age().id(), exception);
}
return true;
}
public static void onServerStopping(ServerStoppingEvent event) {
TICKS.remove(event.getServer());
FAILURES.clear();
UNKNOWN_LOGGED.clear();
}
public static boolean isAgeDimension(ResourceLocation id) {
return id.getNamespace().equals(Rivencraft.MOD_ID) && id.getPath().startsWith("age/");
}
static boolean admitted(List<ResourceLocation> eligible, ResourceLocation id, long run,
int maximum) {
int index = eligible.indexOf(id);
if (index < 0 || maximum < 1) return false;
if (eligible.size() <= maximum) return true;
return Math.floorMod(index - (int) Math.floorMod(run, eligible.size()), eligible.size()) < maximum;
}
private static List<ResourceLocation> loadedPlayerAges(MinecraftServer server) {
List<ResourceLocation> eligible = new ArrayList<>();
AgeRegistrySavedData registry = AgeRegistrySavedData.get(server.overworld());
for (ServerLevel level : server.getAllLevels()) {
ResourceLocation id = level.dimension().location();
if (isAgeDimension(id) && !level.players().isEmpty()
&& registry.findByDimension(id).filter(age -> !age.instabilityPlan().providers().isEmpty())
.isPresent()) eligible.add(id);
}
eligible.sort(Comparator.comparing(ResourceLocation::toString));
return List.copyOf(eligible);
}
private static List<ChunkPos> loadedChunksNearPlayers(ServerLevel level, int maximum) {
Set<ChunkPos> chunks = new LinkedHashSet<>();
for (var player : level.players()) {
ChunkPos center = player.chunkPosition();
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {
int x = center.x + dx;
int z = center.z + dz;
if (level.getChunkSource().hasChunk(x, z)) chunks.add(new ChunkPos(x, z));
if (chunks.size() >= maximum) return List.copyOf(chunks);
}
}
}
return List.copyOf(chunks);
}
@FunctionalInterface
public interface ProviderEffect {
/** Claim budget before each effect action; only use chunks supplied in the context. */
void apply(Context context, ResourceLocation id, int effectiveLevel);
}
public record Context(ServerLevel level, AgeDefinition age, List<ChunkPos> loadedChunks,
long serverTick, Budget budget) {
public Context { loadedChunks = List.copyOf(loadedChunks); }
}
public static final class Budget {
private int remaining;
public Budget(int maximum) {
if (maximum < 0) throw new IllegalArgumentException("Negative work budget");
remaining = maximum;
}
public boolean claim() {
if (remaining == 0) return false;
remaining--;
return true;
}
public int remaining() { return remaining; }
}
private record Handler(boolean worldMutating, ProviderEffect effect) {}
private static final class TickState {
private long tick = Long.MIN_VALUE;
private List<ResourceLocation> eligible = List.of();
}
}
@@ -0,0 +1,167 @@
package net.dnorberg.rivencraft.book;
import java.util.List;
import java.util.UUID;
import net.dnorberg.rivencraft.Rivencraft;
import net.minecraft.core.BlockPos;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.GameType;
import net.neoforged.neoforge.gametest.GameTestHolder;
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
/** Pure server-side provider-plan and scheduler-boundary checks for issue #66. */
@GameTestHolder(Rivencraft.MOD_ID)
@PrefixGameTestTemplate(false)
public final class AgeInstabilityRuntimeGameTests {
private AgeInstabilityRuntimeGameTests() {}
@GameTest(template = "empty")
public static void selectionIsDeterministicAndFrozen(GameTestHelper helper) {
AgeInstability score = new AgeInstability(AgeInstability.CURRENT_VERSION, 30_000,
List.of(new AgeInstability.Contribution("fixture", -1, 30_000, "provider selection")));
AgeInstabilityPlan first = AgeInstabilityPlan.select(score, 44L);
helper.assertTrue(!first.providers().isEmpty(), "An eligible score must select providers");
helper.assertValueEqual(AgeInstabilityPlan.select(score, 44L), first,
"The same Age seed and frozen score must select the same providers");
helper.assertValueEqual(AgeInstabilityPlan.load(first.save()), first,
"Saved provider IDs and levels must survive a round trip");
helper.assertTrue(first.providers().stream().allMatch(provider -> provider.level() > 0
&& InstabilityProviderCatalog.contains(provider.id())),
"Only audited providers with positive levels may be selected");
helper.assertTrue(AgeInstabilityPlan.select(AgeInstability.legacyNeutral(), 44L)
.providers().isEmpty(), "Neutral old Ages must stay inert");
helper.succeed();
}
@GameTest(template = "empty")
public static void savedPlanSurvivesAgeUpdatesAndMissingHandlers(GameTestHelper helper) {
ResourceLocation optional = ResourceLocation.parse("example:optional_provider");
AgeInstabilityPlan plan = new AgeInstabilityPlan(1,
List.of(new AgeInstabilityPlan.ProviderLevel(optional, 2)));
helper.assertValueEqual(AgeInstabilityPlan.load(plan.save()), plan,
"A syntactically valid provider ID must persist even if no handler is installed");
UUID id = UUID.randomUUID();
AgeDefinition age = new AgeDefinition(id, "Runtime", 91L, AgeGenerationProfiles.STANDARD,
AgeDefinition.CURRENT_GENERATION_VERSION, 0L, AgeDefinition.dimensionId(id), null,
AgeTraits.LEGACY_DEFAULTS, null, null, List.of(), AgeInstability.legacyNeutral(), plan);
helper.assertValueEqual(age.withSpawn(new BlockPos(1, 64, 2)).instabilityPlan(), plan,
"Setting an Age spawn must not reroll selected providers");
CompoundTag corrupt = plan.save();
corrupt.getList("Providers", CompoundTag.TAG_COMPOUND).getCompound(0)
.putString("Id", "bad provider id");
boolean rejected = false;
try { AgeInstabilityPlan.load(corrupt); }
catch (IllegalArgumentException expected) { rejected = true; }
helper.assertTrue(rejected, "Malformed provider IDs must fail clearly");
helper.succeed();
}
@GameTest(template = "empty")
public static void ageScopeRotationAndActionBudgetAreBounded(GameTestHelper helper) {
ResourceLocation first = ResourceLocation.parse("rivencraft:age/first");
ResourceLocation second = ResourceLocation.parse("rivencraft:age/second");
ResourceLocation third = ResourceLocation.parse("rivencraft:age/third");
helper.assertTrue(!AgeInstabilityRuntime.isAgeDimension(helper.getLevel().dimension().location()),
"The GameTest Overworld must never be treated as an Age");
helper.assertTrue(!AgeInstabilityRuntime.isAgeDimension(ResourceLocation.parse("rivencraft:preview")),
"Preview worlds must not receive Age effects");
List<ResourceLocation> loaded = List.of(first, second, third);
helper.assertTrue(AgeInstabilityRuntime.admitted(loaded, first, 0, 1)
&& AgeInstabilityRuntime.admitted(loaded, second, 1, 1)
&& AgeInstabilityRuntime.admitted(loaded, third, 2, 1),
"A global cap must rotate fairly among loaded Ages");
AgeInstabilityRuntime.Budget budget = new AgeInstabilityRuntime.Budget(2);
helper.assertTrue(budget.claim() && budget.claim() && !budget.claim(),
"A handler cannot claim more actions than the Age budget");
helper.assertValueEqual(budget.remaining(), 0, "The budget must not go negative");
helper.succeed();
}
@GameTest(template = "empty")
public static void hazardCooldownAndAttemptSequenceSurviveReload(GameTestHelper helper) {
AgeHazardSavedData data = new AgeHazardSavedData();
helper.assertTrue(data.ready(true, 1000, 200) && data.ready(false, 1000, 200),
"Each hazard type starts eligible independently");
helper.assertValueEqual(data.nextAttempt(), 0L, "First hazard roll has a stable sequence");
data.record(true, 1000);
helper.assertTrue(!data.ready(true, 1199, 200) && data.ready(false, 1199, 200),
"Lightning cooldown must not suppress explosions");
AgeHazardSavedData restored = AgeHazardSavedData.load(
data.save(new CompoundTag(), helper.getLevel().registryAccess()),
helper.getLevel().registryAccess());
helper.assertValueEqual(restored.nextAttempt(), 1L, "Restart must not replay the previous roll");
helper.assertTrue(!restored.ready(true, 1199, 200) && restored.ready(true, 1200, 200),
"Reloaded cooldown must still enforce the minimum interval");
helper.assertTrue(restored.meteorReady(1200, 200), "Meteor cooldown starts independently");
restored.recordMeteor(1200);
AgeHazardSavedData meteorReloaded = AgeHazardSavedData.load(
restored.save(new CompoundTag(), helper.getLevel().registryAccess()),
helper.getLevel().registryAccess());
helper.assertTrue(!meteorReloaded.meteorReady(1399, 200)
&& meteorReloaded.meteorReady(1400, 200),
"A meteor attempt must not replay immediately after restart");
helper.succeed();
}
@GameTest(template = "empty")
public static void environmentalCardsPreserveLegacyDeckAndAgeScope(GameTestHelper helper) {
helper.assertTrue(InstabilityProviderCatalog.contains(ResourceLocation.parse("rivencraft:meteors"))
&& InstabilityProviderCatalog.contains(ResourceLocation.parse("rivencraft:burning")),
"Meteor and burning must retain their audited Legacy deck cards");
helper.assertTrue(!InstabilityProviderCatalog.contains(ResourceLocation.parse("rivencraft:erosion")),
"Enabling dormant erosion must not silently change frozen provider selection");
var level = helper.getLevel();
var budget = new AgeInstabilityRuntime.Budget(1);
var age = new AgeDefinition(UUID.randomUUID(), "Fixture", 1L, AgeGenerationProfiles.STANDARD,
AgeDefinition.CURRENT_GENERATION_VERSION, 0L,
ResourceLocation.parse("rivencraft:age/fixture"), null,
AgeTraits.LEGACY_DEFAULTS, null, null, List.of(), AgeInstability.legacyNeutral(),
AgeInstabilityPlan.empty());
var context = new AgeInstabilityRuntime.Context(level, age, List.of(new net.minecraft.world.level.ChunkPos(0, 0)),
level.getServer().getTickCount(), budget);
helper.assertTrue(AgeEnvironmentalProviders.matchesAge(age, age.dimensionId())
&& !AgeEnvironmentalProviders.matchesAge(age, ResourceLocation.parse("rivencraft:age/other"))
&& !AgeEnvironmentalProviders.matchesAge(age, level.dimension().location()),
"One player's environmental Age effects must not leak into another Age or the Overworld");
for (String path : List.of("meteors", "burning", "erosion")) {
AgeEnvironmentalProviders.apply(context, ResourceLocation.parse("rivencraft:" + path), 1);
}
helper.assertValueEqual(budget.remaining(), 1,
"Environmental effects must never run in the GameTest Overworld");
helper.succeed();
}
@GameTest(template = "empty")
public static void burningPersistsOnDrySurvivalPlayer(GameTestHelper helper) {
var player = helper.makeMockServerPlayerInLevel();
player.setGameMode(GameType.SURVIVAL);
player.igniteForSeconds(4);
helper.assertTrue(player.getRemainingFireTicks() >= 79,
"Burning should set at least four seconds of server-side fire ticks");
helper.runAfterDelay(2, () -> {
helper.assertTrue(player.isOnFire() && player.getRemainingFireTicks() > 0,
"A dry survival player should remain on fire after Minecraft ticks the entity");
helper.succeed();
});
}
@GameTest(template = "empty")
public static void hazardRollMatchesLegacyChunkOpportunity(GameTestHelper helper) {
double oneChunk = AgeHazardProviders.legacyChance(1, 1, 1, 1000);
double nearby = AgeHazardProviders.legacyChance(81, 20, 1, 1000);
double thunder = AgeHazardProviders.legacyChance(81, 20, 1, 5000);
double clear = AgeHazardProviders.legacyChance(81, 20, 1, 100000);
helper.assertTrue(Math.abs(oneChunk - 0.001) < 0.000001,
"One chunk tick must retain Legacy's 1/1000 explosion roll");
helper.assertTrue(nearby > 0.79 && nearby < 0.82,
"Nearby loaded chunks must produce frequent bounded explosions");
helper.assertTrue(thunder > clear && clear > 0,
"Legacy lightning must be more frequent in thunder than clear weather");
helper.assertTrue(AgeHazardProviders.legacyChance(0, 20, 1, 1000) == 0,
"Unloaded chunks must never produce a hazard opportunity");
helper.succeed();
}
}
@@ -58,6 +58,8 @@ public final class AgePersistenceGameTests {
helper.assertValueEqual(restored, created, "The complete plan must survive a saved-data round trip"); helper.assertValueEqual(restored, created, "The complete plan must survive a saved-data round trip");
helper.assertValueEqual(restored.instability(), created.instability(), helper.assertValueEqual(restored.instability(), created.instability(),
"The complete instability breakdown must survive reload"); "The complete instability breakdown must survive reload");
helper.assertValueEqual(restored.instabilityPlan(), created.instabilityPlan(),
"The selected provider levels must not reroll on reload");
helper.assertValueEqual(registry.instability(id).orElseThrow(), created.instability(), helper.assertValueEqual(registry.instability(id).orElseThrow(), created.instability(),
"The server diagnostic query must return the saved score"); "The server diagnostic query must return the saved score");
helper.succeed(); helper.succeed();
@@ -90,6 +92,23 @@ public final class AgePersistenceGameTests {
AgeDefinition reused = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(), AgeDefinition reused = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
new AgeReference(defectiveAge.id(), "Changed Name"), stable); new AgeReference(defectiveAge.id(), "Changed Name"), stable);
helper.assertValueEqual(reused, defectiveAge, "Repeated book use must not rescore an Age"); helper.assertValueEqual(reused, defectiveAge, "Repeated book use must not rescore an Age");
CompoundTag scoreOnlySave = AgeRegistrySavedData.get(helper.getLevel())
.save(new CompoundTag(), helper.getLevel().registryAccess());
ListTag savedAges = scoreOnlySave.getList("Ages", CompoundTag.TAG_COMPOUND);
for (int index = 0; index < savedAges.size(); index++) {
CompoundTag entry = savedAges.getCompound(index);
if (entry.getUUID("Id").equals(defectiveAge.id())) entry.remove("InstabilityPlan");
}
AgeRegistrySavedData migrated = AgeRegistrySavedData.load(scoreOnlySave,
helper.getLevel().registryAccess());
AgeDefinition migratedAge = migrated.find(defectiveAge.id()).orElseThrow();
helper.assertValueEqual(migratedAge.instabilityPlan(),
AgeInstabilityPlan.select(defectiveAge.instability(), defectiveAge.seed()),
"A score-only save must receive one deterministic provider migration");
helper.assertValueEqual(AgeRegistrySavedData.load(
migrated.save(new CompoundTag(), helper.getLevel().registryAccess()),
helper.getLevel().registryAccess()).find(defectiveAge.id()).orElseThrow().instabilityPlan(),
migratedAge.instabilityPlan(), "Migrated provider selection must then remain frozen");
helper.succeed(); helper.succeed();
} }
@@ -106,13 +125,91 @@ public final class AgePersistenceGameTests {
AgeInstability bright = AgeInstability.compute(null, new AgeTraits( AgeInstability bright = AgeInstability.compute(null, new AgeTraits(
AgeTraits.LEGACY_DEFAULTS.biomeDistribution(), AgeTraits.Lighting.BRIGHT, AgeTraits.LEGACY_DEFAULTS.biomeDistribution(), AgeTraits.Lighting.BRIGHT,
AgeTraits.LEGACY_DEFAULTS.weather(), AgeTraits.LEGACY_DEFAULTS.celestialPeriod(), AgeTraits.LEGACY_DEFAULTS.weather(), AgeTraits.LEGACY_DEFAULTS.celestialPeriod(),
AgeTraits.LEGACY_DEFAULTS.celestialAngle(), AgeTraits.LEGACY_DEFAULTS.celestialPhase())); AgeTraits.LEGACY_DEFAULTS.celestialAngle(), AgeTraits.LEGACY_DEFAULTS.celestialPhase()),
helper.getLevel().registryAccess());
helper.assertValueEqual(bright.score(), 500, "Bright lighting has the audited Legacy cost"); helper.assertValueEqual(bright.score(), 500, "Bright lighting has the audited Legacy cost");
helper.assertValueEqual(AgeInstability.load(bright.save()), bright, helper.assertValueEqual(AgeInstability.load(bright.save()), bright,
"A score must survive its own versioned round trip"); "A score must survive its own versioned round trip");
helper.succeed(); helper.succeed();
} }
@GameTest(template = "empty")
public static void auditedSymbolCostsAreCountedAndAgeScoped(GameTestHelper helper) {
List<String> legacyStructures = List.of("mineshafts", "nether_fortresses", "strongholds", "villages");
for (String structure : legacyStructures) {
AgeDefinition three = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
new AgeReference(UUID.randomUUID(), "Three " + structure), structureWriting(structure, 3));
AgeDefinition four = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
new AgeReference(UUID.randomUUID(), "Four " + structure), structureWriting(structure, 4));
helper.assertValueEqual(three.instability().score(), 0,
"The first three " + structure + " pages retain Legacy's zero cost");
helper.assertValueEqual(four.instability().score(), 100,
"The fourth " + structure + " page must add Legacy's 100-point cost");
helper.assertTrue(four.instability().breakdown().stream().anyMatch(part ->
part.reason().equals("excess_" + structure) && part.pageIndex() == 8),
"The excess structure cost must identify its authored page");
}
for (String structure : List.of("bastions", "trial_chambers", "ancient_cities", "shipwrecks",
"ocean_ruins", "pillager_outposts", "ruined_portals", "nether_fossils", "buried_treasure",
"trail_ruins")) {
ResourceLocation id = ResourceLocation.fromNamespaceAndPath("rivencraft", structure);
helper.assertTrue(AgeInstability.featureCost(id, 1) == 0
&& AgeInstability.featureCost(id, 3) == 0
&& AgeInstability.featureCost(id, 4) == 100
&& AgeInstability.featureCost(id, 5) == 100,
structure + " must follow the selected Legacy Mineshaft repeat rule");
}
helper.assertValueEqual(AgeInstability.featureCost(
ResourceLocation.parse("rivencraft:trial_chambers"), 4), 100,
"Modern repeated structures must use the same deterministic scoring path");
helper.assertValueEqual(AgeInstability.featureCost(ResourceLocation.parse("rivencraft:dungeons"), 4), 0,
"A Legacy-neutral feature must remain neutral when repeated");
OrderedWriting duplicateBright = new OrderedWriting(List.of(
WritingEntry.linkPanel(),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:terrain/standard"))),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:lighting/bright"))),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:lighting/bright")))
));
AgeDefinition bright = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
new AgeReference(UUID.randomUUID(), "Double Bright"), duplicateBright);
helper.assertValueEqual(bright.instability().score(), 1500,
"Each Bright Lighting page costs 500 and the extra controller costs another 500");
helper.assertValueEqual(bright.instability().breakdown().stream()
.filter(part -> part.reason().equals("bright_lighting")).count(), 2L,
"Every authored Bright Lighting occurrence must retain its own cost");
AgeInstability.Totals totals = bright.instability().totals();
helper.assertValueEqual(totals.baseScore(), 1500, "Diagnostics must expose the immutable base score");
helper.assertTrue(totals.stabilityBonus() == 0 && totals.instabilityPenalty() == 0
&& totals.effectiveScore() == totals.baseScore(),
"Dormant player bonus classes must not create mutable, cross-Age credit");
AgeDefinition restored = AgeRegistrySavedData.load(
AgeRegistrySavedData.get(helper.getLevel()).save(new CompoundTag(), helper.getLevel().registryAccess()),
helper.getLevel().registryAccess()).find(bright.id()).orElseThrow();
helper.assertValueEqual(restored.instability().totals(), totals,
"The base/adjustment diagnostic must remain identical after reload");
helper.succeed();
}
private static OrderedWriting structureWriting(String structure, int count) {
boolean nether = structure.equals("nether_fortresses");
List<WritingEntry> entries = new java.util.ArrayList<>(List.of(
WritingEntry.linkPanel(),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse(
nether ? "rivencraft:terrain/cave" : "rivencraft:terrain/standard"))),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse(
nether ? "rivencraft:biome/nether_wastes" : "rivencraft:biome/plains"))),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:biome/single"))),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:lighting/normal")))
));
for (int index = 0; index < count; index++) {
entries.add(WritingEntry.symbol(new SymbolReference(
ResourceLocation.parse("rivencraft:feature/" + structure))));
}
return new OrderedWriting(entries);
}
@GameTest(template = "empty") @GameTest(template = "empty")
public static void missingRegistryEntryDoesNotReinterpretAnOldAge(GameTestHelper helper) { public static void missingRegistryEntryDoesNotReinterpretAnOldAge(GameTestHelper helper) {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
@@ -124,6 +221,8 @@ public final class AgePersistenceGameTests {
AgeRegistrySavedData old = AgeRegistrySavedData.load(root, helper.getLevel().registryAccess()); AgeRegistrySavedData old = AgeRegistrySavedData.load(root, helper.getLevel().registryAccess());
helper.assertValueEqual(old.instability(id).orElseThrow(), AgeInstability.legacyNeutral(), helper.assertValueEqual(old.instability(id).orElseThrow(), AgeInstability.legacyNeutral(),
"Old Ages without a score must migrate to a neutral saved value"); "Old Ages without a score must migrate to a neutral saved value");
helper.assertTrue(old.instabilityPlan(id).orElseThrow().providers().isEmpty(),
"Pre-score Ages must not acquire effects during migration");
helper.assertValueEqual(AgeRegistrySavedData.load( helper.assertValueEqual(AgeRegistrySavedData.load(
old.save(new CompoundTag(), helper.getLevel().registryAccess()), old.save(new CompoundTag(), helper.getLevel().registryAccess()),
helper.getLevel().registryAccess()).instability(id).orElseThrow(), AgeInstability.legacyNeutral(), helper.getLevel().registryAccess()).instability(id).orElseThrow(), AgeInstability.legacyNeutral(),
@@ -36,6 +36,7 @@ public final class AgeRegistrySavedData extends SavedData {
private static final String RANDOM_FEATURES_TAG = "RandomFeatures"; private static final String RANDOM_FEATURES_TAG = "RandomFeatures";
private static final String SEASON_MODE_TAG = "SeasonMode"; private static final String SEASON_MODE_TAG = "SeasonMode";
private static final String INSTABILITY_TAG = "Instability"; private static final String INSTABILITY_TAG = "Instability";
private static final String INSTABILITY_PLAN_TAG = "InstabilityPlan";
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";
@@ -95,6 +96,10 @@ public final class AgeRegistrySavedData extends SavedData {
return find(ageId).map(AgeDefinition::instability); return find(ageId).map(AgeDefinition::instability);
} }
public Optional<AgeInstabilityPlan> instabilityPlan(UUID ageId) {
return find(ageId).map(AgeDefinition::instabilityPlan);
}
public Optional<AgeDefinition> findByDimension(ResourceLocation dimensionId) { public Optional<AgeDefinition> findByDimension(ResourceLocation dimensionId) {
return ages.values().stream() return ages.values().stream()
.filter(age -> age.dimensionId().equals(dimensionId)) .filter(age -> age.dimensionId().equals(dimensionId))
@@ -130,7 +135,8 @@ public final class AgeRegistrySavedData extends SavedData {
AgeTraits traits = AgeTraits.select(seed); AgeTraits traits = AgeTraits.select(seed);
AgeGenerationPlan plan = AgeGenerationPlan.compile(writing, seed, seedProfile, traits, registries); AgeGenerationPlan plan = AgeGenerationPlan.compile(writing, seed, seedProfile, traits, registries);
AgeTraits effectiveTraits = AgeEnvironmentCompiler.apply(plan, traits); AgeTraits effectiveTraits = AgeEnvironmentCompiler.apply(plan, traits);
AgeInstability instability = AgeInstability.compute(plan, effectiveTraits); AgeInstability instability = AgeInstability.compute(plan, effectiveTraits, registries);
AgeInstabilityPlan instabilityPlan = AgeInstabilityPlan.select(instability, seed);
AgeDefinition created = new AgeDefinition( AgeDefinition created = new AgeDefinition(
reference.id(), reference.id(),
name, name,
@@ -145,7 +151,8 @@ public final class AgeRegistrySavedData extends SavedData {
AgeSeasonMode.select(plan, seed, ModList.get().isLoaded("sereneseasons")), AgeSeasonMode.select(plan, seed, ModList.get().isLoaded("sereneseasons")),
plan == null ? AgeFeatureSelection.randomChoices(seed, plan == null ? AgeFeatureSelection.randomChoices(seed,
AgeRuntimeProfiles.resolve(seedProfile), registries) : List.of(), AgeRuntimeProfiles.resolve(seedProfile), registries) : List.of(),
instability instability,
instabilityPlan
); );
ages.put(created.id(), created); ages.put(created.id(), created);
setDirty(); setDirty();
@@ -178,6 +185,19 @@ public final class AgeRegistrySavedData extends SavedData {
BlockPos spawn = entry.contains(SPAWN_Y_TAG) BlockPos spawn = entry.contains(SPAWN_Y_TAG)
? new BlockPos(entry.getInt(SPAWN_X_TAG), entry.getInt(SPAWN_Y_TAG), entry.getInt(SPAWN_Z_TAG)) ? new BlockPos(entry.getInt(SPAWN_X_TAG), entry.getInt(SPAWN_Y_TAG), entry.getInt(SPAWN_Z_TAG))
: null; : null;
AgeInstability instability = entry.contains(INSTABILITY_TAG, CompoundTag.TAG_COMPOUND)
? AgeInstability.load(entry.getCompound(INSTABILITY_TAG)) : AgeInstability.legacyNeutral();
AgeInstabilityPlan instabilityPlan;
if (entry.contains(INSTABILITY_PLAN_TAG, CompoundTag.TAG_COMPOUND)) {
instabilityPlan = AgeInstabilityPlan.load(entry.getCompound(INSTABILITY_PLAN_TAG));
} else {
// The previous release froze scores but did not yet choose providers.
// Migrate once from that frozen score, then persist the result.
instabilityPlan = entry.contains(INSTABILITY_TAG, CompoundTag.TAG_COMPOUND)
? AgeInstabilityPlan.select(instability, entry.getLong(SEED_TAG))
: AgeInstabilityPlan.empty();
data.setDirty();
}
data.ages.put(id, new AgeDefinition( data.ages.put(id, new AgeDefinition(
id, id,
normalizedName(entry.getString(NAME_TAG)), normalizedName(entry.getString(NAME_TAG)),
@@ -193,9 +213,8 @@ public final class AgeRegistrySavedData extends SavedData {
entry.contains(SEASON_MODE_TAG, CompoundTag.TAG_STRING) entry.contains(SEASON_MODE_TAG, CompoundTag.TAG_STRING)
? AgeSeasonMode.parseOrNull(entry.getString(SEASON_MODE_TAG)) : null, ? AgeSeasonMode.parseOrNull(entry.getString(SEASON_MODE_TAG)) : null,
readRandomFeatures(entry), readRandomFeatures(entry),
entry.contains(INSTABILITY_TAG, CompoundTag.TAG_COMPOUND) instability,
? AgeInstability.load(entry.getCompound(INSTABILITY_TAG)) instabilityPlan
: AgeInstability.legacyNeutral()
)); ));
} }
return data; return data;
@@ -241,6 +260,7 @@ public final class AgeRegistrySavedData extends SavedData {
} }
if (age.seasonMode() != null) entry.putString(SEASON_MODE_TAG, age.seasonMode().name()); if (age.seasonMode() != null) entry.putString(SEASON_MODE_TAG, age.seasonMode().name());
entry.put(INSTABILITY_TAG, age.instability().save()); entry.put(INSTABILITY_TAG, age.instability().save());
entry.put(INSTABILITY_PLAN_TAG, age.instabilityPlan().save());
serializedAges.add(entry); serializedAges.add(entry);
}); });
tag.put(AGES_TAG, serializedAges); tag.put(AGES_TAG, serializedAges);
@@ -0,0 +1,94 @@
package net.dnorberg.rivencraft.book;
import java.util.List;
import java.util.UUID;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.minecraft.core.BlockPos;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.GameType;
import net.neoforged.neoforge.gametest.GameTestHolder;
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
/** Focused mapping, targeting, and isolation checks for issue #67. */
@GameTestHolder(Rivencraft.MOD_ID)
@PrefixGameTestTemplate(false)
public final class AgeStatusEffectGameTests {
private AgeStatusEffectGameTests() {}
@GameTest(template = "empty")
public static void legacyPotionMappingRetainsShortDurationsAndSkyRule(GameTestHelper helper) {
helper.assertValueEqual(AgeStatusEffectProviders.legacyDuration(id("wither")), 30,
"Legacy Wither lasts only 30 ticks per application");
helper.assertValueEqual(AgeStatusEffectProviders.legacyDuration(id("poison_global")), 80,
"Global Poison retains Legacy's 80-tick duration");
helper.assertValueEqual(AgeStatusEffectProviders.legacyDuration(id("enemyregen_global")), 200,
"The enemy regeneration card retains its 200-tick duration");
helper.assertTrue(AgeStatusEffectProviders.localRequiresSky(id("poison"))
&& !AgeStatusEffectProviders.localRequiresSky(id("poison_global")),
"Only local potion cards require open sky");
helper.succeed();
}
@GameTest(template = "empty")
public static void generalDebuffsIncludeLivingEntitiesButCreativePlayersAreExempt(GameTestHelper helper) {
var player = helper.makeMockPlayer(GameType.SURVIVAL);
var cow = helper.spawnWithNoFreeWill(EntityType.COW, new BlockPos(1, 1, 1));
var hostile = helper.spawnWithNoFreeWill(EntityType.SPIDER, new BlockPos(2, 1, 1));
helper.assertTrue(player.isAlive(), "Mock survival player must be alive");
helper.assertTrue(player.level() == helper.getLevel(), "Mock survival player must be in the test level");
helper.assertTrue(!player.isCreative() && !player.isSpectator(),
"Mock survival player must not be creative or spectator");
helper.assertTrue(RivencraftConfig.statusEffectsPlayers(), "Player status effects must be enabled");
helper.assertTrue(AgeStatusEffectProviders.eligibleTarget(helper.getLevel(), player, id("poison_global")),
"A survival player is eligible for a general Legacy debuff");
helper.assertTrue(AgeStatusEffectProviders.eligibleTarget(helper.getLevel(), cow, id("poison_global")),
"General Legacy debuffs are not limited to players");
helper.assertTrue(hostile.isAlive() && hostile.level() == helper.getLevel(),
"Mock hostile mob must be alive in the test level");
helper.assertTrue(RivencraftConfig.statusEffectsHostiles(), "Hostile status effects must be enabled");
helper.assertTrue(hostile.getEffect(MobEffects.REGENERATION) == null,
"Mock hostile mob must not already have regeneration");
helper.assertTrue(hostile.canBeAffected(new MobEffectInstance(MobEffects.REGENERATION, 200, 0)),
"Mock hostile mob must accept regeneration");
helper.assertTrue(AgeStatusEffectProviders.eligibleTarget(helper.getLevel(), hostile,
id("enemyregen_global")), "Hostile mobs can receive the enemy buff");
helper.assertTrue(!AgeStatusEffectProviders.eligibleTarget(helper.getLevel(), cow,
id("enemyregen_global")), "Passive mobs do not receive the adapted enemy buff");
var creative = helper.makeMockPlayer(GameType.CREATIVE);
helper.assertTrue(!AgeStatusEffectProviders.eligibleTarget(helper.getLevel(), creative,
id("poison_global")), "Creative players must be exempt");
var spectator = helper.makeMockPlayer(GameType.SPECTATOR);
helper.assertTrue(!AgeStatusEffectProviders.eligibleTarget(helper.getLevel(), spectator,
id("poison_global")), "Spectators must be exempt");
helper.succeed();
}
@GameTest(template = "empty")
public static void overworldCannotRunAnAgeStatusProvider(GameTestHelper helper) {
var player = helper.makeMockServerPlayerInLevel();
player.setGameMode(GameType.SURVIVAL);
UUID ageId = UUID.randomUUID();
AgeDefinition age = new AgeDefinition(ageId, "Isolated", 100L, AgeGenerationProfiles.STANDARD,
AgeDefinition.CURRENT_GENERATION_VERSION, 0L, AgeDefinition.dimensionId(ageId), null,
AgeTraits.LEGACY_DEFAULTS);
AgeInstabilityRuntime.Budget budget = new AgeInstabilityRuntime.Budget(1);
var context = new AgeInstabilityRuntime.Context(helper.getLevel(), age,
List.of(player.chunkPosition()), helper.getLevel().getServer().getTickCount(), budget);
AgeStatusEffectProviders.apply(context, id("poison_global"), 1);
helper.assertTrue(player.getEffect(MobEffects.POISON) == null,
"An Age provider must not apply in the Overworld");
helper.assertValueEqual(budget.remaining(), 1,
"A rejected cross-world attempt must not consume the Age budget");
helper.succeed();
}
private static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
}
}
@@ -0,0 +1,218 @@
package net.dnorberg.rivencraft.book;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.WeakHashMap;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.minecraft.core.Holder;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.phys.AABB;
import net.neoforged.neoforge.event.entity.EntityTravelToDimensionEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
/** Legacy potion cards adapted to bounded, Age-local server effects. */
public final class AgeStatusEffectProviders {
private static final int MAX_TRACKED_AGES = 64;
private static final Map<ResourceLocation, Spec> SPECS = createSpecs();
private static final Map<ServerLevel, List<Lease>> LEASES = new WeakHashMap<>();
private AgeStatusEffectProviders() {}
public static void register() {
SPECS.keySet().forEach(id -> AgeInstabilityRuntime.register(id, false, AgeStatusEffectProviders::apply));
}
static void apply(AgeInstabilityRuntime.Context context, ResourceLocation id, int level) {
if (!RivencraftConfig.statusEffectsEnabled()
|| !AgeInstabilityRuntime.isAgeDimension(context.level().dimension().location())
|| !context.age().dimensionId().equals(context.level().dimension().location())) return;
Spec spec = SPECS.get(id);
if (spec == null || spec.target() == Target.HOSTILE && !RivencraftConfig.statusEffectsHostiles()
|| spec.target() == Target.GENERAL && !RivencraftConfig.statusEffectsPlayers()
&& !RivencraftConfig.statusEffectsNonplayers()) return;
List<Lease> leases = LEASES.get(context.level());
if (leases == null) {
if (LEASES.size() >= MAX_TRACKED_AGES) return;
leases = new ArrayList<>();
LEASES.put(context.level(), leases);
}
prune(context.level(), leases, context.serverTick(), false);
if (leases.size() >= RivencraftConfig.statusEffectsMaxActive()) return;
Random random = new Random(context.age().seed() ^ (context.serverTick() * 0x9E3779B97F4A7C15L)
^ id.hashCode());
ChunkPos chunk = context.loadedChunks().get(random.nextInt(context.loadedChunks().size()));
AABB bounds = new AABB(chunk.getMinBlockX(), context.level().getMinBuildHeight(), chunk.getMinBlockZ(),
chunk.getMaxBlockX() + 1, context.level().getMaxBuildHeight(), chunk.getMaxBlockZ() + 1);
int duration = Math.min(spec.legacyDuration(), RivencraftConfig.statusEffectsMaxDuration());
int amplifier = Math.max(0, level - 1);
MobEffectInstance instance = new MobEffectInstance(spec.effect(), duration, amplifier);
List<LivingEntity> candidates = new ArrayList<>();
context.level().getEntities(EntityTypeTest.forClass(LivingEntity.class), bounds,
entity -> eligible(context.level(), entity, spec, instance), candidates,
RivencraftConfig.statusEffectsMaxCandidates());
if (candidates.isEmpty()) return;
candidates.sort(Comparator.comparing(Entity::getUUID));
LivingEntity target = candidates.get(random.nextInt(candidates.size()));
if (!context.budget().claim() || !target.addEffect(instance)) return;
leases.add(new Lease(new WeakReference<>(target), instance,
context.serverTick() + duration, spec.target()));
}
private static boolean eligible(ServerLevel level, LivingEntity entity, Spec spec,
MobEffectInstance instance) {
if (!entity.isAlive() || entity.isRemoved() || entity.level() != level
|| entity.getEffect(spec.effect()) != null || !entity.canBeAffected(instance)
|| !spec.global() && !level.canSeeSky(entity.blockPosition())) return false;
return allowedByPolicy(spec.target(), entity);
}
private static boolean allowedByPolicy(Target target, LivingEntity entity) {
if (entity instanceof Player player) {
return target == Target.GENERAL && RivencraftConfig.statusEffectsPlayers()
&& !player.isCreative() && !player.isSpectator();
}
return target == Target.GENERAL ? RivencraftConfig.statusEffectsNonplayers()
: entity instanceof Monster && RivencraftConfig.statusEffectsHostiles();
}
public static void onServerTickPost(ServerTickEvent.Post event) {
if (event.getServer().getTickCount() % 20 != 0) return;
boolean disabled = !RivencraftConfig.instabilityEnabled() || !RivencraftConfig.statusEffectsEnabled();
long tick = event.getServer().getTickCount();
for (var entry : LEASES.entrySet()) prune(entry.getKey(), entry.getValue(), tick, disabled);
LEASES.values().removeIf(List::isEmpty);
}
public static void onEntityTravel(EntityTravelToDimensionEvent event) {
Entity entity = event.getEntity();
if (entity instanceof LivingEntity living && !entity.level().dimension().equals(event.getDimension())) {
clearEntity(living);
}
}
public static void onPlayerChangedDimension(PlayerEvent.PlayerChangedDimensionEvent event) {
if (event.getEntity() instanceof ServerPlayer player) clearEntity(player);
}
public static void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) {
if (event.getEntity() instanceof ServerPlayer player) clearEntity(player);
}
public static void onServerStopping(ServerStoppingEvent event) {
long tick = event.getServer().getTickCount();
for (var entry : LEASES.entrySet()) prune(entry.getKey(), entry.getValue(), tick, true);
LEASES.clear();
}
private static void clearEntity(LivingEntity entity) {
for (List<Lease> leases : LEASES.values()) {
Iterator<Lease> iterator = leases.iterator();
while (iterator.hasNext()) {
Lease lease = iterator.next();
if (lease.entity().get() != entity) continue;
removeOwnedEffect(entity, lease);
iterator.remove();
}
}
}
private static void prune(ServerLevel level, List<Lease> leases, long tick, boolean removeAll) {
Iterator<Lease> iterator = leases.iterator();
while (iterator.hasNext()) {
Lease lease = iterator.next();
LivingEntity entity = lease.entity().get();
if (entity == null || entity.isRemoved() || entity.getEffect(lease.instance().getEffect()) == null) {
iterator.remove();
continue;
}
boolean revoke = removeAll || entity.level() != level
|| !allowedByPolicy(lease.target(), entity);
if (revoke || tick >= lease.expiresAt()) {
removeOwnedEffect(entity, lease);
iterator.remove();
}
}
}
private static void removeOwnedEffect(LivingEntity entity, Lease lease) {
// addEffect stores the supplied instance when no effect exists. Do not remove
// a replacement from another mod (or a stronger/extended effect).
if (entity.getEffect(lease.instance().getEffect()) == lease.instance()
&& lease.instance().getAmplifier() == lease.amplifier()
&& lease.instance().getDuration() <= lease.originalDuration()) {
entity.removeEffect(lease.instance().getEffect());
}
}
static int legacyDuration(ResourceLocation id) {
Spec spec = SPECS.get(id);
return spec == null ? -1 : spec.legacyDuration();
}
static boolean localRequiresSky(ResourceLocation id) {
Spec spec = SPECS.get(id);
return spec != null && !spec.global();
}
static boolean eligibleTarget(ServerLevel level, LivingEntity entity, ResourceLocation id) {
Spec spec = SPECS.get(id);
return spec != null && eligible(level, entity, spec,
new MobEffectInstance(spec.effect(), spec.legacyDuration(), 0));
}
private static Map<ResourceLocation, Spec> createSpecs() {
Map<ResourceLocation, Spec> specs = new HashMap<>();
addPair(specs, "blindness", MobEffects.BLINDNESS, 60);
addPair(specs, "fatigue", MobEffects.DIG_SLOWDOWN, 80);
addPair(specs, "hunger", MobEffects.HUNGER, 80);
addPair(specs, "nausea", MobEffects.CONFUSION, 60);
addPair(specs, "poison", MobEffects.POISON, 80);
addPair(specs, "slow", MobEffects.MOVEMENT_SLOWDOWN, 80);
addPair(specs, "weakness", MobEffects.WEAKNESS, 80);
addPair(specs, "wither", MobEffects.WITHER, 30);
specs.put(id("enemyregen_global"), new Spec(MobEffects.REGENERATION, 200, true, Target.HOSTILE));
specs.put(id("enemyresist_global"), new Spec(MobEffects.DAMAGE_RESISTANCE, 200, true, Target.HOSTILE));
return Map.copyOf(specs);
}
private static void addPair(Map<ResourceLocation, Spec> specs, String name,
Holder<MobEffect> effect, int duration) {
specs.put(id(name), new Spec(effect, duration, false, Target.GENERAL));
specs.put(id(name + "_global"), new Spec(effect, duration, true, Target.GENERAL));
}
private static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
}
private enum Target { GENERAL, HOSTILE }
private record Spec(Holder<MobEffect> effect, int legacyDuration, boolean global, Target target) {}
private record Lease(WeakReference<LivingEntity> entity, MobEffectInstance instance, long expiresAt,
Target target, int amplifier, int originalDuration) {
private Lease(WeakReference<LivingEntity> entity, MobEffectInstance instance, long expiresAt,
Target target) {
this(entity, instance, expiresAt, target, instance.getAmplifier(), instance.getDuration());
}
}
}
@@ -4,6 +4,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import net.dnorberg.rivencraft.Rivencraft; import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.mixin.StructurePlacementAccessor;
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.WritingEntry; import net.dnorberg.rivencraft.writing.WritingEntry;
@@ -14,6 +15,8 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets; import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets;
import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.StructureSet;
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
import net.neoforged.neoforge.gametest.GameTestHolder; import net.neoforged.neoforge.gametest.GameTestHolder;
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate; import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
@@ -90,6 +93,84 @@ public final class AgeStructureGameTests {
helper.succeed(); helper.succeed();
} }
@GameTest(template = "empty")
public static void repeatedStructurePagesIncreasePlacementFrequency(GameTestHelper helper) {
var lookup = helper.getLevel().registryAccess().lookupOrThrow(Registries.STRUCTURE_SET);
RandomSpreadStructurePlacement oneVillage = (RandomSpreadStructurePlacement) lookup
.getOrThrow(BuiltinStructureSets.VILLAGES).value().placement();
RandomSpreadStructurePlacement twoVillages = (RandomSpreadStructurePlacement) AgeStructureSelection
.filteredLookup(lookup, repeated("villages", 2)).getOrThrow(BuiltinStructureSets.VILLAGES)
.value().placement();
helper.assertTrue(oneVillage.spacing() == 34 && twoVillages.spacing() == 24,
"A second Village page must approximately double density by reducing grid spacing");
RandomSpreadStructurePlacement oneMineshaft = (RandomSpreadStructurePlacement) lookup
.getOrThrow(BuiltinStructureSets.MINESHAFTS).value().placement();
RandomSpreadStructurePlacement twoMineshafts = (RandomSpreadStructurePlacement) AgeStructureSelection
.filteredLookup(lookup, repeated("mineshafts", 2)).getOrThrow(BuiltinStructureSets.MINESHAFTS)
.value().placement();
float oneFrequency = ((StructurePlacementAccessor) oneMineshaft).rivencraft$frequency();
float twoFrequency = ((StructurePlacementAccessor) twoMineshafts).rivencraft$frequency();
helper.assertTrue(oneMineshaft.spacing() == 1 && twoMineshafts.spacing() == 1
&& Math.abs(twoFrequency - oneFrequency * 2.0F) < 0.000001F,
"A second Mineshaft page must double its per-chunk probability");
ConcentricRingsStructurePlacement oneStronghold = (ConcentricRingsStructurePlacement) lookup
.getOrThrow(BuiltinStructureSets.STRONGHOLDS).value().placement();
ConcentricRingsStructurePlacement twoStrongholds = (ConcentricRingsStructurePlacement) AgeStructureSelection
.filteredLookup(lookup, repeated("strongholds", 2)).getOrThrow(BuiltinStructureSets.STRONGHOLDS)
.value().placement();
helper.assertTrue(twoStrongholds.distance() == oneStronghold.distance()
&& twoStrongholds.spread() == oneStronghold.spread() * 2
&& twoStrongholds.count() == oneStronghold.count() * 2,
"A second Stronghold page must double positions per ring and total positions");
helper.succeed();
}
@GameTest(template = "empty")
public static void repeatedStructuresConstrainSeedCompletedBiomes(GameTestHelper helper) {
OrderedWriting fourVillages = new OrderedWriting(new java.util.ArrayList<>(java.util.stream.Stream.concat(
java.util.stream.Stream.of(WritingEntry.linkPanel()),
java.util.stream.IntStream.range(0, 4).mapToObj(ignored -> page("feature/villages")))
.toList()));
try {
AgeRegistrySavedData.validateNewWriting(helper.getLevel(), "four", fourVillages);
} catch (IllegalArgumentException exception) {
helper.fail("Four Village pages without explicit biome pages must use compatible seeded completion: "
+ exception.getMessage());
}
helper.succeed();
}
@GameTest(template = "empty")
public static void authoredVillagesOverrideBiomeWithInstability(GameTestHelper helper) {
OrderedWriting writing = new OrderedWriting(List.of(WritingEntry.linkPanel(),
page("terrain/standard"), page("biome/the_end"), page("biome/single"),
page("feature/villages"), page("feature/villages")));
AgeDefinition age;
try {
age = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
new AgeReference(java.util.UUID.randomUUID(), "Forced End Villages"), writing);
} catch (IllegalArgumentException exception) {
helper.fail("Authored Villages must be allowed outside vanilla Village biomes: "
+ exception.getMessage());
return;
}
helper.assertValueEqual(age.instability().score(), 200,
"Each of two Villages forced into The End biome must add 100 instability");
helper.assertValueEqual(age.instability().breakdown().stream()
.filter(part -> part.reason().equals("forced_biome_villages")).count(), 2L,
"Every forced Village occurrence must retain its own instability contribution");
helper.succeed();
}
private static List<AgeFeatureSelection.Choice> repeated(String feature, int count) {
return java.util.stream.IntStream.range(0, count)
.mapToObj(ignored -> new AgeFeatureSelection.Choice(id(feature), Optional.<ResourceLocation>empty()))
.toList();
}
private static ResourceLocation id(String path) { private static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path); return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
} }
@@ -1,14 +1,17 @@
package net.dnorberg.rivencraft.book; package net.dnorberg.rivencraft.book;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Random; import java.util.Random;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import net.dnorberg.rivencraft.mixin.StructurePlacementAccessor;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderOwner;
import net.minecraft.core.HolderSet; import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries; import net.minecraft.core.registries.Registries;
@@ -16,7 +19,11 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey; import net.minecraft.tags.TagKey;
import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets; import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.StructureSet;
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
/** Frozen Age structure-page choices and their vanilla structure-set gate. */ /** Frozen Age structure-page choices and their vanilla structure-set gate. */
public final class AgeStructureSelection { public final class AgeStructureSelection {
@@ -98,14 +105,9 @@ public final class AgeStructureSelection {
var set = registries.lookupOrThrow(Registries.STRUCTURE_SET) var set = registries.lookupOrThrow(Registries.STRUCTURE_SET)
.get(ResourceKey.create(Registries.STRUCTURE_SET, setId)); .get(ResourceKey.create(Registries.STRUCTURE_SET, setId));
if (set.isEmpty()) return "Feature " + feature + " requires missing structure set " + setId; if (set.isEmpty()) return "Feature " + feature + " requires missing structure set " + setId;
if (biomes == null) return null; // Authored structures intentionally override vanilla biome eligibility. An
Set<ResourceLocation> selected = Set.copyOf(biomes.biomes()); // incompatible selection is legal writing and receives instability instead.
boolean compatible = set.orElseThrow().value().structures().stream() return null;
.flatMap(entry -> entry.structure().value().biomes().stream())
.map(holder -> holder.unwrapKey().map(ResourceKey::location).orElse(null))
.anyMatch(selected::contains);
return compatible ? null : "Feature " + feature
+ " needs at least one biome allowed by structure set " + setId;
} }
private static boolean placedExists(RegistryAccess registries, ResourceLocation id) { private static boolean placedExists(RegistryAccess registries, ResourceLocation id) {
@@ -113,10 +115,40 @@ public final class AgeStructureSelection {
.get(ResourceKey.create(Registries.PLACED_FEATURE, id)).isPresent(); .get(ResourceKey.create(Registries.PLACED_FEATURE, id)).isPresent();
} }
static Set<ResourceLocation> compatibleBiomes(ResourceLocation feature, RegistryAccess registries) {
ResourceLocation structureSet = setId(feature);
if (structureSet == null) return Set.of();
return registries.lookupOrThrow(Registries.STRUCTURE_SET)
.get(ResourceKey.create(Registries.STRUCTURE_SET, structureSet)).stream()
.flatMap(holder -> holder.value().structures().stream())
.flatMap(entry -> entry.structure().value().biomes().stream())
.flatMap(holder -> holder.unwrapKey().stream())
.map(ResourceKey::location)
.collect(java.util.stream.Collectors.toUnmodifiableSet());
}
public static boolean biomeCompatible(ResourceLocation feature, AgeBiomeSelection biomes,
RegistryAccess registries) {
Set<ResourceLocation> compatible = compatibleBiomes(feature, registries);
return compatible.isEmpty() || biomes.biomes().stream().anyMatch(compatible::contains);
}
/** True when this exact registered structure belongs to an authored structure page. */
public static boolean authoredStructure(Structure structure, RegistryAccess registries,
List<AgeFeatureSelection.Choice> choices) {
Set<ResourceLocation> enabled = enabledSets(choices).keySet();
var sets = registries.lookupOrThrow(Registries.STRUCTURE_SET);
return enabled.stream().map(id -> ResourceKey.create(Registries.STRUCTURE_SET, id))
.flatMap(key -> sets.get(key).stream())
.flatMap(holder -> holder.value().structures().stream())
.anyMatch(entry -> entry.structure().value() == structure);
}
public static List<AgeFeatureSelection.Choice> randomChoices(long ageSeed, AgeRuntimeProfile profile, public static List<AgeFeatureSelection.Choice> randomChoices(long ageSeed, AgeRuntimeProfile profile,
AgeBiomeSelection biomes, RegistryAccess registries) { AgeBiomeSelection biomes, RegistryAccess registries) {
List<LegacyRankChoice.Option<ResourceLocation>> eligible = new ArrayList<>(FEATURES.stream() List<LegacyRankChoice.Option<ResourceLocation>> eligible = new ArrayList<>(FEATURES.stream()
.filter(id -> error(id, profile, biomes, registries) == null) .filter(id -> error(id, profile, biomes, registries) == null)
.filter(id -> dungeons(id) || biomeCompatible(id, biomes, registries))
.map(id -> new LegacyRankChoice.Option<>(id, randomRank(id))).toList()); .map(id -> new LegacyRankChoice.Option<>(id, randomRank(id))).toList());
Random random = new Random(ageSeed ^ 0x5354525543545552L); Random random = new Random(ageSeed ^ 0x5354525543545552L);
int count = random.nextInt(3); int count = random.nextInt(3);
@@ -136,25 +168,31 @@ public final class AgeStructureSelection {
return 3; // Structures added after Legacy are uncommon, but still discoverable. return 3; // Structures added after Legacy are uncommon, but still discoverable.
} }
private static Set<ResourceLocation> enabledSets(List<AgeFeatureSelection.Choice> choices) { private static Map<ResourceLocation, Integer> enabledSets(List<AgeFeatureSelection.Choice> choices) {
return choices.stream().filter(choice -> feature(choice.id()) && !dungeons(choice.id())) Map<ResourceLocation, Integer> counts = new HashMap<>();
.map(choice -> setId(choice.id())).collect(java.util.stream.Collectors.toUnmodifiableSet()); choices.stream().filter(choice -> feature(choice.id()) && !dungeons(choice.id()))
.forEach(choice -> counts.merge(setId(choice.id()), 1, Integer::sum));
return Map.copyOf(counts);
} }
public static Stream<Holder<StructureSet>> allowedSets(Stream<Holder<StructureSet>> sets, public static Stream<Holder<StructureSet>> allowedSets(Stream<Holder<StructureSet>> sets,
List<AgeFeatureSelection.Choice> choices) { List<AgeFeatureSelection.Choice> choices) {
Set<ResourceLocation> enabled = enabledSets(choices); Map<ResourceLocation, Integer> enabled = enabledSets(choices);
return sets.filter(holder -> holder.unwrapKey() return sets.filter(holder -> holder.unwrapKey()
.map(key -> allowed(key.location(), enabled)).orElse(false)); .map(key -> allowed(key.location(), enabled.keySet())).orElse(false))
.map(holder -> scaledHolder(holder, enabled));
} }
public static HolderLookup<StructureSet> filteredLookup(HolderLookup<StructureSet> lookup, public static HolderLookup<StructureSet> filteredLookup(HolderLookup<StructureSet> lookup,
List<AgeFeatureSelection.Choice> choices) { List<AgeFeatureSelection.Choice> choices) {
Set<ResourceLocation> enabled = enabledSets(choices); Map<ResourceLocation, Integer> enabled = enabledSets(choices);
Map<ResourceKey<StructureSet>, Holder.Reference<StructureSet>> scaled = new HashMap<>();
return new HolderLookup<>() { return new HolderLookup<>() {
@Override @Override
public Optional<Holder.Reference<StructureSet>> get(ResourceKey<StructureSet> key) { public Optional<Holder.Reference<StructureSet>> get(ResourceKey<StructureSet> key) {
return allowed(key.location(), enabled) ? lookup.get(key) : Optional.empty(); if (!allowed(key.location(), enabled.keySet())) return Optional.empty();
return lookup.get(key).map(holder -> scaled.computeIfAbsent(key,
ignored -> scaledReference(holder, enabled.getOrDefault(key.location(), 1))));
} }
@Override @Override
@@ -164,7 +202,11 @@ public final class AgeStructureSelection {
@Override @Override
public Stream<Holder.Reference<StructureSet>> listElements() { public Stream<Holder.Reference<StructureSet>> listElements() {
return lookup.listElements().filter(holder -> allowed(holder.key().location(), enabled)); return lookup.listElements()
.filter(holder -> allowed(holder.key().location(), enabled.keySet()))
.map(holder -> scaled.computeIfAbsent(holder.key(),
ignored -> scaledReference(holder,
enabled.getOrDefault(holder.key().location(), 1))));
} }
@Override @Override
@@ -177,4 +219,57 @@ public final class AgeStructureSelection {
private static boolean allowed(ResourceLocation set, Set<ResourceLocation> enabled) { private static boolean allowed(ResourceLocation set, Set<ResourceLocation> enabled) {
return !CONTROLLED_SETS.contains(set) || enabled.contains(set); return !CONTROLLED_SETS.contains(set) || enabled.contains(set);
} }
private static Holder<StructureSet> scaledHolder(Holder<StructureSet> holder,
Map<ResourceLocation, Integer> enabled) {
int occurrences = holder.unwrapKey().map(key -> enabled.getOrDefault(key.location(), 1)).orElse(1);
return occurrences == 1 ? holder : Holder.direct(scaled(holder.value(), occurrences));
}
private static Holder.Reference<StructureSet> scaledReference(Holder.Reference<StructureSet> holder,
int occurrences) {
if (occurrences == 1) return holder;
return new ScaledReference(holder.key(), scaled(holder.value(), occurrences));
}
static StructureSet scaled(StructureSet set, int occurrences) {
if (occurrences < 1) throw new IllegalArgumentException("Structure occurrence count must be positive");
if (occurrences == 1) return set;
StructurePlacement placement = set.placement();
StructurePlacementAccessor base = (StructurePlacementAccessor) placement;
if (placement instanceof RandomSpreadStructurePlacement random) {
float originalFrequency = base.rivencraft$frequency();
float frequency = Math.min(1.0F, originalFrequency * occurrences);
double frequencyFactor = originalFrequency > 0.0F ? frequency / originalFrequency : 1.0;
double spacingFactor = occurrences / frequencyFactor;
int spacing = Math.max(1, (int) Math.round(random.spacing() / Math.sqrt(spacingFactor)));
int separation = spacing == 1 ? 0 : Math.min(spacing - 1,
(int) Math.round((double) random.separation() * spacing / random.spacing()));
return new StructureSet(set.structures(), new RandomSpreadStructurePlacement(
base.rivencraft$locateOffset(), base.rivencraft$frequencyReductionMethod(), frequency,
base.rivencraft$salt(), base.rivencraft$exclusionZone(), spacing, separation,
random.spreadType()));
}
if (placement instanceof ConcentricRingsStructurePlacement rings) {
int count = saturatedMultiply(rings.count(), occurrences, 4095);
int spread = Math.min(count, saturatedMultiply(rings.spread(), occurrences, 1023));
return new StructureSet(set.structures(), new ConcentricRingsStructurePlacement(
base.rivencraft$locateOffset(), base.rivencraft$frequencyReductionMethod(),
base.rivencraft$frequency(), base.rivencraft$salt(), base.rivencraft$exclusionZone(),
rings.distance(), spread, count, rings.preferredBiomes()));
}
return set;
}
private static int saturatedMultiply(int value, int multiplier, int maximum) {
return (int) Math.min(maximum, (long) value * multiplier);
}
private static final class ScaledReference extends Holder.Reference<StructureSet> {
private static final HolderOwner<StructureSet> OWNER = new HolderOwner<>() {};
private ScaledReference(ResourceKey<StructureSet> key, StructureSet value) {
super(Type.STAND_ALONE, OWNER, key, value);
}
}
} }
@@ -0,0 +1,27 @@
package net.dnorberg.rivencraft.book;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.registry.ModBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestHelper;
import net.neoforged.neoforge.gametest.GameTestHolder;
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
@GameTestHolder(Rivencraft.MOD_ID)
@PrefixGameTestTemplate(false)
public final class CloudPlatformGameTests {
private CloudPlatformGameTests() {}
@GameTest(template = "empty")
public static void cloudIsSolidFootingWithoutAnObtainableItem(GameTestHelper helper) {
BlockPos pos = helper.absolutePos(new BlockPos(1, 1, 1));
var state = ModBlocks.CLOUD_PLATFORM.get().defaultBlockState();
helper.getLevel().setBlock(pos, state, 2);
helper.assertTrue(!state.getCollisionShape(helper.getLevel(), pos).isEmpty(),
"Cloud platform must support a standing player");
helper.assertTrue(ModBlocks.CLOUD_PLATFORM.get().getCloneItemStack(helper.getLevel(), pos, state).isEmpty(),
"Cloud platform must not provide a pick-block item");
helper.succeed();
}
}
@@ -0,0 +1,74 @@
package net.dnorberg.rivencraft.book;
import java.util.ArrayList;
import java.util.List;
import net.dnorberg.rivencraft.Rivencraft;
import net.minecraft.resources.ResourceLocation;
/** Frozen Legacy 0.13.7.06 deck cards and default activation costs, not effect implementations. */
public final class InstabilityProviderCatalog {
public enum Deck {
BASIC(0), HARSH(2_500), DESTRUCTIVE(10_000), EATING(15_000), DEATH(20_000);
private final int entryCost;
Deck(int entryCost) { this.entryCost = entryCost; }
public int entryCost() { return entryCost; }
}
public record Card(ResourceLocation id, int cost) {
public Card {
if (cost <= 0) throw new IllegalArgumentException("Provider cost must be positive");
}
}
private static final List<List<Card>> DECKS = createDecks();
private InstabilityProviderCatalog() {}
public static List<Card> cards(Deck deck) { return DECKS.get(deck.ordinal()); }
public static boolean contains(ResourceLocation id) {
return DECKS.stream().flatMap(List::stream).anyMatch(card -> card.id().equals(id));
}
private static List<List<Card>> createDecks() {
List<List<Card>> decks = new ArrayList<>();
for (Deck ignored : Deck.values()) decks.add(new ArrayList<>());
add(decks, "blindness", 1000, 0, 0, 0, 1, 0);
add(decks, "blindness_global", 1500, 0, 0, 0, 0, 1);
add(decks, "enemyregen_global", 1000, 5, 2, 0, 0, 0);
add(decks, "enemyresist_global", 1000, 2, 1, 0, 0, 0);
add(decks, "fatigue", 500, 5, 0, 0, 0, 0);
add(decks, "fatigue_global", 1000, 0, 5, 0, 0, 0);
add(decks, "hunger", 500, 8, 2, 0, 0, 0);
add(decks, "hunger_global", 1000, 0, 5, 0, 0, 0);
add(decks, "nausea", 1000, 0, 0, 0, 1, 0);
add(decks, "nausea_global", 1500, 0, 0, 0, 0, 1);
add(decks, "poison", 500, 9, 3, 0, 0, 0);
add(decks, "poison_global", 1000, 0, 5, 0, 0, 0);
add(decks, "slow", 500, 6, 1, 0, 0, 0);
add(decks, "slow_global", 1000, 0, 5, 0, 0, 0);
add(decks, "weakness", 500, 8, 2, 0, 0, 0);
add(decks, "weakness_global", 1000, 0, 5, 0, 0, 0);
add(decks, "wither", 1000, 0, 1, 1, 2, 0);
add(decks, "wither_global", 2000, 0, 0, 1, 1, 1);
add(decks, "burning", 500, 0, 1, 0, 0, 0);
add(decks, "crumble", 2000, 0, 0, 6, 0, 0);
add(decks, "decayblue", 2000, 0, 0, 0, 2, 1);
add(decks, "decaypurple", 2000, 0, 0, 0, 2, 1);
add(decks, "decayred", 2000, 0, 0, 0, 2, 1);
add(decks, "decaywhite", 5000, 0, 0, 0, 1, 3);
add(decks, "explosions", 1000, 0, 0, 8, 0, 0);
add(decks, "lightning", 1000, 0, 4, 4, 0, 0);
add(decks, "meteors", 1000, 0, 0, 4, 0, 0);
return decks.stream().map(List::copyOf).toList();
}
private static void add(List<List<Card>> decks, String path, int cost, int... copies) {
Card card = new Card(ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path), cost);
for (Deck deck : Deck.values()) {
for (int copy = 0; copy < copies[deck.ordinal()]; copy++) decks.get(deck.ordinal()).add(card);
}
}
}
@@ -1,5 +1,7 @@
package net.dnorberg.rivencraft.book; package net.dnorberg.rivencraft.book;
import net.dnorberg.rivencraft.registry.ModBlocks;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -250,7 +252,7 @@ public final class TerrainWritingGameTests {
helper.assertTrue(level != null, "The written Age must create a runtime dimension"); helper.assertTrue(level != null, "The written Age must create a runtime dimension");
assertGenerator(helper, level, age.plan().runtimeProfile()); assertGenerator(helper, level, age.plan().runtimeProfile());
BlockPos spawn = target.location().pos(); BlockPos spawn = target.location().pos();
helper.assertTrue(level.getBlockState(spawn.below()).is(Blocks.COBBLESTONE) helper.assertTrue(level.getBlockState(spawn.below()).is(ModBlocks.CLOUD_PLATFORM.get())
&& level.getBlockState(spawn).isAir() && level.getBlockState(spawn).isAir()
&& level.getBlockState(spawn.above()).isAir(), && level.getBlockState(spawn.above()).isAir(),
"Every written terrain family must retain a safe arrival platform"); "Every written terrain family must retain a safe arrival platform");
@@ -77,6 +77,7 @@ public final class ClientEvents {
ItemBlockRenderTypes.setRenderLayer(ModBlocks.MEDIUM_CRYSTAL_BUD.get(), RenderType.cutout()); ItemBlockRenderTypes.setRenderLayer(ModBlocks.MEDIUM_CRYSTAL_BUD.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.LARGE_CRYSTAL_BUD.get(), RenderType.cutout()); ItemBlockRenderTypes.setRenderLayer(ModBlocks.LARGE_CRYSTAL_BUD.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.CRYSTAL_CLUSTER.get(), RenderType.cutout()); ItemBlockRenderTypes.setRenderLayer(ModBlocks.CRYSTAL_CLUSTER.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.CLOUD_PLATFORM.get(), RenderType.translucent());
}); });
NeoForge.EVENT_BUS.addListener(ClientBookInteractionHandler::onRightClickItem); NeoForge.EVENT_BUS.addListener(ClientBookInteractionHandler::onRightClickItem);
NeoForge.EVENT_BUS.addListener(ClientBookInteractionHandler::onRightClickBlock); NeoForge.EVENT_BUS.addListener(ClientBookInteractionHandler::onRightClickBlock);
@@ -1,10 +1,17 @@
package net.dnorberg.rivencraft.command; package net.dnorberg.rivencraft.command;
import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import net.dnorberg.rivencraft.block.DecayBlock;
import net.dnorberg.rivencraft.book.AgeDefinition; import net.dnorberg.rivencraft.book.AgeDefinition;
import net.dnorberg.rivencraft.book.AgeDecayProviders;
import net.dnorberg.rivencraft.book.AgeHazardProviders;
import net.dnorberg.rivencraft.book.AgeEnvironmentalProviders;
import net.dnorberg.rivencraft.book.AgeDimensionService; import net.dnorberg.rivencraft.book.AgeDimensionService;
import net.dnorberg.rivencraft.book.AgeRegistrySavedData; import net.dnorberg.rivencraft.book.AgeRegistrySavedData;
import net.minecraft.commands.Commands; import net.minecraft.commands.Commands;
import net.minecraft.commands.CommandSourceStack;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.neoforged.neoforge.event.RegisterCommandsEvent; import net.neoforged.neoforge.event.RegisterCommandsEvent;
@@ -20,6 +27,17 @@ public final class RivencraftCommands {
.then(Commands.literal("age") .then(Commands.literal("age")
.then(Commands.literal("list") .then(Commands.literal("list")
.executes(context -> listAges(context.getSource()))) .executes(context -> listAges(context.getSource())))
.then(Commands.literal("instability")
.executes(context -> inspectInstability(context.getSource(),
context.getSource().getLevel().dimension().location().toString()))
.then(Commands.argument("dimension", StringArgumentType.string())
.suggests((context, builder) -> {
AgeRegistrySavedData.get(context.getSource().getLevel()).definitions()
.forEach(age -> builder.suggest(age.dimensionId().toString()));
return builder.buildFuture();
})
.executes(context -> inspectInstability(context.getSource(),
StringArgumentType.getString(context, "dimension")))))
.then(Commands.literal("unload") .then(Commands.literal("unload")
.then(Commands.argument("dimension", StringArgumentType.string()) .then(Commands.argument("dimension", StringArgumentType.string())
.suggests((context, builder) -> { .suggests((context, builder) -> {
@@ -30,7 +48,38 @@ public final class RivencraftCommands {
.executes(context -> unloadAge( .executes(context -> unloadAge(
context.getSource(), context.getSource(),
StringArgumentType.getString(context, "dimension") StringArgumentType.getString(context, "dimension")
)))))); ))))
.then(Commands.literal("decay")
.then(Commands.literal("pulse")
.then(Commands.argument("color", StringArgumentType.word())
.suggests((context, builder) -> {
for (DecayBlock.Color color : DecayBlock.Color.values()) {
builder.suggest(color.getSerializedName());
}
return builder.buildFuture();
})
.then(Commands.argument("attempts", IntegerArgumentType.integer(1, 32))
.executes(context -> pulseDecay(context.getSource(),
StringArgumentType.getString(context, "color"),
IntegerArgumentType.getInteger(context, "attempts")))))))
.then(Commands.literal("hazard")
.then(Commands.literal("pulse")
.then(Commands.literal("lightning")
.executes(context -> pulseHazard(context.getSource(), true)))
.then(Commands.literal("explosion")
.executes(context -> pulseHazard(context.getSource(), false)))))
.then(environmentCommand())));
}
private static LiteralArgumentBuilder<CommandSourceStack> environmentCommand() {
return Commands.literal("environment")
.then(Commands.literal("pulse")
.then(Commands.literal("meteor")
.executes(context -> pulseEnvironment(context.getSource(), "meteor")))
.then(Commands.literal("burning")
.executes(context -> pulseEnvironment(context.getSource(), "burning")))
.then(Commands.literal("erosion")
.executes(context -> pulseEnvironment(context.getSource(), "erosion"))));
} }
private static int listAges(net.minecraft.commands.CommandSourceStack source) { private static int listAges(net.minecraft.commands.CommandSourceStack source) {
@@ -80,4 +129,76 @@ public final class RivencraftCommands {
} }
}; };
} }
private static int inspectInstability(CommandSourceStack source, String requestedDimension) {
ResourceLocation dimension = ResourceLocation.tryParse(requestedDimension);
if (dimension == null) {
source.sendFailure(Component.literal("Invalid dimension id: " + requestedDimension));
return 0;
}
AgeDefinition age = AgeRegistrySavedData.get(source.getLevel()).findByDimension(dimension).orElse(null);
if (age == null) {
source.sendFailure(Component.literal("Unknown Rivencraft Age: " + dimension));
return 0;
}
var totals = age.instability().totals();
source.sendSuccess(() -> Component.literal(age.name() + " — " + age.dimensionId()), false);
source.sendSuccess(() -> Component.literal("Instability: base " + totals.baseScore()
+ ", stability bonus " + totals.stabilityBonus()
+ ", penalty " + totals.instabilityPenalty()
+ ", effective " + totals.effectiveScore()), false);
source.sendSuccess(() -> Component.literal("Mutable player bonuses: disabled (no active Legacy registration)"),
false);
return totals.effectiveScore();
}
private static int pulseDecay(net.minecraft.commands.CommandSourceStack source, String colorName, int attempts) {
DecayBlock.Color color;
try {
color = DecayBlock.Color.valueOf(colorName.toUpperCase(java.util.Locale.ROOT));
} catch (IllegalArgumentException exception) {
source.sendFailure(Component.literal("Unknown decay color: " + colorName));
return 0;
}
if (source.getPlayer() == null) {
source.sendFailure(Component.literal("Run this command as a player standing in an Age."));
return 0;
}
int changed = AgeDecayProviders.pulseForTesting(source.getPlayer(), color, attempts);
if (changed < 0) {
source.sendFailure(Component.literal("Enter a loaded Age and enable instability.world_mutation and instability_decay.enabled first."));
return 0;
}
source.sendSuccess(() -> Component.literal("Decay " + colorName + ": " + changed
+ " block(s) converted in " + attempts + " bounded attempt(s)."), true);
return changed;
}
private static int pulseHazard(net.minecraft.commands.CommandSourceStack source, boolean lightning) {
if (source.getPlayer() == null) {
source.sendFailure(Component.literal("Run this command as a player standing in an Age."));
return 0;
}
int result = AgeHazardProviders.pulseForTesting(source.getPlayer(), lightning);
if (result < 0) source.sendFailure(Component.literal("Enter a loaded Age and enable instability_hazards.enabled first."));
else if (result == 0) source.sendFailure(Component.literal("Hazard is on cooldown or no safe loaded target is available."));
else source.sendSuccess(() -> Component.literal("Triggered one bounded "
+ (lightning ? "lightning strike" : "explosion") + " in this Age."), true);
return Math.max(0, result);
}
private static int pulseEnvironment(CommandSourceStack source, String effect) {
if (source.getPlayer() == null) {
source.sendFailure(Component.literal("Run this command as a player standing in an Age."));
return 0;
}
int result = AgeEnvironmentalProviders.pulseForTesting(source.getPlayer(), effect);
if (result == -2) source.sendFailure(Component.literal(
"Burning is extinguished by rain or water. Move to a dry, sky-exposed spot and retry."));
else if (result < 0) source.sendFailure(Component.literal("Enter a loaded Age to test the environmental effect."));
else if (result == 0) source.sendFailure(Component.literal(
"No eligible target, effect disabled, or meteor on cooldown. For erosion, aim at a block beside source fluid."));
else source.sendSuccess(() -> Component.literal("Triggered " + effect + " in this Age."), true);
return Math.max(0, result);
}
} }
@@ -18,6 +18,44 @@ public final class RivencraftConfig {
private static final ModConfigSpec.IntValue SYMBOL_INK_COST; private static final ModConfigSpec.IntValue SYMBOL_INK_COST;
private static final ModConfigSpec.IntValue LINK_PANEL_INK_COST; private static final ModConfigSpec.IntValue LINK_PANEL_INK_COST;
private static final ModConfigSpec.BooleanValue AUTO_WHITELIST_SERENE_AGES; private static final ModConfigSpec.BooleanValue AUTO_WHITELIST_SERENE_AGES;
private static final ModConfigSpec.BooleanValue INSTABILITY_ENABLED;
private static final ModConfigSpec.BooleanValue INSTABILITY_WORLD_MUTATION;
private static final ModConfigSpec.IntValue INSTABILITY_COOLDOWN;
private static final ModConfigSpec.IntValue INSTABILITY_MAX_AGES;
private static final ModConfigSpec.IntValue INSTABILITY_MAX_PROVIDERS;
private static final ModConfigSpec.IntValue INSTABILITY_MAX_ACTIONS;
private static final ModConfigSpec.IntValue INSTABILITY_MAX_LEVEL;
private static final ModConfigSpec.IntValue INSTABILITY_MAX_CHUNKS;
private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_ENABLED;
private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_PLAYERS;
private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_NONPLAYERS;
private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_HOSTILES;
private static final ModConfigSpec.IntValue STATUS_EFFECTS_MAX_ACTIVE;
private static final ModConfigSpec.IntValue STATUS_EFFECTS_MAX_CANDIDATES;
private static final ModConfigSpec.IntValue STATUS_EFFECTS_MAX_DURATION;
private static final ModConfigSpec.BooleanValue DECAY_ENABLED;
private static final ModConfigSpec.IntValue DECAY_MAX_ATTEMPTS;
private static final ModConfigSpec.BooleanValue HAZARDS_ENABLED;
private static final ModConfigSpec.BooleanValue HAZARDS_BLOCK_DAMAGE;
private static final ModConfigSpec.BooleanValue HAZARDS_PLAYER_DAMAGE;
private static final ModConfigSpec.BooleanValue HAZARDS_FIRE;
private static final ModConfigSpec.IntValue HAZARDS_MIN_INTERVAL;
private static final ModConfigSpec.IntValue HAZARDS_MAX_CHUNKS;
private static final ModConfigSpec.IntValue HAZARDS_MAX_BLOCKS;
private static final ModConfigSpec.IntValue HAZARDS_MAX_ENTITIES;
private static final ModConfigSpec.IntValue HAZARDS_MAX_DAMAGE;
private static final ModConfigSpec.IntValue HAZARDS_EXPLOSION_RADIUS;
private static final ModConfigSpec.BooleanValue METEOR_ENABLED;
private static final ModConfigSpec.BooleanValue METEOR_BLOCK_DAMAGE;
private static final ModConfigSpec.BooleanValue METEOR_PLAYER_DAMAGE;
private static final ModConfigSpec.BooleanValue METEOR_FIRE;
private static final ModConfigSpec.IntValue METEOR_MAX_BLOCKS;
private static final ModConfigSpec.IntValue METEOR_MAX_ENTITIES;
private static final ModConfigSpec.IntValue METEOR_MAX_DAMAGE;
private static final ModConfigSpec.BooleanValue SCORCH_ENABLED;
private static final ModConfigSpec.BooleanValue SCORCH_PLAYERS;
private static final ModConfigSpec.IntValue SCORCH_MAX_TARGETS;
private static final ModConfigSpec.BooleanValue EROSION_ENABLED;
static { static {
ModConfigSpec.Builder builder = new ModConfigSpec.Builder(); ModConfigSpec.Builder builder = new ModConfigSpec.Builder();
@@ -40,6 +78,98 @@ public final class RivencraftConfig {
"Existing entries are preserved; disabling this does not remove previously added Ages." "Existing entries are preserved; disabling this does not remove previously added Ages."
).define("auto_whitelist_ages", true); ).define("auto_whitelist_ages", true);
builder.pop(); builder.pop();
builder.push("instability");
INSTABILITY_ENABLED = builder.comment("Run selected instability providers in loaded Ages. Disabling does not alter saved plans.")
.define("enabled", true);
INSTABILITY_WORLD_MUTATION = builder.comment("Allow selected instability providers to change blocks or create explosions, as in Legacy.")
.define("world_mutation", true);
INSTABILITY_COOLDOWN = builder.comment("Minimum ticks between instability runs for each loaded Age.")
.defineInRange("cooldown_ticks", 20, 20, 1200);
INSTABILITY_MAX_AGES = builder.comment("Maximum loaded Ages processed in one server tick.")
.defineInRange("max_ages_per_tick", 4, 1, 16);
INSTABILITY_MAX_PROVIDERS = builder.comment("Maximum provider handlers called in one Age run.")
.defineInRange("max_providers_per_age", 2, 1, 16);
INSTABILITY_MAX_ACTIONS = builder.comment("Shared effect-action budget for one Age run.")
.defineInRange("max_actions_per_age", 1, 1, 16);
INSTABILITY_MAX_LEVEL = builder.comment("Maximum effective level passed to an effect handler; saved levels are unchanged.")
.defineInRange("max_effect_level", 3, 1, 16);
INSTABILITY_MAX_CHUNKS = builder.comment("Maximum already-loaded candidate chunks inspected per Age run.")
.defineInRange("max_loaded_chunks", 16, 1, 64);
builder.pop();
builder.push("instability_status_effects");
STATUS_EFFECTS_ENABLED = builder.comment("Allow bounded instability status effects in loaded Ages.")
.define("enabled", true);
STATUS_EFFECTS_PLAYERS = builder.comment("Allow instability status effects on survival/adventure players.")
.define("affect_players", true);
STATUS_EFFECTS_NONPLAYERS = builder.comment("Allow general instability status effects on non-player living entities, as in Legacy.")
.define("affect_nonplayers", true);
STATUS_EFFECTS_HOSTILES = builder.comment("Allow regeneration and resistance on hostile mobs.")
.define("buff_hostiles", true);
STATUS_EFFECTS_MAX_ACTIVE = builder.comment("Maximum Rivencraft-owned active effect leases per Age.")
.defineInRange("max_active_per_age", 32, 1, 128);
STATUS_EFFECTS_MAX_CANDIDATES = builder.comment("Maximum living entities examined in one chosen loaded chunk.")
.defineInRange("max_candidates_per_attempt", 8, 1, 16);
STATUS_EFFECTS_MAX_DURATION = builder.comment("Maximum duration in ticks for one instability status effect.")
.defineInRange("max_duration_ticks", 200, 20, 200);
builder.pop();
builder.push("instability_decay");
DECAY_ENABLED = builder.comment("Allow destructive colored decay inside loaded Ages, as in Legacy. Also requires instability.world_mutation.")
.define("enabled", true);
DECAY_MAX_ATTEMPTS = builder.comment("Maximum six-neighbor decay conversion attempts per provider call; at most one block changes.")
.defineInRange("max_attempts_per_call", 4, 1, 6);
builder.pop();
builder.push("instability_hazards");
HAZARDS_ENABLED = builder.comment("Run Legacy lightning and explosion cards in loaded Ages.")
.define("enabled", true);
HAZARDS_BLOCK_DAMAGE = builder.comment("Allow explosions to destroy blocks. Also requires instability.world_mutation and mobGriefing.")
.define("block_damage", true);
HAZARDS_PLAYER_DAMAGE = builder.comment("Allow lightning and explosions to hurt survival/adventure players.")
.define("player_damage", true);
HAZARDS_FIRE = builder.comment("Allow lightning and explosions to ignite blocks when doFireTick is enabled.")
.define("fire", true);
HAZARDS_MIN_INTERVAL = builder.comment("Minimum game ticks between hazard events of each type in one Age.",
"Renamed from min_interval_ticks so existing 200-tick test configs receive the Legacy-rate default.")
.defineInRange("minimum_gap_ticks", 20, 20, 12000);
HAZARDS_MAX_CHUNKS = builder.comment("Maximum already-loaded chunks sampled around Age players per hazard roll.")
.defineInRange("max_loaded_chunks", 81, 1, 169);
HAZARDS_MAX_BLOCKS = builder.comment("Maximum distinct blocks one instability explosion may destroy.")
.defineInRange("max_explosion_blocks", 16, 0, 64);
HAZARDS_MAX_ENTITIES = builder.comment("Maximum entities damaged by one hazard event.")
.defineInRange("max_damaged_entities", 8, 0, 32);
HAZARDS_MAX_DAMAGE = builder.comment("Maximum damage per entity from one hazard event.")
.defineInRange("max_entity_damage", 12, 0, 40);
HAZARDS_EXPLOSION_RADIUS = builder.comment("Explosion strength. Legacy used 3; capped to remain inside one loaded chunk.")
.defineInRange("explosion_radius", 3, 1, 3);
builder.pop();
builder.push("instability_meteor");
METEOR_ENABLED = builder.comment("Allow the active Legacy meteor card in loaded Ages.")
.define("enabled", true);
METEOR_BLOCK_DAMAGE = builder.comment("Allow meteor impacts to destroy blocks; also requires instability.world_mutation and mobGriefing.")
.define("block_damage", true);
METEOR_PLAYER_DAMAGE = builder.comment("Allow meteor impacts to hurt survival/adventure players.")
.define("player_damage", true);
METEOR_FIRE = builder.comment("Allow meteor impacts to ignite blocks when doFireTick is enabled.")
.define("fire", true);
METEOR_MAX_BLOCKS = builder.comment("Maximum blocks destroyed by one meteor impact.")
.defineInRange("max_impact_blocks", 24, 0, 64);
METEOR_MAX_ENTITIES = builder.comment("Maximum entities damaged by one meteor impact.")
.defineInRange("max_damaged_entities", 8, 0, 32);
METEOR_MAX_DAMAGE = builder.comment("Maximum damage per entity from one meteor impact.")
.defineInRange("max_entity_damage", 12, 0, 40);
builder.pop();
builder.push("instability_scorching");
SCORCH_ENABLED = builder.comment("Allow Legacy's active burning card to ignite sky-exposed entities.")
.define("enabled", true);
SCORCH_PLAYERS = builder.comment("Allow burning to affect survival/adventure players.")
.define("affect_players", true);
SCORCH_MAX_TARGETS = builder.comment("Maximum entities ignited per Age scheduler pass.")
.defineInRange("max_targets_per_pass", 4, 0, 16);
builder.pop();
builder.push("instability_erosion");
EROSION_ENABLED = builder.comment("Enable Legacy's dormant erosion effect for testing; no saved provider card is added.",
"Ages with a destructive instability score may spread adjacent fluid into one safe block per pass.")
.define("enabled", true);
builder.pop();
SPEC = builder.build(); SPEC = builder.build();
} }
@@ -61,4 +191,43 @@ public final class RivencraftConfig {
public static boolean autoWhitelistSereneAges() { public static boolean autoWhitelistSereneAges() {
return AUTO_WHITELIST_SERENE_AGES.get(); return AUTO_WHITELIST_SERENE_AGES.get();
} }
public static boolean instabilityEnabled() { return INSTABILITY_ENABLED.get(); }
public static boolean instabilityWorldMutation() { return INSTABILITY_WORLD_MUTATION.get(); }
public static int instabilityCooldown() { return INSTABILITY_COOLDOWN.get(); }
public static int instabilityMaxAges() { return INSTABILITY_MAX_AGES.get(); }
public static int instabilityMaxProviders() { return INSTABILITY_MAX_PROVIDERS.get(); }
public static int instabilityMaxActions() { return INSTABILITY_MAX_ACTIONS.get(); }
public static int instabilityMaxLevel() { return INSTABILITY_MAX_LEVEL.get(); }
public static int instabilityMaxChunks() { return INSTABILITY_MAX_CHUNKS.get(); }
public static boolean statusEffectsEnabled() { return STATUS_EFFECTS_ENABLED.get(); }
public static boolean statusEffectsPlayers() { return STATUS_EFFECTS_PLAYERS.get(); }
public static boolean statusEffectsNonplayers() { return STATUS_EFFECTS_NONPLAYERS.get(); }
public static boolean statusEffectsHostiles() { return STATUS_EFFECTS_HOSTILES.get(); }
public static int statusEffectsMaxActive() { return STATUS_EFFECTS_MAX_ACTIVE.get(); }
public static int statusEffectsMaxCandidates() { return STATUS_EFFECTS_MAX_CANDIDATES.get(); }
public static int statusEffectsMaxDuration() { return STATUS_EFFECTS_MAX_DURATION.get(); }
public static boolean decayEnabled() { return DECAY_ENABLED.get(); }
public static int decayMaxAttempts() { return DECAY_MAX_ATTEMPTS.get(); }
public static boolean hazardsEnabled() { return HAZARDS_ENABLED.get(); }
public static boolean hazardsBlockDamage() { return HAZARDS_BLOCK_DAMAGE.get(); }
public static boolean hazardsPlayerDamage() { return HAZARDS_PLAYER_DAMAGE.get(); }
public static boolean hazardsFire() { return HAZARDS_FIRE.get(); }
public static int hazardsMinInterval() { return HAZARDS_MIN_INTERVAL.get(); }
public static int hazardsMaxChunks() { return HAZARDS_MAX_CHUNKS.get(); }
public static int hazardsMaxBlocks() { return HAZARDS_MAX_BLOCKS.get(); }
public static int hazardsMaxEntities() { return HAZARDS_MAX_ENTITIES.get(); }
public static int hazardsMaxDamage() { return HAZARDS_MAX_DAMAGE.get(); }
public static int hazardsExplosionRadius() { return HAZARDS_EXPLOSION_RADIUS.get(); }
public static boolean meteorEnabled() { return METEOR_ENABLED.get(); }
public static boolean meteorBlockDamage() { return METEOR_BLOCK_DAMAGE.get(); }
public static boolean meteorPlayerDamage() { return METEOR_PLAYER_DAMAGE.get(); }
public static boolean meteorFire() { return METEOR_FIRE.get(); }
public static int meteorMaxBlocks() { return METEOR_MAX_BLOCKS.get(); }
public static int meteorMaxEntities() { return METEOR_MAX_ENTITIES.get(); }
public static int meteorMaxDamage() { return METEOR_MAX_DAMAGE.get(); }
public static boolean scorchEnabled() { return SCORCH_ENABLED.get(); }
public static boolean scorchPlayers() { return SCORCH_PLAYERS.get(); }
public static int scorchMaxTargets() { return SCORCH_MAX_TARGETS.get(); }
public static boolean erosionEnabled() { return EROSION_ENABLED.get(); }
} }
@@ -0,0 +1,68 @@
package net.dnorberg.rivencraft.gametest;
import java.util.ArrayList;
import java.util.List;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.block.entity.BookBinderBlockEntity;
import net.dnorberg.rivencraft.item.PageItem;
import net.dnorberg.rivencraft.registry.ModBlocks;
import net.dnorberg.rivencraft.registry.ModItems;
import net.dnorberg.rivencraft.writing.NotebookContents;
import net.dnorberg.rivencraft.writing.SymbolReference;
import net.minecraft.core.BlockPos;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.neoforged.neoforge.gametest.GameTestHolder;
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
@GameTestHolder(Rivencraft.MOD_ID)
@PrefixGameTestTemplate(false)
public final class BookPageCapacityGameTests {
private BookPageCapacityGameTests() {}
private static ItemStack page(String path) {
return PageItem.createSymbolPage(new SymbolReference(
ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path)));
}
@GameTest(template = "empty")
public static void binderAndNotebookRetainPagesBeyondOldLimit(GameTestHelper helper) {
BlockPos pos = helper.absolutePos(new BlockPos(1, 1, 1));
helper.getLevel().setBlock(pos, ModBlocks.BOOK_BINDER.get().defaultBlockState(), 3);
BookBinderBlockEntity binder = (BookBinderBlockEntity) helper.getLevel().getBlockEntity(pos);
binder.setTitle("Long Age");
binder.setItem(BookBinderBlockEntity.COVER, new ItemStack(Items.LEATHER));
binder.setItem(BookBinderBlockEntity.LINK_PANEL, PageItem.createLinkPanelPage());
for (int index = 0; index < 32; index++) {
helper.assertTrue(binder.insertPage(index, page("terrain/standard")),
"Binder must accept page " + (index + 1));
}
binder.setItem(BookBinderBlockEntity.SIZE - 1, page("weather/normal"));
BookBinderBlockEntity restored = new BookBinderBlockEntity(pos, binder.getBlockState());
restored.setLevel(helper.getLevel());
restored.loadWithComponents(binder.saveWithoutMetadata(helper.getLevel().registryAccess()),
helper.getLevel().registryAccess());
helper.assertValueEqual(restored.nextPageIndex(), BookBinderBlockEntity.PAGE_COUNT,
"Binder must retain its highest valid page position after reload");
helper.assertTrue(restored.getItem(BookBinderBlockEntity.FIRST_PAGE + 31).is(ModItems.PAGE.get()),
"Page 32 must survive reload");
helper.assertTrue(restored.getItem(BookBinderBlockEntity.SIZE - 1).is(ModItems.PAGE.get()),
"The final fixed-slot page must survive reload");
helper.assertValueEqual(restored.writingGrammar().symbols().size(), 33,
"Grammar must retain all authored pages");
List<ItemStack> notebookPages = new ArrayList<>();
for (int index = 0; index < NotebookContents.MAX_PAGES; index++) notebookPages.add(ItemStack.EMPTY);
notebookPages.set(31, page("terrain/standard"));
notebookPages.set(NotebookContents.MAX_PAGES - 1, page("weather/normal"));
NotebookContents notebook = new NotebookContents(notebookPages);
helper.assertValueEqual(notebook.pages().size(), NotebookContents.MAX_PAGES,
"Notebook must retain its highest valid page position");
helper.assertValueEqual(notebook.pageCount(), 2,
"Sparse Notebook contents must retain both pages");
helper.succeed();
}
}
@@ -1,5 +1,7 @@
package net.dnorberg.rivencraft.gametest; package net.dnorberg.rivencraft.gametest;
import net.dnorberg.rivencraft.registry.ModBlocks;
import net.dnorberg.rivencraft.Rivencraft; import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.book.AgeDefinition; import net.dnorberg.rivencraft.book.AgeDefinition;
import net.dnorberg.rivencraft.book.AgeBiomeSelection; import net.dnorberg.rivencraft.book.AgeBiomeSelection;
@@ -234,7 +236,7 @@ public final class LinkingGameTests {
helper.assertValueEqual(ageLevel.getSeed(), definition.seed(), helper.assertValueEqual(ageLevel.getSeed(), definition.seed(),
"The runtime dimension seed must match the persisted Age definition"); "The runtime dimension seed must match the persisted Age definition");
BlockPos spawn = target.location().pos(); BlockPos spawn = target.location().pos();
helper.assertTrue(ageLevel.getBlockState(spawn.below()).is(Blocks.COBBLESTONE), helper.assertTrue(ageLevel.getBlockState(spawn.below()).is(ModBlocks.CLOUD_PLATFORM.get()),
"The generated Age must have a cobblestone arrival platform"); "The generated Age must have a cobblestone arrival platform");
helper.assertTrue(ageLevel.getBlockState(spawn).isAir() && ageLevel.getBlockState(spawn.above()).isAir(), helper.assertTrue(ageLevel.getBlockState(spawn).isAir() && ageLevel.getBlockState(spawn.above()).isAir(),
"The generated Age arrival must have clear headroom"); "The generated Age arrival must have clear headroom");
@@ -285,7 +287,7 @@ public final class LinkingGameTests {
var ageLevel = player.getServer().getLevel(destination.location().dimension()); var ageLevel = player.getServer().getLevel(destination.location().dimension());
helper.assertTrue(ageLevel != null, profile + " must create a loaded runtime dimension"); helper.assertTrue(ageLevel != null, profile + " must create a loaded runtime dimension");
BlockPos spawn = destination.location().pos(); BlockPos spawn = destination.location().pos();
helper.assertTrue(ageLevel != null && ageLevel.getBlockState(spawn.below()).is(Blocks.COBBLESTONE), helper.assertTrue(ageLevel != null && ageLevel.getBlockState(spawn.below()).is(ModBlocks.CLOUD_PLATFORM.get()),
profile + " must create a solid arrival platform"); profile + " must create a solid arrival platform");
helper.assertTrue(ageLevel != null && ageLevel.getBlockState(spawn).isAir() helper.assertTrue(ageLevel != null && ageLevel.getBlockState(spawn).isAir()
&& ageLevel.getBlockState(spawn.above()).isAir(), && ageLevel.getBlockState(spawn.above()).isAir(),
@@ -23,11 +23,11 @@ import net.minecraft.world.item.Items;
/** Fixed, ordered binder slots and a server-owned virtual result. */ /** Fixed, ordered binder slots and a server-owned virtual result. */
public final class BookBinderMenu extends AbstractContainerMenu { public final class BookBinderMenu extends AbstractContainerMenu {
public static final int RESULT = BookBinderBlockEntity.SIZE; public static final int RESULT = BookBinderBlockEntity.SIZE;
public static final int SELECT_BASE = 100; public static final int SELECT_BASE = 1000;
public static final int MOVE_PREVIOUS = 200; public static final int MOVE_PREVIOUS = 2000;
public static final int MOVE_NEXT = 201; public static final int MOVE_NEXT = 2001;
public static final int IMPORT_NOTEBOOK = 202; public static final int IMPORT_NOTEBOOK = 2002;
public static final int STRIP_CLICK_BASE = 300; public static final int STRIP_CLICK_BASE = 3000;
private static final int PLAYER_START = RESULT + 1; private static final int PLAYER_START = RESULT + 1;
private final BookBinderBlockEntity binder; private final BookBinderBlockEntity binder;
@@ -40,11 +40,9 @@ public final class NotebookMenu extends AbstractContainerMenu {
this.openedHotbarSlot = inventory.selected; this.openedHotbarSlot = inventory.selected;
this.contents = new NotebookContainer(inventory, hand); this.contents = new NotebookContainer(inventory, hand);
for (int row = 0; row < 3; row++) { for (int page = 0; page < NOTEBOOK_SLOTS; page++) {
for (int column = 0; column < 9; column++) { // The client draws these pages on a filtered, scrollable surface instead.
// The client draws these pages on a filtered, scrollable surface instead. addSlot(new PageSlot(contents, page, -1000, -1000));
addSlot(new PageSlot(contents, column + row * 9, -1000, -1000));
}
} }
for (int row = 0; row < 3; row++) { for (int row = 0; row < 3; row++) {
for (int column = 0; column < 9; column++) { for (int column = 0; column < 9; column++) {
@@ -0,0 +1,37 @@
package net.dnorberg.rivencraft.mixin;
import java.util.List;
import java.util.Optional;
import net.dnorberg.rivencraft.book.AgeFeatureSelection;
import net.dnorberg.rivencraft.book.AgeStructureSelection;
import net.dnorberg.rivencraft.world.AgeFeatureChunkGenerator;
import net.dnorberg.rivencraft.world.AgeFlatChunkGenerator;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.structure.Structure;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/** Lets explicitly authored structures generate outside their vanilla biome sets. */
@Mixin(Structure.class)
public abstract class AgeStructureBiomeMixin {
@Shadow
protected abstract Optional<Structure.GenerationStub> findGenerationPoint(
Structure.GenerationContext context);
@Inject(method = "findValidGenerationPoint", at = @At("HEAD"), cancellable = true)
private void rivencraft$allowAuthoredStructureBiome(Structure.GenerationContext context,
CallbackInfoReturnable<Optional<Structure.GenerationStub>> cir) {
ChunkGenerator generator = context.chunkGenerator();
List<AgeFeatureSelection.Choice> features;
if (generator instanceof AgeFeatureChunkGenerator age) features = age.ageFeatures();
else if (generator instanceof AgeFlatChunkGenerator age) features = age.ageFeatures();
else return;
if (AgeStructureSelection.authoredStructure((Structure) (Object) this,
context.registryAccess(), features)) {
cir.setReturnValue(findGenerationPoint(context));
}
}
}
@@ -0,0 +1,26 @@
package net.dnorberg.rivencraft.mixin;
import java.util.Optional;
import net.minecraft.core.Vec3i;
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
/** Exposes immutable placement settings so per-Age structure density can preserve vanilla behavior. */
@Mixin(StructurePlacement.class)
public interface StructurePlacementAccessor {
@Accessor("locateOffset")
Vec3i rivencraft$locateOffset();
@Accessor("frequencyReductionMethod")
StructurePlacement.FrequencyReductionMethod rivencraft$frequencyReductionMethod();
@Accessor("frequency")
float rivencraft$frequency();
@Accessor("salt")
int rivencraft$salt();
@Accessor("exclusionZone")
Optional<StructurePlacement.ExclusionZone> rivencraft$exclusionZone();
}
@@ -7,6 +7,8 @@ import net.dnorberg.rivencraft.block.WritingDeskBlock;
import net.dnorberg.rivencraft.block.InkMixerBlock; import net.dnorberg.rivencraft.block.InkMixerBlock;
import net.dnorberg.rivencraft.block.BuddingCrystalBlock; import net.dnorberg.rivencraft.block.BuddingCrystalBlock;
import net.dnorberg.rivencraft.block.StarFissureBlock; import net.dnorberg.rivencraft.block.StarFissureBlock;
import net.dnorberg.rivencraft.block.DecayBlock;
import net.dnorberg.rivencraft.block.CloudPlatformBlock;
import net.minecraft.world.level.block.AmethystClusterBlock; import net.minecraft.world.level.block.AmethystClusterBlock;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
@@ -56,6 +58,12 @@ public final class ModBlocks {
public static final DeferredBlock<StarFissureBlock> STAR_FISSURE = BLOCKS.registerBlock("star_fissure", public static final DeferredBlock<StarFissureBlock> STAR_FISSURE = BLOCKS.registerBlock("star_fissure",
StarFissureBlock::new, BlockBehaviour.Properties.ofFullCopy(Blocks.END_PORTAL) StarFissureBlock::new, BlockBehaviour.Properties.ofFullCopy(Blocks.END_PORTAL)
.lightLevel(state -> 6)); .lightLevel(state -> 6));
public static final DeferredBlock<DecayBlock> DECAY = BLOCKS.registerBlock("decay",
DecayBlock::new, BlockBehaviour.Properties.ofFullCopy(Blocks.STONE)
.strength(5.0F, 10.0F).noLootTable());
public static final DeferredBlock<CloudPlatformBlock> CLOUD_PLATFORM = BLOCKS.registerBlock("cloud_platform",
CloudPlatformBlock::new, BlockBehaviour.Properties.ofFullCopy(Blocks.WHITE_STAINED_GLASS)
.strength(1.5F).noOcclusion().noLootTable());
private ModBlocks() { private ModBlocks() {
} }
@@ -15,6 +15,7 @@ public final class ModSounds {
public static final DeferredHolder<SoundEvent, SoundEvent> LINK = register("linking.link"); public static final DeferredHolder<SoundEvent, SoundEvent> LINK = register("linking.link");
public static final DeferredHolder<SoundEvent, SoundEvent> LINK_FISSURE = register("linking.link-fissure"); public static final DeferredHolder<SoundEvent, SoundEvent> LINK_FISSURE = register("linking.link-fissure");
public static final DeferredHolder<SoundEvent, SoundEvent> METEOR_ROAR = register("entity.meteor.roar");
private ModSounds() { private ModSounds() {
} }
@@ -13,7 +13,9 @@ import net.minecraft.world.item.ItemStack;
/** A bounded, position-preserving collection of Page stacks stored on a Notebook item. */ /** A bounded, position-preserving collection of Page stacks stored on a Notebook item. */
public record NotebookContents(List<ItemStack> pages) { public record NotebookContents(List<ItemStack> pages) {
public static final int MAX_PAGES = 27; // Legacy did not impose a book-page cap. Our fixed-slot binder persists slot IDs
// as unsigned bytes; 252 page positions (after its three input slots) fit safely.
public static final int MAX_PAGES = 252;
public static final NotebookContents EMPTY = new NotebookContents(List.of()); public static final NotebookContents EMPTY = new NotebookContents(List.of());
public static final Codec<NotebookContents> CODEC = ItemStack.OPTIONAL_CODEC.listOf() public static final Codec<NotebookContents> CODEC = ItemStack.OPTIONAL_CODEC.listOf()
.validate(NotebookContents::validate) .validate(NotebookContents::validate)
@@ -14,7 +14,7 @@ import net.minecraft.resources.ResourceLocation;
/** Server-owned interpretation of ordered writing before Age-plan compilation. */ /** Server-owned interpretation of ordered writing before Age-plan compilation. */
public final class WritingGrammar { public final class WritingGrammar {
// A newly assembled book has one Link Panel plus at most 27 page positions. // A newly assembled book has one Link Panel plus the binder's page positions.
public static final int MAX_NEW_ENTRIES = NotebookContents.MAX_PAGES + 1; public static final int MAX_NEW_ENTRIES = NotebookContents.MAX_PAGES + 1;
private static final Set<String> MATERIAL_FEATURES = Set.of("rocks", "surface_lakes", "deep_lakes", private static final Set<String> MATERIAL_FEATURES = Set.of("rocks", "surface_lakes", "deep_lakes",
"lava_lakes", "floating_islands", "tendrils", "spheres", "spikes", "obelisks"); "lava_lakes", "floating_islands", "tendrils", "spheres", "spikes", "obelisks");
@@ -0,0 +1 @@
{"variants":{"":{"model":"rivencraft:block/cloud_platform"}}}
@@ -0,0 +1,8 @@
{
"variants": {
"color=blue": { "model": "rivencraft:block/decay_blue" },
"color=purple": { "model": "rivencraft:block/decay_purple" },
"color=red": { "model": "rivencraft:block/decay_red" },
"color=white": { "model": "rivencraft:block/decay_white" }
}
}
@@ -24,6 +24,8 @@
"block.rivencraft.book_binder": "Book Binder", "block.rivencraft.book_binder": "Book Binder",
"container.rivencraft.book_binder": "Book Binder", "container.rivencraft.book_binder": "Book Binder",
"block.rivencraft.ink_mixer": "Ink Mixer", "block.rivencraft.ink_mixer": "Ink Mixer",
"block.rivencraft.decay": "Decay",
"block.rivencraft.cloud_platform": "Cloud Platform",
"container.rivencraft.ink_mixer": "Ink Mixer", "container.rivencraft.ink_mixer": "Ink Mixer",
"screen.rivencraft.ink_mixer.ink": "Ink: %s/%s", "screen.rivencraft.ink_mixer.ink": "Ink: %s/%s",
"screen.rivencraft.ink_mixer.additive_hint": "Click the basin with an additive; right-click adds one.", "screen.rivencraft.ink_mixer.additive_hint": "Click the basin with an additive; right-click adds one.",
@@ -0,0 +1 @@
{"parent":"minecraft:block/cube_all","render_type":"minecraft:translucent","textures":{"all":"rivencraft:block/cloud_platform"}}
@@ -0,0 +1 @@
{"parent":"minecraft:block/cube_all","textures":{"all":"rivencraft:block/decay_blue"}}
@@ -0,0 +1 @@
{"parent":"minecraft:block/cube_all","textures":{"all":"rivencraft:block/decay_purple"}}
@@ -0,0 +1 @@
{"parent":"minecraft:block/cube_all","textures":{"all":"rivencraft:block/decay_red"}}
@@ -0,0 +1 @@
{"parent":"minecraft:block/cube_all","textures":{"all":"rivencraft:block/decay_white"}}
@@ -10,5 +10,9 @@
"linking.link-fissure": { "linking.link-fissure": {
"category": "player", "category": "player",
"sounds": [{"name": "rivencraft:linking/link-fissure"}] "sounds": [{"name": "rivencraft:linking/link-fissure"}]
},
"entity.meteor.roar": {
"category": "hostile",
"sounds": [{"name": "rivencraft:entity/meteor/roar"}]
} }
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 868 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 B

@@ -0,0 +1,24 @@
{
"replace": false,
"values": [
"minecraft:bedrock",
"minecraft:barrier",
"minecraft:end_portal",
"minecraft:end_portal_frame",
"minecraft:end_gateway",
"minecraft:nether_portal",
"minecraft:reinforced_deepslate",
"minecraft:structure_block",
"minecraft:jigsaw",
"minecraft:command_block",
"minecraft:chain_command_block",
"minecraft:repeating_command_block",
"minecraft:light",
"rivencraft:book_stand",
"rivencraft:writing_desk",
"rivencraft:book_binder",
"rivencraft:ink_mixer",
"rivencraft:star_fissure",
"rivencraft:cloud_platform"
]
}
+3 -1
View File
@@ -4,7 +4,9 @@
"package": "net.dnorberg.rivencraft.mixin", "package": "net.dnorberg.rivencraft.mixin",
"compatibilityLevel": "JAVA_21", "compatibilityLevel": "JAVA_21",
"mixins": [ "mixins": [
"AgeDungeonPlacementMixin" "AgeDungeonPlacementMixin",
"AgeStructureBiomeMixin",
"StructurePlacementAccessor"
], ],
"client": [ "client": [
"client.ClientLevelSoundMixin", "client.ClientLevelSoundMixin",