Compare commits

..
3 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
29 changed files with 1067 additions and 63 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
ordered-writing model. Linking Books and Descriptive Books create persistent
Ages from either authored supported symbols or seeded random completion.
Instability and the remaining unsupported Legacy symbol effects have not been
ported yet. The [Milestone 5 acceptance record](docs/MILESTONE_5_ACCEPTANCE.md)
lists the supported grammar, optional integrations, and limits.
Milestone 6 instability work is in progress: Ages persist frozen instability
scores and provider plans, and the bounded runtime implements status effects,
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,
unresolved-symbol, and baseline link-panel states. Page visuals follow the
+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/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/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
full LGPL v3 text in its root `LICENSE` file. Rivencraft's root `LICENSE`
+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.
+1 -1
View File
@@ -6,7 +6,7 @@ The saved provider IDs are independent of installed handlers. A missing optional
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; the remaining hazards belong to #70. 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.
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)
+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.
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. Issue #66 additionally freezes a provider selection from this score; see [runtime policy](INSTABILITY_RUNTIME.md).
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.
`/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.
+16 -10
View File
@@ -1,6 +1,6 @@
# 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
@@ -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. |
| 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).
[`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 |
| --- | --- | --- |
| 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. |
| 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. |
| 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)). | 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)). | 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. |
| 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. |
| 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 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. |
| 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.
## 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.
Issue #66 establishes a server-only scheduler with bounded per-Age actions, provider calls, levels, cooldowns, loaded-chunk candidates, and rotating active-Age admission. World-mutating handlers are **off by default**. No provider effects are registered yet; #67–#70 must enforce protected spawn/link platforms, portals, and provider-specific damage/spread limits before activation. These are **Rivencraft safety adaptations**, not Legacy defaults. Expose score breakdown, selected effects, enablement, and budget suppression in server diagnostics (#72). See [runtime policy](INSTABILITY_RUNTIME.md).
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.
+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
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
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
subset.** See the [acceptance record](MILESTONE_5_ACCEPTANCE.md) and
[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
source behavior from proposed 1.21.1 safety limits.
7. **Structures and polish** — libraries, crystals, portals, recipes, models,
+1 -1
View File
@@ -6,7 +6,7 @@ New Binder writing has at most one Link Panel plus 252 symbol pages (the current
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.
+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.
mod_license=LGPL-3.0-or-later
# The mod version. Rivencraft uses the x.y.z.b policy documented in README.md.
mod_version=0.5.7.1
mod_version=0.5.8.4
immersive_portals_version=6.0.7
terrablender_version=4.1.0.8
serene_seasons_version_id=B6nTjh4b
@@ -25,6 +25,7 @@ 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.writing.SymbolCatalog;
import net.neoforged.bus.api.IEventBus;
@@ -44,6 +45,7 @@ public final class Rivencraft {
AgeStatusEffectProviders.register();
AgeDecayProviders.register();
AgeHazardProviders.register();
AgeEnvironmentalProviders.register();
modContainer.registerConfig(ModConfig.Type.SERVER, RivencraftConfig.SPEC);
modContainer.registerConfig(ModConfig.Type.CLIENT, RivencraftClientConfig.SPEC);
modEventBus.addListener(ModNetworking::register);
@@ -60,6 +62,8 @@ public final class Rivencraft {
NeoForge.EVENT_BUS.addListener(BookStandConversionHandler::onRightClickBlock);
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);
@@ -70,6 +74,7 @@ public final class Rivencraft {
NeoForge.EVENT_BUS.addListener(AgeLifecycleEvents::onPlayerLoggedOut);
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(AgeRuntimeProfiles::register);
@@ -88,6 +88,9 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List<R
Random countRandom = new Random(seed ^ 0x42494F4D45434F55L);
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.
List<ResourceLocation> filler = profile.terrain() == AgeRuntimeProfile.Terrain.VOID && !authored.isEmpty()
? new ArrayList<>() : new ArrayList<>(availableBiomes);
@@ -103,6 +106,59 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List<R
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) {
var registry = registries.lookupOrThrow(Registries.BIOME);
if (isCave(profile)) {
@@ -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) {}
}
@@ -68,7 +68,7 @@ public final class AgeHazardProviders {
}
}
private static List<ChunkPos> loadedChunksNearPlayers(ServerLevel level, int maximum) {
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();
@@ -188,13 +188,23 @@ public final class AgeHazardProviders {
}
private static void explode(ServerLevel level, AgeDefinition age, ChunkPos chunk, BlockPos pos) {
boolean grief = canMutate(level) && RivencraftConfig.hazardsBlockDamage()
&& RivencraftConfig.hazardsMaxBlocks() > 0;
boolean fire = grief && RivencraftConfig.hazardsFire()
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),
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,
RivencraftConfig.hazardsExplosionRadius(), false,
radius, false,
grief ? Level.ExplosionInteraction.BLOCK : Level.ExplosionInteraction.NONE);
if (fire) {
int ignited = 0;
@@ -222,13 +232,17 @@ public final class AgeHazardProviders {
return true;
}
private static boolean canMutate(ServerLevel level) {
static boolean canMutate(ServerLevel level) {
return RivencraftConfig.instabilityWorldMutation()
&& level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING);
}
private static boolean eligibleEntity(Entity entity) {
return !(entity instanceof Player player) || RivencraftConfig.hazardsPlayerDamage()
return eligibleEntity(entity, RivencraftConfig.hazardsPlayerDamage());
}
private static boolean eligibleEntity(Entity entity, boolean playerDamage) {
return !(entity instanceof Player player) || playerDamage
&& !player.isCreative() && !player.isSpectator();
}
@@ -241,15 +255,24 @@ public final class AgeHazardProviders {
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) {
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
@@ -269,7 +292,7 @@ public final class AgeHazardProviders {
|| 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() >= RivencraftConfig.hazardsMaxBlocks()) return false;
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);
@@ -281,8 +304,8 @@ public final class AgeHazardProviders {
@Override
public boolean shouldDamageEntity(Explosion explosion, Entity entity) {
if (damaged >= RivencraftConfig.hazardsMaxEntities() || !eligibleEntity(entity)
|| RivencraftConfig.hazardsMaxDamage() == 0) return false;
if (damaged >= maxEntities || !eligibleEntity(entity, playerDamage)
|| maxDamage == 0) return false;
damaged++;
damagedEntities.add(entity.getUUID());
return true;
@@ -290,7 +313,7 @@ public final class AgeHazardProviders {
@Override
public float getEntityDamageAmount(Explosion explosion, Entity entity) {
return Math.min(super.getEntityDamageAmount(explosion, entity), RivencraftConfig.hazardsMaxDamage());
return Math.min(super.getEntityDamageAmount(explosion, entity), maxDamage);
}
@Override
@@ -13,6 +13,7 @@ public final class AgeHazardSavedData extends SavedData {
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");
@@ -34,11 +35,21 @@ public final class AgeHazardSavedData extends SavedData {
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;
}
@@ -47,6 +58,7 @@ public final class AgeHazardSavedData extends SavedData {
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;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import net.dnorberg.rivencraft.writing.WritingGrammar;
import net.minecraft.core.RegistryAccess;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.resources.ResourceLocation;
/** Frozen, server-owned score. Only new Age creation consults the current symbol catalog. */
public record AgeInstability(int version, int score, List<Contribution> breakdown) {
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 {
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")));
}
static AgeInstability compute(AgeGenerationPlan plan, AgeTraits traits) {
static AgeInstability compute(AgeGenerationPlan plan, AgeTraits traits, RegistryAccess registries) {
Objects.requireNonNull(traits, "traits");
List<Contribution> contributions = new ArrayList<>();
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),
diagnostic.index(), diagnostic.instability(), diagnostic.message()));
}
addAuditedSymbolCosts(plan, registries, contributions);
}
// Legacy's bright-lighting symbol adds +500. Other balance costs are deferred
// until their corresponding authored symbols and audited values exist.
if (traits.lighting() == AgeTraits.Lighting.BRIGHT) {
int pageIndex = plan == null ? -1 : plan.activeSymbols().stream()
.filter(symbol -> symbol.semantics().role()
== net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING)
.mapToInt(AgeGenerationPlan.ResolvedSymbol::index).findFirst().orElse(-1);
contributions.add(new Contribution("bright_lighting", pageIndex, 500,
pageIndex < 0 ? "Seeded bright lighting" : "Authored bright lighting"));
// A missing lighting controller is seed-completed. Legacy runs the generated
// symbol's own modifier, so a generated Bright Lighting choice still costs 500.
if (traits.lighting() == AgeTraits.Lighting.BRIGHT && (plan == null || plan.symbols().stream()
.noneMatch(symbol -> symbol.semantics().role()
== net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING))) {
contributions.add(new Contribution("bright_lighting", -1, BRIGHT_LIGHTING_COST,
"Seeded bright lighting"));
}
return new AgeInstability(CURRENT_VERSION,
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() {
CompoundTag tag = new CompoundTag();
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");
}
}
}
}
@@ -55,6 +55,7 @@ public final class AgeInstabilityRuntime {
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());
@@ -65,7 +66,8 @@ public final class AgeInstabilityRuntime {
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())) continue;
if (AgeHazardProviders.isHazard(provider.id())
|| AgeEnvironmentalProviders.isEnvironmental(provider.id())) continue;
if (invoke(context, provider.id(), provider.level())) ran++;
}
}
@@ -8,6 +8,7 @@ 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;
@@ -94,9 +95,59 @@ public final class AgeInstabilityRuntimeGameTests {
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);
@@ -125,13 +125,91 @@ public final class AgePersistenceGameTests {
AgeInstability bright = AgeInstability.compute(null, new AgeTraits(
AgeTraits.LEGACY_DEFAULTS.biomeDistribution(), AgeTraits.Lighting.BRIGHT,
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(AgeInstability.load(bright.save()), bright,
"A score must survive its own versioned round trip");
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")
public static void missingRegistryEntryDoesNotReinterpretAnOldAge(GameTestHelper helper) {
UUID id = UUID.randomUUID();
@@ -135,7 +135,7 @@ public final class AgeRegistrySavedData extends SavedData {
AgeTraits traits = AgeTraits.select(seed);
AgeGenerationPlan plan = AgeGenerationPlan.compile(writing, seed, seedProfile, traits, registries);
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(
reference.id(),
@@ -4,6 +4,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.mixin.StructurePlacementAccessor;
import net.dnorberg.rivencraft.writing.OrderedWriting;
import net.dnorberg.rivencraft.writing.SymbolReference;
import net.dnorberg.rivencraft.writing.WritingEntry;
@@ -14,6 +15,8 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets;
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.PrefixGameTestTemplate;
@@ -90,6 +93,84 @@ public final class AgeStructureGameTests {
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) {
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
}
@@ -1,14 +1,17 @@
package net.dnorberg.rivencraft.book;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.stream.Stream;
import net.dnorberg.rivencraft.mixin.StructurePlacementAccessor;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderOwner;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
@@ -16,7 +19,11 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
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.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. */
public final class AgeStructureSelection {
@@ -98,14 +105,9 @@ public final class AgeStructureSelection {
var set = registries.lookupOrThrow(Registries.STRUCTURE_SET)
.get(ResourceKey.create(Registries.STRUCTURE_SET, setId));
if (set.isEmpty()) return "Feature " + feature + " requires missing structure set " + setId;
if (biomes == null) return null;
Set<ResourceLocation> selected = Set.copyOf(biomes.biomes());
boolean compatible = set.orElseThrow().value().structures().stream()
.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;
// Authored structures intentionally override vanilla biome eligibility. An
// incompatible selection is legal writing and receives instability instead.
return null;
}
private static boolean placedExists(RegistryAccess registries, ResourceLocation id) {
@@ -113,10 +115,40 @@ public final class AgeStructureSelection {
.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,
AgeBiomeSelection biomes, RegistryAccess registries) {
List<LegacyRankChoice.Option<ResourceLocation>> eligible = new ArrayList<>(FEATURES.stream()
.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());
Random random = new Random(ageSeed ^ 0x5354525543545552L);
int count = random.nextInt(3);
@@ -136,25 +168,31 @@ public final class AgeStructureSelection {
return 3; // Structures added after Legacy are uncommon, but still discoverable.
}
private static Set<ResourceLocation> enabledSets(List<AgeFeatureSelection.Choice> choices) {
return choices.stream().filter(choice -> feature(choice.id()) && !dungeons(choice.id()))
.map(choice -> setId(choice.id())).collect(java.util.stream.Collectors.toUnmodifiableSet());
private static Map<ResourceLocation, Integer> enabledSets(List<AgeFeatureSelection.Choice> choices) {
Map<ResourceLocation, Integer> counts = new HashMap<>();
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,
List<AgeFeatureSelection.Choice> choices) {
Set<ResourceLocation> enabled = enabledSets(choices);
Map<ResourceLocation, Integer> enabled = enabledSets(choices);
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,
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<>() {
@Override
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
@@ -164,7 +202,11 @@ public final class AgeStructureSelection {
@Override
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
@@ -177,4 +219,57 @@ public final class AgeStructureSelection {
private static boolean allowed(ResourceLocation set, Set<ResourceLocation> enabled) {
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);
}
}
}
@@ -6,9 +6,12 @@ import net.dnorberg.rivencraft.block.DecayBlock;
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.AgeRegistrySavedData;
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.resources.ResourceLocation;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
@@ -24,6 +27,17 @@ public final class RivencraftCommands {
.then(Commands.literal("age")
.then(Commands.literal("list")
.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.argument("dimension", StringArgumentType.string())
.suggests((context, builder) -> {
@@ -53,7 +67,19 @@ public final class RivencraftCommands {
.then(Commands.literal("lightning")
.executes(context -> pulseHazard(context.getSource(), true)))
.then(Commands.literal("explosion")
.executes(context -> pulseHazard(context.getSource(), false)))))));
.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) {
@@ -104,6 +130,28 @@ 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 {
@@ -138,4 +186,19 @@ public final class RivencraftCommands {
+ (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);
}
}
@@ -45,6 +45,17 @@ public final class RivencraftConfig {
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 {
ModConfigSpec.Builder builder = new ModConfigSpec.Builder();
@@ -130,6 +141,35 @@ public final class RivencraftConfig {
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();
}
@@ -179,4 +219,15 @@ public final class RivencraftConfig {
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,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();
}
@@ -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_FISSURE = register("linking.link-fissure");
public static final DeferredHolder<SoundEvent, SoundEvent> METEOR_ROAR = register("entity.meteor.roar");
private ModSounds() {
}
@@ -10,5 +10,9 @@
"linking.link-fissure": {
"category": "player",
"sounds": [{"name": "rivencraft:linking/link-fissure"}]
},
"entity.meteor.roar": {
"category": "hostile",
"sounds": [{"name": "rivencraft:entity/meteor/roar"}]
}
}
+3 -1
View File
@@ -4,7 +4,9 @@
"package": "net.dnorberg.rivencraft.mixin",
"compatibilityLevel": "JAVA_21",
"mixins": [
"AgeDungeonPlacementMixin"
"AgeDungeonPlacementMixin",
"AgeStructureBiomeMixin",
"StructurePlacementAccessor"
],
"client": [
"client.ClientLevelSoundMixin",