Compare commits

..
2 Commits
Author SHA1 Message Date
dnorberg 10a70e3b6a Complete X.1.0 milestone for Minecraft 1.21.1 and 26.3
Build and smoke / changes (push) Waiting to run
2026-11-18 22:55:03 -05:00
dnorberg 6630ed7ab1 Release machine acceleration, dropped books and baseline defaults for both tracks
Build and smoke / changes (push) Waiting to run
2026-11-18 16:43:39 -05:00
105 changed files with 3689 additions and 164 deletions

No files matched your search

+12 -8
View File
@@ -10,7 +10,7 @@ also lets you author modern terrain, biomes, structures, seasons, and celestial
bodies. It is an independently developed project, not a byte-for-byte copy of bodies. It is an independently developed project, not a byte-for-byte copy of
the 1.12.2 mod. the 1.12.2 mod.
Current releases: **1.21.1.0.6** and **26.3.0.10**, with separate Minecraft-specific JARs and saves. Current releases: **1.21.1.1.0** and **26.3.1.0**, with separate Minecraft-specific JARs and saves.
The gameplay guide below describes the **Minecraft 1.21.1 release**. The separate The gameplay guide below describes the **Minecraft 1.21.1 release**. The separate
**Minecraft 26.3 release** uses Java 25, NeoForge 26.3.0.99 and a first-party Age **Minecraft 26.3 release** uses Java 25, NeoForge 26.3.0.99 and a first-party Age
@@ -20,14 +20,17 @@ instability and Link Modifier controls. JEI, TerraBlender/Biomes O' Plenty,
Serene Seasons and Ruins remain optional. See the [26.3 guide](ports/mc263/README.md) Serene Seasons and Ruins remain optional. See the [26.3 guide](ports/mc263/README.md)
and [parity review](docs/MC263_PARITY_REVIEW.md). and [parity review](docs/MC263_PARITY_REVIEW.md).
These releases add [Native biome-family Pages](docs/NATIVE_BIOME_FAMILIES.md), These releases complete **Milestone X.1.0**. Native Nether and Native End now use
[desert vegetation](docs/DESERT_VEGETATION.md) and Number-controlled their natural fluid and sky defaults, while explicit Sky/Flooded/fluid Pages
[Static Sky resolution](docs/STATIC_SKY_RESOLUTION.md). retain control. Flat terrain uses End/Nether ground materials in those biomes,
including single-biome and mixed distributions. See [Native generation](docs/NATIVE_FLUIDS.md).
On 26.3, optional Immersive Portals Reborn or Seamless Portals provides live book On 26.3, optional Immersive Portals Reborn or Seamless Portals provides live book
and crystal portal views, including look-only exploration in the book panel. and crystal portal views, including look-only exploration in the book panel.
Install only one fork; built-in animations work without either. Install only one fork; built-in animations work without either.
Known Reborn/Seamless crashes and travel disconnects remain tracked in The 26.3 release adds targeted guards for portal-engine world-reset
acknowledgements and unavailable section rebuilds addressed in
[#118](https://git.paddedcell.org/dnorberg/rivencraft/issues/118). [#118](https://git.paddedcell.org/dnorberg/rivencraft/issues/118).
See [verification and scope](docs/PORTAL_TRANSITION_GUARDS.md).
Use matching client/server builds, keep Minecraft tracks separate and back up worlds before updating. Use matching client/server builds, keep Minecraft tracks separate and back up worlds before updating.
## Getting started ## Getting started
@@ -57,7 +60,9 @@ Stand. Crystal formations yield shards for Crystal Blocks. A connected crystal
frame with a Book Receptacle and a bound book forms a portal; frames can stand frame with a Book Receptacle and a bound book forms a portal; frames can stand
upright or lie flat. Libraries, Book Stands, and portals use Legacy-inspired upright or lie flat. Libraries, Book Stands, and portals use Legacy-inspired
assets and sounds. Handheld travel drops the used book at the departure point, assets and sounds. Handheld travel drops the used book at the departure point,
so plan how you will retrieve it. so plan how you will retrieve it. Dropped books do not pick up on contact:
right-click to open one, or shift-right-click to collect it. Ground books use
lectern-style previews with interactive exploration disabled.
## Requirements and optional integrations ## Requirements and optional integrations
@@ -132,8 +137,7 @@ The JAR is written to `build/libs/`. Development runs need the required mods;
see [GameTest guidance](docs/GAMETESTS.md) for focused archived suites. see [GameTest guidance](docs/GAMETESTS.md) for focused archived suites.
New versions prefix the Minecraft version, followed by the milestone/release New versions prefix the Minecraft version, followed by the milestone/release
slice and fixes/additional-work iteration. For example, `26.3.0.1` produces slice and fixes/additional-work iteration. For example, `26.3.0.1` produces
`rivencraft-26.3.0.1.jar`. Existing 1.21.1 artifacts keep their published legacy `rivencraft-26.3.0.1.jar`. Both supported tracks now use this scheme. See the [release workflow](docs/DUAL_VERSION_RELEASE.md).
numbers until that line's next code release. See the [release workflow](docs/DUAL_VERSION_RELEASE.md).
Rivencraft is licensed under LGPL-3.0-or-later. Legacy-derived material is Rivencraft is licensed under LGPL-3.0-or-later. Legacy-derived material is
credited in [NOTICE](NOTICE) and [asset provenance](docs/ASSET_PROVENANCE.md). credited in [NOTICE](NOTICE) and [asset provenance](docs/ASSET_PROVENANCE.md).
+11
View File
@@ -0,0 +1,11 @@
# Rivencraft 1.21.1.0.10
Intermediate development candidate; accepted changes are included in the subsequent 1.21.1.0.12 / 26.3.0.15 releases.
- Dropped Linking/Descriptive Books no longer auto-pick up on contact.
- Right-click opens the existing book GUI; its panel links while leaving the book on the ground.
- Shift-right-click picks up using normal ownership, pickup-delay and inventory checks.
- Ground-book previews follow lectern behavior: rotating views remain available, interactive exploration is disabled.
- Server validates the actual nearby entity, UUID and expected book for actions and previews.
- Clients and servers must use matching updated builds.
- Includes the prior local Writing Desk and machine-acceleration changes; 1.21.1 also includes universal open-book drop conversion.
+17
View File
@@ -0,0 +1,17 @@
# Rivencraft 1.21.1.0.12
Release for Minecraft 1.21.1 / NeoForge 21.1.264 / Java 21.
Requires Dynamic Dimensions AR Edition and Bad Packets. Update clients and servers together.
- Accelerated Pages now also speed up registered server-side machine tickers. Repeated Pages stack within independent configurable machine/candidate budgets. Normal fuel, energy and input costs apply; machines gated by global time may remain limited.
- Corrects Writing Desk selected-page placement on the red mat and adds white paper-stack geometry on the right shelf, with up to four layers matching the stored paper count.
- Dropped Linking and Descriptive Books do not auto-pick up. Right-click opens the book; shift-right-click collects it with normal ownership, delay and inventory checks. Destination-panel travel leaves the ground book in place.
- Ground-book previews follow lectern behavior: rotating previews remain available, interactive exploration is disabled. Server validation rejects stale or remote book actions.
- Zero-count Overworld materials use version-specific bundled averages, balancing valuable-block instability with void/skyblock Overworlds. Positive measured counts retain precedence.
- Missing modded ores use combined iron/deepslate iron measurements, falling back to bundled iron averages when measured iron is also absent. No extra profiling dimension is generated.
- Existing 401 Age / 500 Overworld sampling thresholds, 5% excess allowance, material weights and difficulty controls remain unchanged.
- Ordinary dropped books now consistently convert to open-book entities across player, container, station, Disarm and saved-item drop paths, preserving their book data, transform, ownership and metadata.
Player in-game checks passed for both supported versions. Focused machine probes passed 25 checks (1.21.1) / 26 (26.3), dropped-book interaction probes passed 21 / 23, and baseline policy checks passed 14 per version with source-average audits. The 1.21.1 universal-drop probe passed 62 checks. Writing Desk geometry audit passed 126 face checks. These do not claim a separate automated full client/restart matrix.
The abandoned reference-world generation probes stalled and were stopped without retry. They are superseded by bundled defaults; no generation pass is claimed for them.
+8
View File
@@ -0,0 +1,8 @@
# Rivencraft 1.21.1.0.13
Intermediate development candidate; accepted changes are included in 1.21.1.1.0 / 26.3.1.0. This candidate was not published.
- Native Nether uses lava for natural noise-terrain fluids, including Cave terrain, and disables Overworld water aquifers.
- Native End removes natural fluid filling and aquifers while retaining the chosen terrain geometry.
- Flat/Void remain flat/empty. Explicit Flooded and authored fluid features retain their own behavior.
- Updated Native-family tooltips. Existing generated chunks are not rewritten; test new Ages.
+9
View File
@@ -0,0 +1,9 @@
# Rivencraft 1.21.1.0.14
Intermediate development candidate; accepted changes are included in 1.21.1.1.0 / 26.3.1.0. This candidate was not published.
- Native Nether defaults to its Nether sky, and Native End to its End sky, unless an explicit Sky Page chooses another style.
- Written Sky Pages retain priority with authored celestials. Native/Caves keep their previous sky fallback.
- Includes Native Nether natural lava and Native End dry-terrain changes from the prior candidate.
- Flat/Void geometry and explicitly authored Flooded/fluid features retain their behavior.
- Updated tooltips. Existing generated chunks are not rewritten.
+10
View File
@@ -0,0 +1,10 @@
# Rivencraft 1.21.1.0.15
Intermediate development candidate; accepted changes are included in 1.21.1.1.0 / 26.3.1.0. This candidate was not published.
- Flat End biomes now use End Stone instead of grass/dirt.
- Flat Nether biomes use Nether ground, including Crimson/Warped Nylium, Soul Sand/Soul Soil and Basalt/Blackstone for the corresponding vanilla biomes.
- Supports single-biome plans and local materials in mixed distributions, including tagged End and TerraBlender-region Nether classification.
- Base-column queries match placed materials. Bedrock, air, height, authored features and fluids are preserved.
- Includes the earlier Native Nether lava / Native End dry generation and default sky improvements.
- Existing generated chunks are not rewritten; use fresh Ages for visual checks.
+11
View File
@@ -0,0 +1,11 @@
# Rivencraft 1.21.1.0.7
Intermediate development candidate; accepted changes are included in the subsequent 1.21.1.0.12 / 26.3.0.15 releases.
- Accelerated Pages now give ticking server machines extra registered ticker calls.
- Repeated Pages stack within separate configurable machine and candidate budgets.
- Fair allocation, loaded/ticking chunk checks, world-border/removal checks and tick freeze remain in effect.
- No force-loading or entity acceleration; normal Ages and the Overworld are unchanged.
- Existing Accelerated Ages gain the behavior without rebinding; saved Page counts are unchanged.
- Random-block acceleration retains its own independent budget.
- Machine fuel, energy and input costs remain normal; global-time-gated machines may not scale linearly.
+8
View File
@@ -0,0 +1,8 @@
# Rivencraft 1.21.1.0.8
Intermediate development candidate; accepted changes are included in the subsequent 1.21.1.0.12 / 26.3.0.15 releases.
- Corrects Writing Desk selected-page height and centers it on the red writing mat.
- Adds shared white paper-stack geometry on the right shelf, slightly forward, using Legacy's existing desk texture.
- Paper count controls up to four staggered layers; attachments follow all desk facings.
- Includes the player-validated Accelerated machine support from issue #112.
+11
View File
@@ -0,0 +1,11 @@
# Rivencraft 1.21.1.0.9
Intermediate development candidate; accepted changes are included in the subsequent 1.21.1.0.12 / 26.3.0.15 releases.
- All ordinary dropped Linking/Descriptive Books now convert to open-book entities, including unwritten books and saved item drops loaded from disk.
- Central queued conversion covers player, container, stand, station and Disarm paths.
- Preserves stack components/count, toss position/motion/rotation, pickup delay, ownership and serializable metadata; retains existing open-book lifetime/weather behavior.
- Canceled replacement spawning keeps the original; custom books and non-book items are skipped.
- Keeps the existing custom pickup-particle copy fix.
- Includes the previously player-validated Accelerated machines and Writing Desk model changes.
- Minecraft 26.3 already has this drop behavior and is unchanged by this slice.
+16
View File
@@ -0,0 +1,16 @@
# Rivencraft 1.21.1.1.0
Completes Milestone X.1.0 for Minecraft 1.21.1 / NeoForge 21.1.264 / Java 21.
Requires Dynamic Dimensions AR Edition and Bad Packets. Use matching client/server builds and the JAR for your Minecraft version.
- Native Nether uses lava for natural noise-terrain fluids, including Cave terrain, and disables Overworld water aquifers.
- Native End removes natural fluid filling and aquifers while preserving the chosen terrain geometry.
- Native Nether and Native End default to their corresponding skies when no Sky Page is written. Explicit Sky Pages retain priority, including with authored celestials.
- Flat End biomes use End Stone instead of grass/dirt. Flat Nether biomes use Nether ground, including Crimson/Warped Nylium, Soul Sand/Soul Soil and Basalt/Blackstone for the corresponding vanilla biomes.
- Corrects single-biome Flat generation and local materials across mixed distributions. Tagged End biomes and TerraBlender-region Nether classification are recognized; other recognized Nether biomes use the Netherrack fallback.
- Base-column queries match placed Flat materials. Bedrock, air, height, authored features and explicit Flooded/fluid features retain their behavior.
- Updated Native-family tooltips. Existing generated chunks are not rewritten.
Player in-game checks passed. Sequential Native-generation probes passed **219 checks on 1.21.1 / 213 on 26.3**, including actual Flat block placement, mixed distributions, generator codecs, natural-fluid settings and sky precedence. Temporary worlds were removed; no probe stalled.
Versioning is now **Minecraft version.1.0**: milestone/release slice 1, iteration 0. Both Minecraft tracks retain separate builds and saves.
+81
View File
@@ -0,0 +1,81 @@
# Accelerated server machines — issue #112
Introduced in development candidates **1.21.1.0.7** and **26.3.0.11**.
Player in-game checks passed; included in releases **1.21.1.0.12** and **26.3.0.15**.
## Behavior
Each authored Accelerated Page requests one extra tick per server-side ticking
block entity in that Age, in addition to its normal tick. One Page targets 2x
normal ticker calls; four target 5x, before budgets. Identical Pages stack.
The normal registered bound ticker is reused, including optional modded machines.
Its own state validity, chunk-ticking and NeoForge error-handling rules remain active.
Entities, scheduled block ticks and the global clock are not accelerated.
Extra work respects removed/rebound tickers, loaded chunks, normal block-ticking
range, world border and server tick freeze. No new chunk tickets are created.
Machines in normally ticking force-loaded Age chunks may run without a nearby
player. Random-block acceleration remains restricted to its existing player-nearby
chunks. The Overworld and Ages without Accelerated Pages receive no extra work.
The existing authored-plan/page-count save data is unchanged. Existing Accelerated
Ages gain machine ticking after installing this build; no new Age is required.
Page counts persist through the existing save/reload/reseed paths. Work cursors
are transient and reset on reload; they do not alter the saved Page count.
## Independent budgets
Both targets expose these settings under accelerated_age:
| Setting | Default | Meaning |
| --- | --- | --- |
| max_machine_candidates_per_tick | 1024 | Maximum registered ticker entries inspected in one Age tick, rotating across the list. |
| max_machine_ticks_per_tick | 4096 | Maximum extra machine ticker calls per Age tick. Zero disables only machines. |
| max_random_tick_attempts_per_tick | 16384 | Existing random block samples; zero disables only random-block acceleration. |
| max_loaded_chunks | 8 | Existing random-block chunk cap; not a machine chunk-loading setting. |
The selected machine window is snapshotted before executing tickers. Work is
distributed round-robin across eligible machines rather than letting the first
machine use every repeated Page. Removal/replacement/freeze is checked again
before each call. Large installations can hit the cap and run slower than the
requested multiplier. Both machine settings have an upper bound of 65536.
## Compatibility limits
Additional ticker calls also consume normal fuel, energy, inputs and durability.
The effect does not synthesize power or bypass recipe requirements. Machines that
compare global game time, use once-per-tick guards, async jobs or scheduled work
may remain limited to their ordinary rate. Transport may bottleneck independently.
No optional machine mod is required or hard-coded.
## Validation and manual checks
Run sequentially:
python3 scripts/regression_machine112.py mc1211
python3 scripts/regression_machine112.py mc263
These use new disposable worlds and remove them on pass or fail. A 60-second
stall stops the run and hands remaining checks to the player, without a retry.
Fixtures remain outside shipping artifacts.
In-game checks, on each target:
1. In Survival, compare fuelled furnaces in Ages with zero, one and four Pages.
Smelting should be about 10, 5 and 2 seconds per ordinary 200-tick recipe,
before machine budgets; use the same input/fuel and avoid other speed effects.
2. Repeat with a ticking modded machine (Create on 1.21.1 if available). Record
the machine type if it does not accelerate; game-time guards may be a limit.
3. Remove and replace a working machine, leave its chunks, return, then restart.
No ghost ticking or force-loading should occur. Existing Page counts remain.
4. Confirm an ordinary Overworld furnace stays at its normal rate and random-tick
crops still accelerate in an Accelerated Age.
5. With two players in the same Age, confirm the effect is not doubled by player
count. Test tick freeze; machines must stop along with the normal world.
Automated probes test registered vanilla furnace recipes, zero/one/repeated Pages,
freeze, removal/replacement, nonloaded/border guards, a custom registered ticker,
Overworld event exclusion, bounded fair work, and saved Page-count decoding.
They do not constitute a real modded-machine or two-client/restart pass.
### Automated result
Sequential probes passed: **25 checks on 1.21.1**, **26 checks on 26.3**. The freeze check initially exposed a cached runsNormally value immediately after setFrozen; the adapter now checks both the current freeze flag and the tick manager's run state. No test stalled. Both temporary worlds were removed. Player in-game checks subsequently passed; no independent real-mod-machine or two-client/restart result is claimed.
+74
View File
@@ -0,0 +1,74 @@
# Block-instability baselines
Issue #115 uses version-specific bundled averages when an individual Overworld
material has a measured count of zero. It does not create a reference dimension.
## Defaults
The defaults are averaged from the developer's existing Overworld profiles:
987 chunks for Minecraft 1.21.1 and 1,024 chunks for Minecraft 26.3.
Every sampled chunk contributes to the denominator, including chunks without
that block. Ore and deepslate variants retain separate averages.
The bundled JSON files are:
- 1.21.1: src/main/resources/assets/rivencraft/instability/default_block_baseline.json
- 26.3: ports/mc263/src/main/resources/assets/rivencraft/instability/default_block_baseline.json
Each records the source sample count and source-export SHA-256. They contain no
save path, chunk coordinates, or dependency on the developer's save. Rebuild an
average with scripts/generate_block_baseline.py SOURCE_JSON VERSION OUTPUT_JSON.
## Scoring
For each watched block:
1. A positive measured Overworld count uses its actual count divided by sampled chunks.
2. A modded ore with zero measured occurrences uses the combined measured
iron_ore and deepslate_iron_ore average. If that combined count is zero,
it uses the combined bundled iron average. This takes precedence over any
modded ore entry in the bundled JSON.
3. Other zero-count materials use their own bundled average, or zero if absent.
The combined bundled iron average is 89.96656534954407 blocks/chunk for 1.21.1
and 76.5361328125 blocks/chunk for 26.3. Installed mods remain optional:
unused resource IDs do not register blocks or make a mod required.
The existing readiness requirements remain: at least 401 sampled Age chunks
and 500 sampled Overworld chunks. The 5% excess allowance, material weights,
difficulty multipliers and score cap are unchanged. The baseline is selected
per material, so one absent ore cannot replace all measured Overworld results.
Storage blocks and fluids do not receive the modded-ore iron substitution.
They use their own measured/default counts.
Existing saved profiles remain usable. The abandoned reference-source flag is
no longer written or read. Existing Ages use this calculation without rebinding.
## Validation
The former reference-world generation probes stalled on both versions and were
stopped without retry. That implementation and its temporary fixture were
removed. Their logs remain under build/verification/baseline115/.
The replacement is checked without starting a server: regenerate/compare the
bundled averages and exercise the production shared Java policy with each
version's actual resource. Production builds check both Minecraft integrations.
Player checks:
- In a void/skyblock or flat Overworld, enter an Age with valuable generated
blocks. Allow the Age and Overworld profiles to reach the existing thresholds.
Confirm excess materials produce block instability rather than every missing
Overworld ore being compared against zero.
- A modded ore absent from the Overworld should use iron, even if the modded
ore has an entry in the bundled defaults.
- In a normal Overworld, measured positive counts should still take priority.
- Reopen the save and verify profiles and scores persist normally.
Inside the Age, use /rivencraft age instability on 1.21.1 or
/rivencraft_port instability status on 26.3 to inspect readiness and scoring;
instability scores remain absent from the book GUI. The player reported in-game acceptance on both versions before publication.
This is manual acceptance, not a passing result from the abandoned reference-world probes.
Offline verification: both source-average audits passed; the production shared
Java policy passed 14 checks per version. Both production builds passed.
+126
View File
@@ -0,0 +1,126 @@
# Open-book drops — issue #114
Initial conversion slice: local **1.21.1.0.9**, followed by the interaction candidates below.
The existing 26.3 conversion was already player-validated and remains unchanged
in **26.3.0.12**. That initial conversion slice changed only 1.21.1; the interaction follow-up below changes both versions.
## Central conversion
Both targets listen for ordinary ItemEntity joins on the server at LOWEST
priority. Linking and Descriptive Books convert regardless of binding state.
Pages, Notebooks, folders, portfolios and sealed collections retain ordinary
item behavior. Existing DroppedBookEntity instances are skipped.
A queued server task waits until the original join callback completes. It
rechecks the level identity, entity registration/removal and item type, then
creates a custom book. The source is discarded only if addFreshEntity accepts
the replacement. A canceled source cannot create a ghost replacement; canceled
replacement spawning leaves the source intact. Another join/reload may retry.
There is no per-tick scan, force-loading, or conversion recursion.
This covers Q/Ctrl-Q and inventory tosses, container/loot/dispenser-style item
spawns, stand/receptacle contents, full-inventory deliveries, death inventory
drops, and Disarm. Existing ordinary book entities loaded from disk take the
same join path. Books created directly by handheld travel already use the
custom type and retain their existing departure placement.
## State and lifetime
fromDrop uses Minecraft's native restoreFrom NBT path, copies the full stack and
gives the replacement a fresh UUID while the source is still registered. On 1.21.1 the live transform/motion is copied explicitly after NBT loading, which otherwise clamps very high velocities.
Position, facing, velocity, pickup delay, owner/thrower, persistent data and
serializable entity metadata are retained. Arbitrary tosses do not get the
handheld departure constructor's extra height or zero velocity.
The replacement adopts open-book lifetime (unlimited ordinary ItemEntity age)
and the existing slow book decay and rain/water damage. The original ordinary
despawn age is intentionally not retained. Normal book entity save/load retains
its own decay clock thereafter.
The 1.21.1 custom copy() override remains intact so client pickup particles keep
the custom renderer type.
## Validation
Run only the changed target:
python3 scripts/regression_drop114.py mc1211
A disposable server probe exercises native metadata/component copying, bound and
unwritten variants, direct joins and NBT-loaded item joins, actual player toss,
container drop, stand break/full inventory retrieval, station break, Disarm,
inventory death-path drops, already-custom skip, non-book items, cancellation and
retry, custom NBT round trip and pickup-copy entity type. Temporary worlds and
fixture outputs are removed on pass or fail. Stop and hand off a stalled probe.
Player checks on 1.21.1:
- Q/Ctrl-Q and inventory/cursor tosses for Linking/Descriptive Books, bound and
unwritten. Verify open-book orientation, throw motion, pickup delay, name,
destination and modifiers.
- Break a loaded stand; expect one lectern and exactly one open book. Shift-remove
with a full inventory. Repeat with a receptacle and Link Modifier station.
- Test death and Disarm drops and handheld travel. Full-inventory Return Link
delivery can be checked if automatic Return Links are explicitly enabled.
- Leave/reload the chunk and restart with books on the ground. Pick them up and
verify no client pickup-particle crash. Pages/collections stay ordinary items.
An NBT round trip is not a full server restart, and FakePlayer drop paths do not
replace real GUI, death, portal or client rendering acceptance.
## Automated result
The isolated 1.21.1 server probe passed **62 checks**. High-velocity native NBT loading was accounted for by explicitly retaining live transform/motion. No test stalled; the disposable world and fixture build outputs were deleted. The production build passes. No new 26.3 code or tests were run for this root-only change. Player acceptance was subsequently reported; included in 1.21.1.0.12.
## Legacy-style interaction follow-up
Candidates **1.21.1.0.10** and **26.3.0.13** add:
- Walking over a custom dropped book never picks it up.
- Right-click opens the existing Linking/Descriptive Book GUI. Clicking its
destination panel uses normal linking rules and leaves the same book in place.
- Shift-right-click explicitly attempts normal item pickup, respecting ownership,
pickup delay, inventory capacity and NeoForge pickup hooks. A full inventory
leaves the book in the world. This uses inventory pickup rather than Legacy's
special empty-hand assignment.
- Ground books use the lectern-style view: rotating destination previews are
supported, **interactive exploration is disabled**. GUI input closes if the
entity disappears or moves out of reach.
- Unwritten dropped books retain their naming/binding screens. The server
resolves and updates the actual nearby entity, never a held item.
- ID + UUID + expected full stack + alive/range checks reject stale, replaced,
picked-up or remote source actions. Normal travel rules and 26.3 catalog
acknowledgement remain in effect. Preview leases on 26.3 also validate the
dropped entity and distinguish it from hands/stands.
Reviewed local Legacy EntityLinkbook interaction bytecode. Legacy uses sneaking
and an empty hand for direct hand pickup, otherwise opens BOOK_ENTITY. Rivencraft
keeps the requested gesture but uses existing pickup permissions/hooks.
New dropped-action/open-screen payloads reuse existing screens and binding/travel
helpers. 1.21.1 networking protocol is 20; 26.3 book-network registration is 2.
The 26.3 preview request adds an optional dropped-entity UUID with a default
constructor for existing hand/stand callers. Update clients and servers together.
Sequential isolated interaction probes exercise no-contact pickup, normal open,
explicit pickup with owner/delay/full-inventory checks, stale/forged/remote source
rejection, actual binding helper dispatch, teleport request dispatch without
duplicating/removing the ground book, and packet codec round trips. The fixture
captures teleport requests because FakePlayer's connection intentionally ignores
teleports. It does not establish real client rendering or dimension transition.
The 26.3 fixture acknowledges its catalog explicitly; there is no production bypass.
Player checks on both versions:
1. Drop bound Linking and Descriptive Books. Walk over each: no pickup.
2. Right-click: normal book GUI, rotating preview when its optional renderer is
available, and no usable interactive-view control. Click the destination panel
to travel. Return and verify the same book remains.
3. Shift-right-click to collect, including a full inventory and a fresh toss's
pickup delay. Confirm contents/title/modifiers remain intact.
4. Try unwritten books, input names/bind and reopen. Check changing/removing the
ground book while its GUI is open closes it safely.
5. Check reload/restart, ordinary held/stand book GUIs and optional live previews.
### Follow-up automated result
Interaction probes passed sequentially: **21 checks on 1.21.1, 23 on 26.3**. No stall occurred; temporary worlds were deleted. Dedicated-server startup caught and corrected eager client-screen class loading on 1.21.1; client handling now uses a deferred lambda. The fixtures capture teleport dispatch and simulate the 26.3 catalog acknowledgement; the player subsequently reported in-game acceptance on both versions. No independent automated full client/restart matrix is claimed. Logs remain in build/verification/drop_interactions.
The complete interaction update is included in releases **1.21.1.0.12** and **26.3.0.15**.
+14
View File
@@ -115,3 +115,17 @@ above remains historical; unchanged earlier artifacts are not relabeled.
## 2026-11-17 release update ## 2026-11-17 release update
Player-approved 1.21.1.0.6 and 26.3.0.10 collect #108 desert vegetation, #109 Static Sky resolution and #111 Native biome families. The 26.3 release also includes #117 optional Seamless live rendering. #118 remains open for Reborn/Seamless failures, including the recovered caves_on_top acknowledgement disconnect. Both JARs retain their player-tested hashes. Player-approved 1.21.1.0.6 and 26.3.0.10 collect #108 desert vegetation, #109 Static Sky resolution and #111 Native biome families. The 26.3 release also includes #117 optional Seamless live rendering. #118 remains open for Reborn/Seamless failures, including the recovered caves_on_top acknowledgement disconnect. Both JARs retain their player-tested hashes.
## Completed Milestone X.1.0 releases (2026-11-18)
Versions **1.21.1.1.0** and **26.3.1.0** mark completion of the X.1.0 milestone.
The Minecraft version remains the prefix; the milestone/release slice is now 1
and the fix/additional-work counter resets to 0. Later work increments that
last counter, for example 26.3.1.1. Both use ordinary release channels.
Native fluid/sky/Flat-material changes passed player checks on both tracks;
the final 26.3 transition guards also passed player acceptance. Historical
open-issue notes above describe older releases; #118 and #119 are now complete.
Automated evidence remains bounded: 219/213 Native checks and 47 isolated
26.3 client-guard checks, plus the player reports.
+10
View File
@@ -64,3 +64,13 @@ consolidation; issue #84 records the final milestone acceptance. See the
[M7 acceptance](MILESTONE_7_ACCEPTANCE.md), [M7 Legacy audit](LEGACY_M7_AUDIT.md), [M7 acceptance](MILESTONE_7_ACCEPTANCE.md), [M7 Legacy audit](LEGACY_M7_AUDIT.md),
[M7 regression matrix](MILESTONE_7_REGRESSION.md), and [M7 regression matrix](MILESTONE_7_REGRESSION.md), and
[M7 compatibility review](MILESTONE_7_COMPATIBILITY_REVIEW.md). [M7 compatibility review](MILESTONE_7_COMPATIBILITY_REVIEW.md).
## Version X.1.0 — complete (2026-11-18)
The post-port improvement milestone is complete in **1.21.1.1.0** and **26.3.1.0**.
The final issues were #119 (Native Nether/End fluids, sky defaults and Flat
ground materials) and #118 (26.3 portal transition guards), both accepted by the
player. See [Native generation](NATIVE_FLUIDS.md) and
[portal guard evidence](PORTAL_TRANSITION_GUARDS.md). Each Minecraft track keeps
its own artifact, dependencies and saves.
+11 -4
View File
@@ -13,8 +13,9 @@ Release builds: **1.21.1.0.6** and **26.3.0.10**. Player in-game validation pass
The three explicit family controllers work with Standard, Amplified, Island, The three explicit family controllers work with Standard, Amplified, Island,
Cave, Flat and Void terrain. The **Terrain Page still controls geometry**. Cave, Flat and Void terrain. The **Terrain Page still controls geometry**.
Void stays empty; its biomes can affect weather and seasons. These controllers Void stays empty; its biomes can affect weather and seasons. In the original family release these controllers did not select a sky style.
do not select a sky style, dimension type or season. Releases 1.21.1.1.0 / 26.3.1.0 add Nether/End sky defaults
unless a Sky Page is explicitly written. They do not select a season.
The player chose **seeded regional layout including modded biomes** for Native The player chose **seeded regional layout including modded biomes** for Native
Nether/End, rather than vanilla climate or End-island placement. The family Nether/End, rather than vanilla climate or End-island placement. The family
@@ -77,8 +78,8 @@ On 26.3, authored noise-terrain generation can now construct a vanilla noise
baseline when the primary Overworld is Flat/custom rather than a Noise generator. baseline when the primary Overworld is Flat/custom rather than a Noise generator.
This allows the independent Native-family/terrain pairing in that setup instead This allows the independent Native-family/terrain pairing in that setup instead
of failing with “Overworld generator cannot accept authored noise settings.” of failing with “Overworld generator cannot accept authored noise settings.”
The existing path for an ordinary noise Overworld is unchanged. Issue #115's The existing path for an ordinary noise Overworld is unchanged. The later material-abundance baseline work is documented separately in
separate material-abundance baseline work is not completed by this fix. [block baselines](BLOCK_BASELINE.md).
## Creative, JEI and loot policy ## Creative, JEI and loot policy
@@ -137,3 +138,9 @@ BOP/TerraBlender**. Coverage includes:
5. Verify all three Pages appear under biome generation in Creative and JEI. 5. Verify all three Pages appear under biome generation in Creative and JEI.
6. Reopen an older Native Cave Age if available. Its saved mixed pool is kept; 6. Reopen an older Native Cave Age if available. Its saved mixed pool is kept;
create a new Age to test the new default rather than expecting migration. create a new Age to test the new default rather than expecting migration.
## Natural fluids — issue #119
Releases 1.21.1.1.0 / 26.3.1.0 apply lava to Native Nether
natural fluids and remove Native End natural water. Explicit Flooded/fluid
features remain separate. See [Native fluid rules](NATIVE_FLUIDS.md).
+139
View File
@@ -0,0 +1,139 @@
# Native terrain fluids — issue #119
Released in **1.21.1.1.0** and **26.3.1.0**. Player in-game checks passed on both; issue #119 closed.
## Behavior
Native Nether replaces the noise terrain's default fluid with lava and disables
Overworld water aquifers. This includes Cave terrain, which keeps its preset
fluid height for Native Nether instead of the ordinary dry-Cave override.
Native End uses air as its default fluid, disables aquifers, and places the
fluid cutoff below the terrain's minimum Y. Vanilla's fluid picker can otherwise
introduce low-level lava even after changing the default fluid to air.
Terrain still determines geometry and the ordinary fluid cutoff for Nether:
Standard, Amplified, Island and Cave retain their noise shape and vertical
range. This does not raise Island terrain's below-world cutoff into an ocean.
Flat and Void retain their existing empty/flat generation; the Native Page does
not add an ocean to either.
The change follows the frozen Native family choice, including recognized
modded members. It does not infer a family merely from a particular biome
appearing in a custom Single/Tiled/region distribution. Native, Native Caves,
and explicitly authored non-Native biome distributions retain existing rules.
The fluid rule does not change season, biome-pool or material-rule selection.
Native-family sky defaults are described below.
## Native sky defaults
When no explicit Sky Page is active, Native Nether defaults to the Nether sky
and Native End defaults to the End sky. This applies independently of terrain.
A written Overworld, Nether, End or Static Sky Page takes precedence, including
when Sun/Moon Pages are also present. Celestials alone do not override the
Native-family default. Color/celestial authoring remains intact.
Native and Native Caves keep their previous fallback selection. 1.21.1 derives
the default from the saved family plan for server effects and the synchronized
sky profile. 26.3 freezes the resolved style through its existing Age sky save
and dimension-type variant, rather than consulting mutable worldgen state.
## Explicit authoring and saves
Flooded still deliberately adds water at the authored/default height after
terrain and decorations. Explicit fluid features retain their selected fluid.
Thus Native End + Flooded intentionally has water, and Native Nether + Flooded
is not an implicit lava Flooded Page. These are separate authoring instructions.
The Native family already persists in the biome plan. The effective noise fluid,
aquifer policy and cutoff are included in the generator's existing codec.
No new Page or config is introduced. Tooltips explain the natural-fluid rules.
Existing generated chunks are not rewritten. Use newly created Ages for visual
validation; older Native-family Ages may use the new fluid rules in future chunks
when their generator is reconstructed.
## Focused verification
Run sequentially:
python3 scripts/regression_native119.py mc1211
python3 scripts/regression_native119.py mc263
Each run creates one temporary server world and isolated fixture output, holding
the host-wide server lock. It removes the world on pass/fail; if a run stalls
after 60 seconds, it stops and hands the remaining check to the player without
retrying. Logs remain under build/verification/native119/.
The fixture builds real authored generators for all six terrain choices and
three explicit Native families, checks generator codec reload and the actual
vanilla fluid picker over the full vertical range. Flat/Void must remain flat.
This establishes settings and fluid-picker behavior, not completed decorated
terrain, modded lake behavior, or visual/client acceptance.
## Player checks — both versions
1. Create Link Panel → Standard → Native Nether. Explore new terrain:
natural oceans/aquifers should use lava rather than water.
2. Repeat with Cave → Native Nether: any natural fluid is lava.
3. Create Standard → Native End, then Cave → Native End. Natural terrain should
be dry; explore new chunks to check for unexpected water.
4. Check Native Caves remains dry on Cave, and ordinary Standard + Native still
generates normal water. Flat/Void should not acquire new natural oceans.
5. Test Native End + Flooded and Native Nether + Flooded to confirm explicit
water authoring still works. Fluid-feature Pages keep their chosen fluid.
6. Native Nether/End without a Sky Page should show the corresponding sky.
Add Overworld Sky or Static Sky and verify the written Sky wins; repeat with
a Sun Page to verify celestial authoring does not change that priority.
7. Save/reopen, revisit, and check sky and new chunks retain the intended behavior.
The prior fluid-only candidates passed 76 focused checks per version.
The sky-default extension adds checks for defaults, explicit precedence with
celestials, dimension effects and saved/serialized styles. Player visual checks
were subsequently accepted by the player for the combined candidates.
Combined fluid/sky results: **134 checks on 1.21.1, 122 on 26.3**, run sequentially.
Both production builds and JAR audits passed; both Dev candidates installed.
Temporary worlds removed; no stalls. Player visual acceptance subsequently passed.
## Flat biome materials
Flat generation previously wrote the vanilla grass/dirt layers directly without
running noise terrain's biome surface rules. Both targets now choose materials
from the biome at each column/layer. 26.3 also routes single End/Nether biome
plans through the custom flat generator, rather than the vanilla flat bypass.
| Biome | Flat cap | Flat soil |
| --- | --- | --- |
| End family | End Stone | End Stone |
| Nether Wastes / other recognized Nether | Netherrack | Netherrack |
| Crimson Forest | Crimson Nylium | Netherrack |
| Warped Forest | Warped Nylium | Netherrack |
| Soul Sand Valley | Soul Sand | Soul Soil |
| Basalt Deltas | Basalt | Blackstone |
| Other biomes | Existing Flat layers | Existing Flat layers |
This is a biome-aware Flat material preset, not Nether noise geometry or a
reproduction of every mod's custom surface decorator. Tagged End biomes use End
Stone; tagged or TerraBlender-region Nether biomes use the Nether fallback.
Vanilla family IDs remain recognized even when broad tags are missing.
TerraBlender-region IDs are captured into generator state and codec; no optional
API call or mutable Age data is read per generated block.
Bedrock, air, terrain height and non-base layer blocks remain intact. Materials
are chosen during base filling, before authored features and biome decoration,
so a rock/tendril material is not recolored by a later broad cleanup scan.
The base-column query uses the same material decision as block placement.
Mixed End/Nether/Overworld distributions retain their own materials locally.
Visual checks: create fresh Flat + Native End, Flat + Native Nether, and Flat
with a single End/Nether biome. Check the surface and exposed dirt layers at
edges; also test a mixed distribution and an ordinary Plains Flat Age. Authored
material features and Flooded should retain their own blocks/fluids. Existing
chunks are not changed.
Latest combined checks (including actual Flat block placement and mixed columns):
**219 on 1.21.1 / 213 on 26.3**. They passed sequentially without stalls;
temporary worlds were removed. The player subsequently reported in-game acceptance. Optional mod-specific
custom surface decorators remain outside this Flat material preset.
+97
View File
@@ -0,0 +1,97 @@
# Portal transition guards — issue #118
Released with **26.3.1.0**; NeoForge 26.3.0.99 / Java 25.
Only 26.3 client code changed for issue #118; the 1.21.1.1.0 release includes
the separately accepted Native-generation updates.
## Evidence and attribution
The installed Seamless 1.0.0 and Reborn 7.0.12 bytecode has the same unchecked
redirectHandleBlockChangedAck path: getClientWorlds asserts that the portal
engine is initialized, then iterates its worlds. Its own world-replacement
cleanup can leave initialization false until a later initialization point.
Rivencraft does not call that cleanup. Its existing workaround was Reborn-only.
Two newer Seamless reports (2026-11-18 21:51:41 and 22:05:32) still show this
same assertion. That establishes an ongoing compatibility gap, not an Age
generation exception. Local reports are retained outside the repository.
The Reborn exploration crash dereferenced a null RenderSection in its wrapped
compileAsync path. Both vanilla 26.3 and NeoForge's patched compileSections
loop retrieve the current section for an extracted job and dereference it
without a null check. ViewArea can return null for a section outside its current
storage. Reborn wraps the compile call; Seamless modifies the priority decision
instead. The observed origin of the stale job is still not conclusively
attributed to vanilla, the portal engine, or their interaction. No independent
full-client reproduction without Rivencraft is claimed.
The [Seamless project](https://www.curseforge.com/minecraft/mc-mods/immersive-portal)
links to [its upstream tracker](https://github.com/fmpapierz/SeamlessPortals/issues).
No new report has been submitted by this change. An unrelated report there does
not establish a match to these failure paths.
## Acknowledgement guard
ImmersiveBlockAckMixin runs on the client/game thread, only when either supported
fork is installed. During an uninitialized-world-map interval, it acknowledges
the packet listener's own ClientLevel directly and skips the failing multiworld
redirect. With an initialized map the fork handles the packet normally,
including remote worlds. Off-thread packets retain vanilla scheduling. With no
packet world, there is no valid local prediction state to acknowledge.
The helper and mixin were renamed from their old Reborn-only names. Optional
portal API classes remain behind the installed-engine check; no new required
dependency or configuration switch is introduced.
## Unavailable section jobs
At compileSections entry, when a supported fork is present, only jobs whose
section is absent from the current ViewArea are removed. The check uses an
invoker for the same section lookup vanilla performs later.
Every valid job retains its object identity, order, region, additional renderers
and dirty state. The whole render pass is not canceled. There is no try/catch
around rendering, permanent coordinate blacklist, terrain scan or new chunk
loading. A newly allocated section can be extracted and compiled normally.
Other exceptions propagate. This is a targeted mitigation for the observed
null receiver, not a claim to fix every renderer or world-ownership issue.
## Verification
./gradlew -p ports/mc263 build
python3 scripts/regression_client118.py
The isolated script passed **47 checks** using production guard/mixin bytecode.
It extracts and runs the acknowledgement redirect bytecode from both installed
forks, reproducing the old uninitialized-map assertion before testing guarded
delivery. Coverage includes warm/cold maps, exact-once local acknowledgement,
normal remote acknowledgement, off-thread noninterference, no-fork bypass,
missing packet world, stale/valid renderer jobs, retained job identity/payload
and dirty state, newly available sections, null view area and unrelated errors.
Minecraft lifecycle and renderer types in this script are small isolated stubs.
It starts no Minecraft client, GPU, server or test world. It does not prove
runtime Mixin application, live portal graphics or end-to-end network timing.
No stall occurred and no stalled server probe was retried. Temporary test
outputs are deleted; result retained in build/verification/issue118/guards.txt.
## Player acceptance checklist
Test each installed renderer separately; never enable both together.
1. Start with Seamless and confirm the client loads. Create/open/close a new Age
book, travel repeatedly and return. Include normal block placement/breaking
around travel to exercise prediction acknowledgements.
2. Open live book previews, enter/exit look-only exploration, close/reopen and
use a live crystal portal. Verify the view stays correct and travel works.
3. Explore across chunks, rebuild terrain (F3+A), and change render distance.
Confirm no section crash and that terrain continues rebuilding visibly.
4. Disconnect/rejoin and fully restart; repeat travel to existing/new Ages.
5. Repeat with Reborn alone, particularly sustained exploration/rebuilding.
6. Optionally check animated fallback with no portal mod. Neither renderer is
required for normal Rivencraft travel.
The user reported in-game pass and authorized publication after testing the
26.3.0.19 candidate. Issue #118 and Milestone X.1.0 are complete. This records
player acceptance; no independent exhaustive GPU/network/renderer matrix or
standalone external-fork reproduction is claimed.
+3 -1
View File
@@ -29,6 +29,8 @@ See the [installation guide](https://git.paddedcell.org/dnorberg/rivencraft/wiki
- Preview destinations with the built-in Legacy-style animation or an optional rendering integration for your Minecraft version. - Preview destinations with the built-in Legacy-style animation or an optional rendering integration for your Minecraft version.
- Set an Age’s water level with Flooded and Number Pages. - Set an Age’s water level with Flooded and Number Pages.
- Select Native Caves, Nether or End biome pools independently of terrain, grow desert vegetation with Trees/Huge Trees/Flowers, and control Static Sky resolution with Number Pages. - Select Native Caves, Nether or End biome pools independently of terrain, grow desert vegetation with Trees/Huge Trees/Flowers, and control Static Sky resolution with Number Pages.
- Native Nether defaults to lava and Nether sky; Native End to dry terrain and End sky. Explicit Sky and Flooded Pages retain control. Flat terrain uses appropriate End/Nether ground in those biomes.
- Right-click dropped open books to read/link, or shift-right-click to collect; walking over them does not pick them up.
## Getting started ## Getting started
@@ -46,7 +48,7 @@ Optional integrations include **JEI**, **TerraBlender** and compatible biome mod
Destination previews depend on the Minecraft version: Destination previews depend on the Minecraft version:
- **1.21.1:** optional Create/Ponder snapshots or Immersive Portals live views. - **1.21.1:** optional Create/Ponder snapshots or Immersive Portals live views.
- **26.3:** optional **Immersive Portals Reborn or Seamless Portals** live book and crystal-portal views, including look-only exploration inside the book panel. Install only one fork per instance. **Known Reborn/Seamless crashes and travel disconnects remain under investigation:** [issue #118](https://git.paddedcell.org/dnorberg/rivencraft/issues/118). - **26.3:** optional **Immersive Portals Reborn or Seamless Portals** live book and crystal-portal views, including look-only exploration inside the book panel. Install only one fork per instance. The 26.3.1.0 release includes player-accepted guards for portal world-reset acknowledgements and unavailable section rebuilds; see [scope and verification](https://git.paddedcell.org/dnorberg/rivencraft/src/branch/main/docs/PORTAL_TRANSITION_GUARDS.md).
Built-in animated previews remain available without a portal renderer. Create/Ponder scenes are not currently included in the 26.3 build. Built-in animated previews remain available without a portal renderer. Create/Ponder scenes are not currently included in the 26.3 build.
+7
View File
@@ -19,3 +19,10 @@ former behavior or loader version.
audits are intentionally retained for source attribution and migration audits are intentionally retained for source attribution and migration
history; these three entry points replace the former practice of treating history; these three entry points replace the former practice of treating
every dated task note as a current installation guide. every dated task note as a current installation guide.
## Current cross-version updates
- [Accelerated machines](ACCELERATED_MACHINES.md)
- [Writing Desk display model](WRITING_DESK_MODEL.md)
- [Dropped books](DROPPED_BOOKS.md)
- [Void/skyblock block baselines](BLOCK_BASELINE.md)
+12 -3
View File
@@ -1,8 +1,8 @@
# Optional Seamless Portals integration — issue #117 # Optional Seamless Portals integration — issue #117
Local candidate **26.3.0.9**, Minecraft 26.3 / NeoForge 26.3.0.99 / Java 25. Current release: **26.3.1.0**, Minecraft 26.3 / NeoForge 26.3.0.99 / Java 25.
Pending real-client validation; not committed or published. Minecraft 1.21.1 Seamless integration and the later transition guards passed player in-game
is unchanged by this issue. checks. Earlier candidate/release notes below retain their historical scope.
## Supported engines and API boundary ## Supported engines and API boundary
@@ -134,3 +134,12 @@ Inspected Seamless artifact SHA-256: `5d2bfc2a811a6526e3f6722c521d97e5de2869a6ea
## Release validation (2026-11-17) ## Release validation (2026-11-17)
Player in-game checks passed. Included in releases 1.21.1.0.6 and 26.3.0.10 (Seamless integration applies to 26.3 only). Earlier candidate notes above describe development history. Known Reborn/Seamless acknowledgement and rendering failures remain tracked in [#118](https://git.paddedcell.org/dnorberg/rivencraft/issues/118); this release does not resolve them. Player in-game checks passed. Included in releases 1.21.1.0.6 and 26.3.0.10 (Seamless integration applies to 26.3 only). Earlier candidate notes above describe development history. Known Reborn/Seamless acknowledgement and rendering failures remain tracked in [#118](https://git.paddedcell.org/dnorberg/rivencraft/issues/118); this release does not resolve them.
## Accepted transition guards — issue #118
Release **26.3.1.0**, validated as candidate **26.3.0.19**, extends the acknowledgement reset guard
to Seamless as well as Reborn, and removes unavailable section jobs before the
vanilla renderer dereferences them. The older Reborn-only notes describe the
published releases. See [transition investigation](PORTAL_TRANSITION_GUARDS.md)
for evidence, exact scope, isolated tests and remaining client validation.
+54
View File
@@ -0,0 +1,54 @@
# Writing Desk display model — issue #113
Introduced in candidates **1.21.1.0.8** and **26.3.0.12**.
Player in-game checks passed (2026-11-18); included in **1.21.1.0.12** and **26.3.0.15**.
## References and placement
Reviewed dev images/current 26.3.png and the local Legacy ModelWritingDesk /
RenderWritingDesk bytecode. Legacy uses dedicated paper geometry with small yaw
offsets and separate selected-item rendering. Reuse the imported Legacy desk
atlas, including its white paper patch; no new artwork or texture edits.
The existing two block JSON models put the tabletop at Y=12/16. Their red mat
crosses the controller/extension seam. Earlier attachments used unrelated heights:
paper at 0.27 (below the middle shelf at 0.375), selected page at 0.572 (below the tabletop at 0.75).
WritingDeskDisplayModel is shared by both clients:
- Selected page: desk-local (0.5, 0.752, 0), scale 0.7, centered on the seam/mat.
The renderer origin is the controller center (0.5, 0, 0.5).
- Paper stack: local center X=1.15, Z=-0.1, sitting on the right middle shelf at 0.376.
Its sheets are 0.5 x 0.625 blocks, 1/32 high with alternating +/-2-degree yaw.
This is the extension/right half, shifted toward the desk's front.
- One visible layer for 1–16 paper, two for 17–32, three for 33–48 and four for
49–64. Zero paper emits no mesh. Each layer has closed, shaded white geometry.
- Both attachments share the desk's existing facing transform. Geometry stays
within their respective supporting surfaces and does not overlap the selected page.
- The 26.3 renderer captures count/page during extraction and submits immutable
precomputed paper geometry; it does not read the block entity during submission.
The desk's base geometry, non-occluding registration, GUI, storage/copy costs and
item textures are unchanged. Dynamic paper is model geometry rather than repeated
vanilla Paper item sprites. Symbol Pages retain their item renderer so changing
the selected symbol displays its actual artwork.
## Validation
Both Gradle builds pass. A disposable Java geometry audit checked 126 faces over
counts 0, 1, 15, 16, 17, 32, 33, 48, 49 and 64, including outward winding, support-surface
clearance/bounds, separation from the selected page and four facing transforms.
No game server was started for this client-model change.
This does not replace GPU screenshots.
Player checks on both targets:
1. Place four desks, one per horizontal facing. Compare with neighboring solid
blocks and inspect from above, below and each side.
2. Check neither attachment, page only, paper only and both.
3. Try 1, 16, 17, 32, 33, 48, 49 and 64 paper; verify visible height transitions
and no clipping/floating geometry. Paper should be white and on the right shelf,
slightly forward; the selected page should sit over the red mat.
4. Change/remove selected pages and paper, leave/reload the chunk and restart.
Displays must update; neighboring block faces must remain visible correctly.
5. Provide comparison screenshots of all facings for final visual acceptance.
Player acceptance was reported after testing these candidates. The checklist above records the suggested visual matrix; no automated GPU screenshot or independent full restart matrix is claimed.
+1 -1
View File
@@ -36,7 +36,7 @@ mod_name=Rivencraft
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. # The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=LGPL-3.0-or-later mod_license=LGPL-3.0-or-later
# Minecraft.release-slice.iteration; independent of the 26.3 release track. # Minecraft.release-slice.iteration; independent of the 26.3 release track.
mod_version=1.21.1.0.6 mod_version=1.21.1.1.0
immersive_portals_version=6.0.7 immersive_portals_version=6.0.7
terrablender_version=4.1.0.8 terrablender_version=4.1.0.8
serene_seasons_version_id=pHEgQQUE serene_seasons_version_id=pHEgQQUE
+12 -6
View File
@@ -1,6 +1,6 @@
# Minecraft 26.3 # Minecraft 26.3
The current **Minecraft 26.3 release is 26.3.0.10**, for NeoForge 26.3.0.99 and The current **Minecraft 26.3 release is 26.3.1.0**, for NeoForge 26.3.0.99 and
Java 25. It uses Rivencraft's first-party Age backend, with no Dynamic Dimensions Java 25. It uses Rivencraft's first-party Age backend, with no Dynamic Dimensions
or Bad Packets dependency. The writing loop, authored/seeded Ages, generation or Bad Packets dependency. The writing loop, authored/seeded Ages, generation
features, weather/skies/celestials, libraries, crystal portals, live instability, features, weather/skies/celestials, libraries, crystal portals, live instability,
@@ -13,10 +13,11 @@ views. Install only one fork per instance. Built-in animations and normal travel
remain available without either. Independent settings under book_previews control remain available without either. Independent settings under book_previews control
each fork's live book and crystal views. each fork's live book and crystal views.
**Known portal-mod failures:** [#118](https://git.paddedcell.org/dnorberg/rivencraft/issues/118) **Milestone X.1.0 is complete.** This release adds the player-accepted
tracks Reborn section-rebuild crashes and Reborn/Seamless acknowledgement disconnects world-reset acknowledgement and unavailable-section rebuild guards for the
during travel. Rejoining recovered the observed Seamless Age-loading disconnect. optional portal engines. See [scope and evidence](../../docs/PORTAL_TRANSITION_GUARDS.md).
This release does not fix those failures. See [integration details](../../docs/SEAMLESS_PORTALS.md). Native Nether/End fluid and sky defaults and Flat biome materials are covered
in [Native generation](../../docs/NATIVE_FLUIDS.md).
Native Caves/Nether/End Pages, desert vegetation and Number-controlled Static Sky Native Caves/Nether/End Pages, desert vegetation and Number-controlled Static Sky
resolution passed player checks on both supported versions. Native controls select resolution passed player checks on both supported versions. Native controls select
@@ -29,7 +30,12 @@ The port feature and acceptance review is recorded in
movement is disabled. The final dedicated-server restart/return check passed. movement is disabled. The final dedicated-server restart/return check passed.
Create/Ponder scenes are not ported to this target. Use matching client/server Create/Ponder scenes are not ported to this target. Use matching client/server
builds, keep saves separate from 1.21.1 and back up before updating. builds, keep saves separate from 1.21.1 and back up before updating.
See [release notes](RELEASE_NOTES_26.3.0.10.md). See [release notes](RELEASE_NOTES_26.3.1.0.md).
This release adds [Accelerated machine ticking](../../docs/ACCELERATED_MACHINES.md),
corrects [Writing Desk displays](../../docs/WRITING_DESK_MODEL.md), restores
[dropped-book interaction](../../docs/DROPPED_BOOKS.md), and adds
[void/skyblock block baselines](../../docs/BLOCK_BASELINE.md). Player in-game checks passed.
Flooded Environment Pages now fill Cave and other terrain to Y=63 by default, Flooded Environment Pages now fill Cave and other terrain to Y=63 by default,
or the absolute base-25 Number Pages immediately before Flooded. Both-version or the absolute base-25 Number Pages immediately before Flooded. Both-version
+11
View File
@@ -0,0 +1,11 @@
# Rivencraft 26.3.0.11
Intermediate development candidate; accepted changes are included in the subsequent 1.21.1.0.12 / 26.3.0.15 releases.
- Accelerated Pages now give ticking server machines extra registered ticker calls.
- Repeated Pages stack within separate configurable machine and candidate budgets.
- Fair allocation, loaded/ticking chunk checks, world-border/removal checks and tick freeze remain in effect.
- No force-loading or entity acceleration; normal Ages and the Overworld are unchanged.
- Existing Accelerated Ages gain the behavior without rebinding; saved Page counts are unchanged.
- Random-block acceleration retains its own independent budget.
- Machine fuel, energy and input costs remain normal; global-time-gated machines may not scale linearly.
+8
View File
@@ -0,0 +1,8 @@
# Rivencraft 26.3.0.12
Intermediate development candidate; accepted changes are included in the subsequent 1.21.1.0.12 / 26.3.0.15 releases.
- Corrects Writing Desk selected-page height and centers it on the red writing mat.
- Adds shared white paper-stack geometry on the right shelf, slightly forward, using Legacy's existing desk texture.
- Paper count controls up to four staggered layers; attachments follow all desk facings.
- Includes the player-validated Accelerated machine support from issue #112.
+11
View File
@@ -0,0 +1,11 @@
# Rivencraft 26.3.0.13
Intermediate development candidate; accepted changes are included in the subsequent 1.21.1.0.12 / 26.3.0.15 releases.
- Dropped Linking/Descriptive Books no longer auto-pick up on contact.
- Right-click opens the existing book GUI; its panel links while leaving the book on the ground.
- Shift-right-click picks up using normal ownership, pickup-delay and inventory checks.
- Ground-book previews follow lectern behavior: rotating views remain available, interactive exploration is disabled.
- Server validates the actual nearby entity, UUID and expected book for actions and previews.
- Clients and servers must use matching updated builds.
- Includes the prior local Writing Desk and machine-acceleration changes; 1.21.1 also includes universal open-book drop conversion.
+18
View File
@@ -0,0 +1,18 @@
# Rivencraft 26.3.0.15
Release for Minecraft 26.3 / NeoForge 26.3.0.99 / Java 25.
Uses Rivencraft's first-party Age backend; no Dynamic Dimensions or Bad Packets required. Update clients and servers together.
- Accelerated Pages now also speed up registered server-side machine tickers. Repeated Pages stack within independent configurable machine/candidate budgets. Normal fuel, energy and input costs apply; machines gated by global time may remain limited.
- Corrects Writing Desk selected-page placement on the red mat and adds white paper-stack geometry on the right shelf, with up to four layers matching the stored paper count.
- Dropped Linking and Descriptive Books do not auto-pick up. Right-click opens the book; shift-right-click collects it with normal ownership, delay and inventory checks. Destination-panel travel leaves the ground book in place.
- Ground-book previews follow lectern behavior: rotating previews remain available, interactive exploration is disabled. Server validation rejects stale or remote book actions.
- Zero-count Overworld materials use version-specific bundled averages, balancing valuable-block instability with void/skyblock Overworlds. Positive measured counts retain precedence.
- Missing modded ores use combined iron/deepslate iron measurements, falling back to bundled iron averages when measured iron is also absent. No extra profiling dimension is generated.
- Existing 401 Age / 500 Overworld sampling thresholds, 5% excess allowance, material weights and difficulty controls remain unchanged.
Player in-game checks passed for both supported versions. Focused machine probes passed 25 checks (1.21.1) / 26 (26.3), dropped-book interaction probes passed 21 / 23, and baseline policy checks passed 14 per version with source-average audits. The 1.21.1 universal-drop probe passed 62 checks. Writing Desk geometry audit passed 126 face checks. These do not claim a separate automated full client/restart matrix.
The abandoned reference-world generation probes stalled and were stopped without retry. They are superseded by bundled defaults; no generation pass is claimed for them.
Known issue: [#118](https://git.paddedcell.org/dnorberg/rivencraft/issues/118) continues to track optional Reborn/Seamless crashes and travel disconnects. This release does not fix those failures.
+8
View File
@@ -0,0 +1,8 @@
# Rivencraft 26.3.0.16
Intermediate development candidate; accepted changes are included in 1.21.1.1.0 / 26.3.1.0. This candidate was not published.
- Native Nether uses lava for natural noise-terrain fluids, including Cave terrain, and disables Overworld water aquifers.
- Native End removes natural fluid filling and aquifers while retaining the chosen terrain geometry.
- Flat/Void remain flat/empty. Explicit Flooded and authored fluid features retain their own behavior.
- Updated Native-family tooltips. Existing generated chunks are not rewritten; test new Ages.
+9
View File
@@ -0,0 +1,9 @@
# Rivencraft 26.3.0.17
Intermediate development candidate; accepted changes are included in 1.21.1.1.0 / 26.3.1.0. This candidate was not published.
- Native Nether defaults to its Nether sky, and Native End to its End sky, unless an explicit Sky Page chooses another style.
- Written Sky Pages retain priority with authored celestials. Native/Caves keep their previous sky fallback.
- Includes Native Nether natural lava and Native End dry-terrain changes from the prior candidate.
- Flat/Void geometry and explicitly authored Flooded/fluid features retain their behavior.
- Updated tooltips. Existing generated chunks are not rewritten.
+10
View File
@@ -0,0 +1,10 @@
# Rivencraft 26.3.0.18
Intermediate development candidate; accepted changes are included in 1.21.1.1.0 / 26.3.1.0. This candidate was not published.
- Flat End biomes now use End Stone instead of grass/dirt.
- Flat Nether biomes use Nether ground, including Crimson/Warped Nylium, Soul Sand/Soul Soil and Basalt/Blackstone for the corresponding vanilla biomes.
- Supports single-biome plans and local materials in mixed distributions, including tagged End and TerraBlender-region Nether classification.
- Base-column queries match placed materials. Bedrock, air, height, authored features and fluids are preserved.
- Includes the earlier Native Nether lava / Native End dry generation and default sky improvements.
- Existing generated chunks are not rewritten; use fresh Ages for visual checks.
+11
View File
@@ -0,0 +1,11 @@
# Rivencraft 26.3.0.19
Intermediate development candidate; accepted changes are included in 1.21.1.1.0 / 26.3.1.0. This candidate was not published.
- Extends the block-prediction acknowledgement guard to Seamless as well as Reborn during portal-engine world-map reset.
- Preserves normal initialized multiworld acknowledgements and off-thread packet scheduling.
- Filters only unavailable section rebuild jobs before compilation when a supported portal fork is installed. Valid jobs, geometry callbacks and dirty state remain intact.
- Unrelated renderer exceptions are not swallowed. Full runtime/client validation is still required.
- Includes the accepted Native fluids/skies and Flat End/Nether ground updates.
26.3 build passed; 47 isolated guard checks passed. Minecraft runtime types were stubs, with production guard bytecode and both forks' actual acknowledgement redirect bytecode. This is not a complete client/network/GPU pass. Minecraft 1.21.1 is unchanged by this fix.
+20
View File
@@ -0,0 +1,20 @@
# Rivencraft 26.3.1.0
Completes Milestone X.1.0 for Minecraft 26.3 / NeoForge 26.3.0.99 / Java 25.
Uses Rivencraft's first-party Age backend; no Dynamic Dimensions or Bad Packets required. Use matching client/server builds and the JAR for your Minecraft version.
- Native Nether uses lava for natural noise-terrain fluids, including Cave terrain, and disables Overworld water aquifers.
- Native End removes natural fluid filling and aquifers while preserving the chosen terrain geometry.
- Native Nether and Native End default to their corresponding skies when no Sky Page is written. Explicit Sky Pages retain priority, including with authored celestials.
- Flat End biomes use End Stone instead of grass/dirt. Flat Nether biomes use Nether ground, including Crimson/Warped Nylium, Soul Sand/Soul Soil and Basalt/Blackstone for the corresponding vanilla biomes.
- Corrects single-biome Flat generation and local materials across mixed distributions. Tagged End biomes and TerraBlender-region Nether classification are recognized; other recognized Nether biomes use the Netherrack fallback.
- Base-column queries match placed Flat materials. Bedrock, air, height, authored features and explicit Flooded/fluid features retain their behavior.
- Updated Native-family tooltips. Existing generated chunks are not rewritten.
- Extends the transitional block-prediction acknowledgement guard to Seamless and Reborn, preserving ordinary initialized multiworld delivery and off-thread scheduling.
- Filters only unavailable section rebuild jobs before compilation when either supported portal engine is installed. Valid jobs, additional geometry and dirty state are preserved; unrelated renderer exceptions propagate.
Player in-game checks passed. Sequential Native-generation probes passed **219 checks on 1.21.1 / 213 on 26.3**, including actual Flat block placement, mixed distributions, generator codecs, natural-fluid settings and sky precedence. Temporary worlds were removed; no probe stalled.
The transition guards passed **47 isolated checks** using production guard bytecode and both forks' acknowledgement redirect bytecode with stubbed Minecraft runtime types. The player subsequently reported in-game acceptance. This does not claim an independent exhaustive GPU/network matrix or standalone external-fork reproduction. Install only one optional portal fork at a time.
Versioning is now **Minecraft version.1.0**: milestone/release slice 1, iteration 0. Both Minecraft tracks retain separate builds and saves.
+1 -1
View File
@@ -7,7 +7,7 @@ neo_version=26.3.0.99
mod_id=rivencraft mod_id=rivencraft
mod_name=Rivencraft mod_name=Rivencraft
mod_license=LGPL-3.0-or-later mod_license=LGPL-3.0-or-later
mod_version=26.3.0.10 mod_version=26.3.1.0
jei_version=31.17.0.109 jei_version=31.17.0.109
+1 -1
View File
@@ -86,7 +86,7 @@
"symbol.rivencraft.feature.dungeons.description": "Add monster-room dungeon attempts throughout surface noise or Cave terrain, including Nether cave biomes. Not Flat or Void.", "symbol.rivencraft.feature.dungeons.description": "Add monster-room dungeon attempts throughout surface noise or Cave terrain, including Nether cave biomes. Not Flat or Void.",
"symbol.rivencraft.biome.single.description": "Use one biome across the Age. If omitted, choose an eligible biome from the Age seed.", "symbol.rivencraft.biome.single.description": "Use one biome across the Age. If omitted, choose an eligible biome from the Age seed.",
"symbol.rivencraft.terrain.flat.description": "A level, biome-decorated landscape with its foundation at Y=0.", "symbol.rivencraft.terrain.flat.description": "A level, biome-decorated landscape with its foundation at Y=0.",
"symbol.rivencraft.environment.accelerated.description": "Adds extra random block ticks near players in this Age. Repeated pages stack within server tick budgets; does not speed up entities or machines.", "symbol.rivencraft.environment.accelerated.description": "Adds extra random block ticks and server machine ticks in this Age. Repeated pages stack within separate budgets; entities are not accelerated.",
"symbol.rivencraft.feature.floating_islands.description": "Add high floating islands alongside noise, Flat, or Void terrain; not Cave terrain.", "symbol.rivencraft.feature.floating_islands.description": "Add high floating islands alongside noise, Flat, or Void terrain; not Cave terrain.",
"symbol.rivencraft.feature.caves.description": "Add extra cave carving to noise terrain, including Cave; not Flat or Void.", "symbol.rivencraft.feature.caves.description": "Add extra cave carving to noise terrain, including Cave; not Flat or Void.",
"symbol.rivencraft.feature.ravines.description": "Add canyon carving to noise terrain; not Flat or Void. Skips Nether biomes.", "symbol.rivencraft.feature.ravines.description": "Add canyon carving to noise terrain; not Flat or Void. Skips Nether biomes.",
@@ -20,6 +20,8 @@ public final class PortConfig {
public static final ModConfigSpec.EnumValue<ReturnLinkMode> RETURN_LINK_MODE; public static final ModConfigSpec.EnumValue<ReturnLinkMode> RETURN_LINK_MODE;
public static final ModConfigSpec.IntValue ACCELERATED_MAX_CHUNKS; public static final ModConfigSpec.IntValue ACCELERATED_MAX_CHUNKS;
public static final ModConfigSpec.IntValue ACCELERATED_MAX_ATTEMPTS; public static final ModConfigSpec.IntValue ACCELERATED_MAX_ATTEMPTS;
public static final ModConfigSpec.IntValue ACCELERATED_MACHINE_CANDIDATES;
public static final ModConfigSpec.IntValue ACCELERATED_MACHINE_TICKS;
static { static {
var builder = new ModConfigSpec.Builder(); var builder = new ModConfigSpec.Builder();
@@ -74,8 +76,12 @@ public final class PortConfig {
builder.push("accelerated_age"); builder.push("accelerated_age");
ACCELERATED_MAX_CHUNKS = builder.comment("Maximum already-loaded player-nearby chunks given extra random ticks per Age tick.") ACCELERATED_MAX_CHUNKS = builder.comment("Maximum already-loaded player-nearby chunks given extra random ticks per Age tick.")
.defineInRange("max_loaded_chunks", 8, 1, 64); .defineInRange("max_loaded_chunks", 8, 1, 64);
ACCELERATED_MAX_ATTEMPTS = builder.comment("Maximum extra random-tick positions sampled per Age tick, shared fairly across loaded sections; zero disables Accelerated.") ACCELERATED_MAX_ATTEMPTS = builder.comment("Maximum extra random-tick positions sampled per Age tick, shared fairly across loaded sections; zero disables extra random ticks.")
.defineInRange("max_random_tick_attempts_per_tick", 16384, 0, 65536); .defineInRange("max_random_tick_attempts_per_tick", 16384, 0, 65536);
ACCELERATED_MACHINE_CANDIDATES = builder.comment("Maximum registered server machine tickers inspected per Age tick; rotates fairly without loading chunks.")
.defineInRange("max_machine_candidates_per_tick", 1024, 1, 65536);
ACCELERATED_MACHINE_TICKS = builder.comment("Maximum extra machine ticker calls per Age tick, shared round-robin. Each Accelerated page requests one extra tick per machine; zero disables machine acceleration independently of random ticks.")
.defineInRange("max_machine_ticks_per_tick", 4096, 0, 65536);
builder.pop(); builder.pop();
net.dnorberg.rivencraft.age.PortInstabilityConfig.define(builder); net.dnorberg.rivencraft.age.PortInstabilityConfig.define(builder);
SPEC = builder.build(); SPEC = builder.build();
@@ -16,7 +16,7 @@ import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
/** Extra random block ticks from authored Accelerated pages, bounded to loaded player chunks. */ /** Independent bounded random-block and server-machine acceleration in authored Ages. */
public final class PortAcceleratedTicks { public final class PortAcceleratedTicks {
public static final Identifier PAGE = Identifier.fromNamespaceAndPath("rivencraft", "environment/accelerated"); public static final Identifier PAGE = Identifier.fromNamespaceAndPath("rivencraft", "environment/accelerated");
@@ -42,9 +42,10 @@ public final class PortAcceleratedTicks {
static void tick(ServerLevel level) { static void tick(ServerLevel level) {
int maximumAttempts = PortConfig.ACCELERATED_MAX_ATTEMPTS.get(); int maximumAttempts = PortConfig.ACCELERATED_MAX_ATTEMPTS.get();
if (maximumAttempts == 0) return;
int pages = pages(level); int pages = pages(level);
if (pages == 0) return; if (pages == 0 || !level.tickRateManager().runsNormally() || level.tickRateManager().isFrozen()) return;
PortMachineTicks.tick(level, pages);
if (maximumAttempts == 0) return;
List<ChunkPos> chunks = loadedPlayerChunks(level); List<ChunkPos> chunks = loadedPlayerChunks(level);
if (chunks.isEmpty()) return; if (chunks.isEmpty()) return;
@@ -54,6 +54,32 @@ public final class PortBlockInstability {
private PortBlockInstability() {} private PortBlockInstability() {}
private static final net.dnorberg.rivencraft.shared.MaterialBaselinePolicy DEFAULT_BASELINE =
net.dnorberg.rivencraft.shared.MaterialBaselinePolicy.load(
"/assets/rivencraft/instability/default_block_baseline.json");
public static int baselineSamples(MinecraftServer server) {
return PortBlockProfileSavedData.get(server.overworld()).count();
}
public static String baselineStatus(MinecraftServer server) {
return "minecraft:overworld; zero counts use bundled defaults, modded ores use iron";
}
private static boolean moddedOre(Identifier id) {
if (id.getNamespace().equals("minecraft") || id.getNamespace().equals("rivencraft")
|| !BuiltInRegistries.BLOCK.containsKey(id)) return false;
var state = BuiltInRegistries.BLOCK.getValue(id).defaultBlockState();
return state.is(Tags.BlockItems.ORES.block()) || id.getPath().endsWith("_ore") || id.getPath().contains("_ore_");
}
static double baselineAverage(Identifier id, Map<Identifier, Long> baseline, int chunks) {
long iron = baseline.getOrDefault(Identifier.withDefaultNamespace("iron_ore"), 0L)
+ baseline.getOrDefault(Identifier.withDefaultNamespace("deepslate_iron_ore"), 0L);
return DEFAULT_BASELINE.average(id.toString(), baseline.getOrDefault(id, 0L),
chunks, moddedOre(id), iron);
}
/** Track recognized materials from installed mods without requiring any mod-specific API. */ /** Track recognized materials from installed mods without requiring any mod-specific API. */
static boolean tracked(Identifier id) { static boolean tracked(Identifier id) {
if (VANILLA_WEIGHTS.containsKey(id)) return true; if (VANILLA_WEIGHTS.containsKey(id)) return true;
@@ -164,7 +190,7 @@ public final class PortBlockInstability {
GENERATION_IN_FLIGHT.remove(event.getServer()); GENERATION_IN_FLIGHT.remove(event.getServer());
} }
/** Generate at most one chunk per second across the active Age and its Overworld baseline. */ /** Generate at most one chunk per second across active Ages and the Overworld baseline. */
private static void generateNextSpawnSample(MinecraftServer server) { private static void generateNextSpawnSample(MinecraftServer server) {
if (GENERATION_IN_FLIGHT.containsKey(server)) return; if (GENERATION_IN_FLIGHT.containsKey(server)) return;
List<SampleTarget> targets = new ArrayList<>(); List<SampleTarget> targets = new ArrayList<>();
@@ -178,8 +204,8 @@ public final class PortBlockInstability {
PortBlockProfileSavedData.MIN_AGE_SAMPLES)); PortBlockProfileSavedData.MIN_AGE_SAMPLES));
} }
if (targets.isEmpty()) return; if (targets.isEmpty()) return;
ServerLevel overworld = server.overworld(); ServerLevel baseline = server.overworld();
targets.add(0, new SampleTarget(overworld, overworld.getRespawnData().pos(), targets.add(0, new SampleTarget(baseline, baseline.getRespawnData().pos(),
PortBlockProfileSavedData.MIN_BASELINE_SAMPLES)); PortBlockProfileSavedData.MIN_BASELINE_SAMPLES));
int first = Math.floorMod(NEXT_TARGET.getOrDefault(server, 0), targets.size()); int first = Math.floorMod(NEXT_TARGET.getOrDefault(server, 0), targets.size());
for (int offset = 0; offset < targets.size(); offset++) { for (int offset = 0; offset < targets.size(); offset++) {
@@ -261,7 +287,7 @@ public final class PortBlockInstability {
double weight = weight(id); double weight = weight(id);
if (weight <= 0) continue; if (weight <= 0) continue;
double excess = age.getOrDefault(id, 0L) / (double) ageChunks double excess = age.getOrDefault(id, 0L) / (double) ageChunks
- 1.05 * baseline.getOrDefault(id, 0L) / (double) baselineChunks; - 1.05 * baselineAverage(id, baseline, baselineChunks);
if (excess > 0) result += excess * weight; if (excess > 0) result += excess * weight;
} }
return (int) Math.min(100_000, Math.round(result)); return (int) Math.min(100_000, Math.round(result));
@@ -3,6 +3,8 @@ package net.dnorberg.rivencraft.age;
import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.List; import java.util.List;
import net.dnorberg.rivencraft.shared.FlatBiomeMaterials;
import net.minecraft.resources.Identifier;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -38,16 +40,25 @@ import org.jspecify.annotations.Nullable;
public final class PortFlatChunkGenerator extends ChunkGenerator { public final class PortFlatChunkGenerator extends ChunkGenerator {
public static final MapCodec<PortFlatChunkGenerator> CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( public static final MapCodec<PortFlatChunkGenerator> CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group(
BiomeSource.CODEC.fieldOf("biome_source").forGetter(generator -> generator.biomeSource), BiomeSource.CODEC.fieldOf("biome_source").forGetter(generator -> generator.biomeSource),
FlatLevelGeneratorSettings.CODEC.fieldOf("settings").forGetter(PortFlatChunkGenerator::settings) FlatLevelGeneratorSettings.CODEC.fieldOf("settings").forGetter(PortFlatChunkGenerator::settings),
Identifier.CODEC.listOf().optionalFieldOf("nether_biomes", List.of()).forGetter(generator -> generator.netherBiomeIds)
).apply(instance, PortFlatChunkGenerator::new)); ).apply(instance, PortFlatChunkGenerator::new));
private final FlatLevelGeneratorSettings settings; private final FlatLevelGeneratorSettings settings;
private final List<Identifier> netherBiomeIds;
private final Set<Identifier> netherBiomes;
private final MemoizedFunction<Holder<Biome>, BiomeGenerationSettings> generationSettingsGetter; private final MemoizedFunction<Holder<Biome>, BiomeGenerationSettings> generationSettingsGetter;
public PortFlatChunkGenerator(BiomeSource biomeSource, FlatLevelGeneratorSettings settings) { public PortFlatChunkGenerator(BiomeSource biomeSource, FlatLevelGeneratorSettings settings) {
this(biomeSource, settings, List.of());
}
public PortFlatChunkGenerator(BiomeSource biomeSource, FlatLevelGeneratorSettings settings, List<Identifier> netherBiomeIds) {
super(biomeSource, this.generationSettingsGetter = MemoizedFunction.of( super(biomeSource, this.generationSettingsGetter = MemoizedFunction.of(
biome -> generationSettings(settings, biome))); biome -> generationSettings(settings, biome)));
this.settings = settings; this.settings = settings;
this.netherBiomeIds = List.copyOf(netherBiomeIds);
this.netherBiomes = Set.copyOf(netherBiomeIds);
} }
public FlatLevelGeneratorSettings settings() { public FlatLevelGeneratorSettings settings() {
@@ -92,6 +103,7 @@ public final class PortFlatChunkGenerator extends ChunkGenerator {
RandomState random, StructureManager structures, BiomeManager biomes, RandomState random, StructureManager structures, BiomeManager biomes,
@Nullable WorldGenRegion carverBiomeRegion, Set<Holder<Biome>> possibleBiomes) { @Nullable WorldGenRegion carverBiomeRegion, Set<Holder<Biome>> possibleBiomes) {
List<BlockState> layers = settings.getLayers(); List<BlockState> layers = settings.getLayers();
var resolver = biomeSource.createUncachedResolver(random);
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
Heightmap floor = chunk.getOrCreateHeightmapUnprimed(Heightmap.Types.OCEAN_FLOOR_WG); Heightmap floor = chunk.getOrCreateHeightmapUnprimed(Heightmap.Types.OCEAN_FLOOR_WG);
Heightmap surface = chunk.getOrCreateHeightmapUnprimed(Heightmap.Types.WORLD_SURFACE_WG); Heightmap surface = chunk.getOrCreateHeightmapUnprimed(Heightmap.Types.WORLD_SURFACE_WG);
@@ -100,9 +112,11 @@ public final class PortFlatChunkGenerator extends ChunkGenerator {
if (state == null) continue; if (state == null) continue;
int y = chunk.getMinY() + layer; int y = chunk.getMinY() + layer;
for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) {
chunk.setBlockState(pos.set(x, y, z), state); BlockState actual = layerState(state, chunk.getPos().getMinBlockX() + x, y,
floor.update(x, y, z, state); chunk.getPos().getMinBlockZ() + z, resolver);
surface.update(x, y, z, state); chunk.setBlockState(pos.set(x, y, z), actual);
floor.update(x, y, z, actual);
surface.update(x, y, z, actual);
} }
} }
return CompletableFuture.completedFuture(chunk); return CompletableFuture.completedFuture(chunk);
@@ -121,11 +135,22 @@ public final class PortFlatChunkGenerator extends ChunkGenerator {
@Override @Override
public NoiseColumn getBaseColumn(int x, int z, LevelHeightAccessor height, RandomState random) { public NoiseColumn getBaseColumn(int x, int z, LevelHeightAccessor height, RandomState random) {
return new NoiseColumn(height.getMinY(), settings.getLayers().stream().limit(height.getHeight()) var layers = settings.getLayers();
.map(state -> state == null ? Blocks.AIR.defaultBlockState() : state) var resolver = biomeSource.createUncachedResolver(random);
return new NoiseColumn(height.getMinY(), java.util.stream.IntStream.range(0, Math.min(height.getHeight(), layers.size()))
.mapToObj(i -> layerState(layers.get(i), x, height.getMinY() + i, z, resolver))
.toArray(BlockState[]::new)); .toArray(BlockState[]::new));
} }
private BlockState layerState(BlockState state, int x, int y, int z, net.minecraft.world.level.biome.BiomeResolver resolver) {
if (state == null) return Blocks.AIR.defaultBlockState();
if (!FlatBiomeMaterials.isBaseMaterial(state)) return state;
var biome = resolver.getNoiseBiome(net.minecraft.core.QuartPos.fromBlock(x),
net.minecraft.core.QuartPos.fromBlock(y), net.minecraft.core.QuartPos.fromBlock(z));
boolean regionNether = biome.unwrapKey().map(key -> netherBiomes.contains(key.identifier())).orElse(false);
return FlatBiomeMaterials.layer(state, biome, regionNether);
}
@Override public void addDebugScreenInfo(List<String> info, RandomState random, @Override public void addDebugScreenInfo(List<String> info, RandomState random,
BlockPos pos, SamplerContext context) { } BlockPos pos, SamplerContext context) { }
@Override public void spawnOriginalMobs(WorldGenRegion level) { } @Override public void spawnOriginalMobs(WorldGenRegion level) { }
@@ -32,7 +32,8 @@ public final class PortInstabilityCommands {
+ "; effective score=" + PortInstabilityRuntime.effectiveScore(level) + "; effective score=" + PortInstabilityRuntime.effectiveScore(level)
+ "; difficulty=" + PortInstabilityConfig.instabilityDifficulty() + "; difficulty=" + PortInstabilityConfig.instabilityDifficulty()
+ "; samples Age=" + PortBlockInstability.sampledChunks(level) + "/" + PortBlockProfileSavedData.MIN_AGE_SAMPLES + "; samples Age=" + PortBlockInstability.sampledChunks(level) + "/" + PortBlockProfileSavedData.MIN_AGE_SAMPLES
+ ", Overworld=" + PortBlockInstability.sampledChunks(source.getServer().overworld()) + "/" + PortBlockProfileSavedData.MIN_BASELINE_SAMPLES + ", baseline=" + PortBlockInstability.baselineSamples(source.getServer()) + "/" + PortBlockProfileSavedData.MIN_BASELINE_SAMPLES
+ " [" + PortBlockInstability.baselineStatus(source.getServer()) + "]"
+ "; profiling=" + PortInstabilityData.get(source.getServer()).supportsProfiling(level)), false); + "; profiling=" + PortInstabilityData.get(source.getServer()).supportsProfiling(level)), false);
for (var cost : age.contributions()) source.sendSuccess(() -> Component.literal( for (var cost : age.contributions()) source.sendSuccess(() -> Component.literal(
" " + cost.reason() + " page=" + cost.page() + " +" + cost.points()), false); " " + cost.reason() + " page=" + cost.page() + " +" + cost.points()), false);
@@ -0,0 +1,30 @@
package net.dnorberg.rivencraft.age;
import java.util.Map;
import java.util.WeakHashMap;
import net.dnorberg.rivencraft.PortConfig;
import net.dnorberg.rivencraft.mixin.LevelBlockEntityTickersAccessor;
import net.dnorberg.rivencraft.shared.AcceleratedMachineWork;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.entity.TickingBlockEntity;
/** Reuses vanilla/NeoForge bound tickers, including modded server machines. */
public final class PortMachineTicks {
private static final Map<ServerLevel, AcceleratedMachineWork> WORK = new WeakHashMap<>();
private PortMachineTicks() {}
public static void tick(ServerLevel level, int pages) {
if (pages <= 0 || !level.tickRateManager().runsNormally() || level.tickRateManager().isFrozen()) return;
WORK.computeIfAbsent(level, ignored -> new AcceleratedMachineWork()).run(
((LevelBlockEntityTickersAccessor) level).rivencraft$blockEntityTickers(),
pages, PortConfig.ACCELERATED_MACHINE_CANDIDATES.get(), PortConfig.ACCELERATED_MACHINE_TICKS.get(),
ticker -> eligible(level, ticker), TickingBlockEntity::tick);
}
private static boolean eligible(ServerLevel level, TickingBlockEntity ticker) {
var pos = ticker.getPos();
return level.tickRateManager().runsNormally() && !level.tickRateManager().isFrozen() && !ticker.isRemoved()
&& level.getWorldBorder().isWithinBounds(pos)
&& level.hasChunkAt(pos) && level.shouldTickBlocksAt(pos);
}
}
@@ -2,6 +2,7 @@ package net.dnorberg.rivencraft.age;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import java.util.List; import java.util.List;
import net.dnorberg.rivencraft.shared.NativeBiomeKind;
import java.util.Locale; import java.util.Locale;
import java.util.Random; import java.util.Random;
import net.dnorberg.rivencraft.Rivencraft; import net.dnorberg.rivencraft.Rivencraft;
@@ -30,9 +31,25 @@ public enum PortSkyStyle {
} }
public static PortSkyStyle resolve(List<Identifier> pages, long seed, PortRandomPagePolicy policy) { public static PortSkyStyle resolve(List<Identifier> pages, long seed, PortRandomPagePolicy policy) {
return pages.stream().map(PortSkyStyle::forPage).filter(java.util.Objects::nonNull) var explicit = pages.stream().map(PortSkyStyle::forPage).filter(java.util.Objects::nonNull).findFirst();
.findFirst().orElseGet(() -> pages.stream().anyMatch(PortSkyStyle::isCelestial) if (explicit.isPresent()) return explicit.get();
? OVERWORLD : random(seed, policy)); NativeBiomeKind family = NativeBiomeKind.TERRAIN;
for (var page : pages) {
if (!page.getNamespace().equals(Rivencraft.MOD_ID) || !page.getPath().startsWith("biome/")) continue;
String choice = page.getPath().substring("biome/".length());
if (NativeBiomeKind.isController(choice)) family = NativeBiomeKind.controller(choice);
}
PortSkyStyle nativeSky = forNativeKind(family, null);
if (nativeSky != null) return nativeSky;
return pages.stream().anyMatch(PortSkyStyle::isCelestial) ? OVERWORLD : random(seed, policy);
}
public static PortSkyStyle forNativeKind(NativeBiomeKind kind, PortSkyStyle fallback) {
return switch (kind) {
case NETHER -> NETHER;
case END -> END;
default -> fallback;
};
} }
/** Nether-style Ages use their fog clear color as the visible backdrop. */ /** Nether-style Ages use their fog clear color as the visible backdrop. */
@@ -1,5 +1,7 @@
package net.dnorberg.rivencraft.age; package net.dnorberg.rivencraft.age;
import net.dnorberg.rivencraft.shared.NativeBiomeKind;
import java.io.IOException; import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -123,7 +125,8 @@ public final class RuntimeAgeBackend {
PortTerrainFeaturePlan terrainFeatures, PortWeatherMode weather, PortTerrainFeaturePlan terrainFeatures, PortWeatherMode weather,
PortLighting lighting) { PortLighting lighting) {
return create(server, id, seed, biomePlan, terrain, rocks, vegetation, dungeons, lakes, return create(server, id, seed, biomePlan, terrain, rocks, vegetation, dungeons, lakes,
terrainFeatures, weather, lighting, PortSkyStyle.OVERWORLD); terrainFeatures, weather, lighting, PortSkyStyle.forNativeKind(
biomePlan == null ? NativeBiomeKind.TERRAIN : biomePlan.nativeKind(), PortSkyStyle.OVERWORLD));
} }
public static ServerLevel create(MinecraftServer server, Identifier id, long seed, public static ServerLevel create(MinecraftServer server, Identifier id, long seed,
@@ -539,7 +542,7 @@ public final class RuntimeAgeBackend {
if (server.getLevel(key) != null) throw new IllegalArgumentException("Level already loaded: " + id); if (server.getLevel(key) != null) throw new IllegalArgumentException("Level already loaded: " + id);
if (biomePlan != null && biomePlan.distribution() == PortBiomePlan.Distribution.NATIVE if (biomePlan != null && biomePlan.distribution() == PortBiomePlan.Distribution.NATIVE
&& !biomePlan.biomes().isEmpty() && terrain != PortAgeTerrain.CAVE && !biomePlan.biomes().isEmpty() && terrain != PortAgeTerrain.CAVE
&& biomePlan.nativeKind() == net.dnorberg.rivencraft.shared.NativeBiomeKind.TERRAIN) && biomePlan.nativeKind() == NativeBiomeKind.TERRAIN)
throw new IllegalArgumentException("Only Native Cave terrain may carry an explicit native biome pool"); throw new IllegalArgumentException("Only Native Cave terrain may carry an explicit native biome pool");
// Noise terrains reuse the Overworld biome source unless a // Noise terrains reuse the Overworld biome source unless a
@@ -575,11 +578,15 @@ public final class RuntimeAgeBackend {
settings = new FlatLevelGeneratorSettings(Optional.empty(), biome, List.of()); settings = new FlatLevelGeneratorSettings(Optional.empty(), biome, List.of());
settings.updateLayers(); settings.updateLayers();
} }
generator = biomePlan != null && biomePlan.biomes().size() > 1 var netherBiomes = net.dnorberg.rivencraft.compat.TerraBlenderBiomes.nether(server.registryAccess());
? new PortFlatChunkGenerator(authoredBiomeSource(server, biomePlan, seed), settings) boolean specialGround = net.dnorberg.rivencraft.shared.FlatBiomeMaterials.isEnd(biome)
|| net.dnorberg.rivencraft.shared.FlatBiomeMaterials.isNether(biome,
biome.unwrapKey().map(b -> netherBiomes.contains(b.identifier())).orElse(false));
generator = biomePlan != null && (biomePlan.biomes().size() > 1 || specialGround)
? new PortFlatChunkGenerator(authoredBiomeSource(server, biomePlan, seed), settings, netherBiomes)
: new FlatLevelSource(settings); : new FlatLevelSource(settings);
} else if ((biomePlan != null && (biomePlan.distribution() != PortBiomePlan.Distribution.NATIVE } else if ((biomePlan != null && (biomePlan.distribution() != PortBiomePlan.Distribution.NATIVE
|| biomePlan.nativeKind() != net.dnorberg.rivencraft.shared.NativeBiomeKind.TERRAIN)) || biomePlan.nativeKind() != NativeBiomeKind.TERRAIN))
|| terrain != PortAgeTerrain.STANDARD) { || terrain != PortAgeTerrain.STANDARD) {
// A Flat/skyblock Overworld has no noise generator to adapt. Native // A Flat/skyblock Overworld has no noise generator to adapt. Native
// family pages must still work with an independently authored noise terrain. // family pages must still work with an independently authored noise terrain.
@@ -595,7 +602,7 @@ public final class RuntimeAgeBackend {
.getOrThrow(Biomes.LUSH_CAVES)) .getOrThrow(Biomes.LUSH_CAVES))
: noise.getBiomeSource(); : noise.getBiomeSource();
if (terrain == PortAgeTerrain.CAVE && biomePlan != null if (terrain == PortAgeTerrain.CAVE && biomePlan != null
&& biomePlan.nativeKind() == net.dnorberg.rivencraft.shared.NativeBiomeKind.TERRAIN) { && biomePlan.nativeKind() == NativeBiomeKind.TERRAIN) {
var biomes = server.registryAccess().lookupOrThrow(Registries.BIOME); var biomes = server.registryAccess().lookupOrThrow(Registries.BIOME);
for (Identifier biomeId : biomePlan.biomes()) { for (Identifier biomeId : biomePlan.biomes()) {
var holder = biomes.get(ResourceKey.create(Registries.BIOME, biomeId)) var holder = biomes.get(ResourceKey.create(Registries.BIOME, biomeId))
@@ -605,7 +612,7 @@ public final class RuntimeAgeBackend {
} }
} }
if (biomePlan != null && (biomePlan.distribution() != PortBiomePlan.Distribution.NATIVE if (biomePlan != null && (biomePlan.distribution() != PortBiomePlan.Distribution.NATIVE
|| biomePlan.nativeKind() != net.dnorberg.rivencraft.shared.NativeBiomeKind.TERRAIN || biomePlan.nativeKind() != NativeBiomeKind.TERRAIN
|| terrain == PortAgeTerrain.CAVE && !biomePlan.biomes().isEmpty())) { || terrain == PortAgeTerrain.CAVE && !biomePlan.biomes().isEmpty())) {
source = authoredBiomeSource(server, biomePlan, seed); source = authoredBiomeSource(server, biomePlan, seed);
} }
@@ -615,10 +622,17 @@ public final class RuntimeAgeBackend {
.getOrThrow(NoiseGeneratorSettings.AMPLIFIED); .getOrThrow(NoiseGeneratorSettings.AMPLIFIED);
case ISLAND -> server.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS) case ISLAND -> server.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS)
.getOrThrow(NoiseGeneratorSettings.FLOATING_ISLANDS); .getOrThrow(NoiseGeneratorSettings.FLOATING_ISLANDS);
case CAVE -> dryCaveSettings(server); case CAVE -> biomePlan != null
&& biomePlan.nativeKind() == NativeBiomeKind.NETHER
? server.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS)
.getOrThrow(NoiseGeneratorSettings.CAVES)
: dryCaveSettings(server);
case FLAT, VOID -> throw new IllegalStateException("Flat terrain should use FlatLevelSource"); case FLAT, VOID -> throw new IllegalStateException("Flat terrain should use FlatLevelSource");
}; };
generator = new NoiseBasedChunkGenerator(source, PortBiomeMaterialRules.apply(server.registryAccess(), settings.value())); var nativeKind = biomePlan == null ? NativeBiomeKind.TERRAIN
: biomePlan.nativeKind();
var fluids = nativeFluidSettings(settings.value(), nativeKind);
generator = new NoiseBasedChunkGenerator(source, PortBiomeMaterialRules.apply(server.registryAccess(), fluids));
} }
generator = new PortFeatureChunkGenerator(generator, rocks, vegetation, dungeons, lakes, terrainFeatures, seed, generator = new PortFeatureChunkGenerator(generator, rocks, vegetation, dungeons, lakes, terrainFeatures, seed,
terrain != PortAgeTerrain.CAVE, PortLibraryWriting.get(server).symbols(id)); terrain != PortAgeTerrain.CAVE, PortLibraryWriting.get(server).symbols(id));
@@ -654,6 +668,18 @@ public final class RuntimeAgeBackend {
} }
} }
/** Native family controls natural fluid only; authored Flooded/features run later. */
static NoiseGeneratorSettings nativeFluidSettings(NoiseGeneratorSettings base,
NativeBiomeKind kind) {
if (kind != NativeBiomeKind.NETHER
&& kind != NativeBiomeKind.END) return base;
boolean nether = kind == NativeBiomeKind.NETHER;
return new NoiseGeneratorSettings(base.noiseSettings(), base.defaultBlock(),
(nether ? Blocks.LAVA : Blocks.AIR).defaultBlockState(), base.noiseRouter(),
base.materialRule(), base.spawnTarget(), nether ? base.seaLevel() : base.noiseSettings().minY() - 1,
base.disableMobGeneration(), Optional.empty(), base.useLegacyRandomSource(), base.debugFunctions());
}
private static Holder<NoiseGeneratorSettings> dryCaveSettings(MinecraftServer server) { private static Holder<NoiseGeneratorSettings> dryCaveSettings(MinecraftServer server) {
NoiseGeneratorSettings caves = server.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS) NoiseGeneratorSettings caves = server.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS)
.getOrThrow(NoiseGeneratorSettings.CAVES).value(); .getOrThrow(NoiseGeneratorSettings.CAVES).value();
@@ -28,6 +28,7 @@ public final class AgeCatalogClient {
@SubscribeEvent @SubscribeEvent
public static void register(RegisterClientPayloadHandlersEvent event) { public static void register(RegisterClientPayloadHandlersEvent event) {
event.register(net.dnorberg.rivencraft.network.OpenDroppedBookScreenPayload.TYPE, ClientDroppedBooks::open);
event.register(net.dnorberg.rivencraft.network.BookPreviewPayload.TYPE, (payload, context) -> PortBookPreview.accept(payload)); event.register(net.dnorberg.rivencraft.network.BookPreviewPayload.TYPE, (payload, context) -> PortBookPreview.accept(payload));
event.register(net.dnorberg.rivencraft.network.WritingDeskCatalogPayload.TYPE, ClientWritingDeskCatalog::handle); event.register(net.dnorberg.rivencraft.network.WritingDeskCatalogPayload.TYPE, ClientWritingDeskCatalog::handle);
event.register(net.dnorberg.rivencraft.network.SereneAgeWhitelistPayload.TYPE, (payload, context) -> event.register(net.dnorberg.rivencraft.network.SereneAgeWhitelistPayload.TYPE, (payload, context) ->
@@ -0,0 +1,31 @@
package net.dnorberg.rivencraft.client;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.network.*;
import net.minecraft.client.Minecraft;
import net.neoforged.neoforge.client.network.ClientPacketDistributor;
import net.neoforged.neoforge.network.handling.IPayloadContext;
public final class ClientDroppedBooks {
private ClientDroppedBooks() {}
public static boolean present(DroppedBookActionPayload source) {
var mc = Minecraft.getInstance();
var entity = mc.level == null ? null : mc.level.getEntity(source.entityId());
return mc.player != null && entity instanceof net.dnorberg.rivencraft.entity.DroppedBookEntity
&& !entity.isRemoved() && entity.getUUID().equals(source.entityUuid())
&& mc.player.distanceToSqr(entity) <= 64;
}
public static void send(DroppedBookActionPayload source, DroppedBookActionPayload.Action action, String title) {
ClientPacketDistributor.sendToServer(source.action(action, title, false));
}
public static void open(OpenDroppedBookScreenPayload payload, IPayloadContext context) {
context.enqueueWork(() -> {
var source = payload.source();
if (!present(source)) return;
if (source.book().is(Rivencraft.LINKING_BOOK.get()))
Minecraft.getInstance().gui.setScreen(new PortLinkingBookScreen(source));
else if (source.book().is(Rivencraft.DESCRIPTIVE_BOOK.get()))
Minecraft.getInstance().gui.setScreen(new PortDescriptiveBookScreen(source));
});
}
}
@@ -3,14 +3,14 @@ package net.dnorberg.rivencraft.client;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import qouteall.imm_ptl.core.ClientWorldLoader; import qouteall.imm_ptl.core.ClientWorldLoader;
/** Reborn's world map is briefly unavailable during vanilla dimension replacement. */ /** The portal engine's world map is briefly unavailable during vanilla dimension replacement. */
public final class RebornPredictionAcks { public final class ImmersivePredictionAcks {
private RebornPredictionAcks() {} private ImmersivePredictionAcks() {}
public static boolean handleDuringWorldReset(ClientLevel packetLevel, int sequence) { public static boolean handleDuringWorldReset(ClientLevel packetLevel, int sequence) {
if (ClientWorldLoader.getIsInitialized()) return false; if (ClientWorldLoader.getIsInitialized()) return false;
// The old remote worlds have been discarded. Preserve the vanilla ack for // The old remote worlds have been discarded. Preserve the vanilla ack for
// the packet listener's live world until Reborn rebuilds its multiworld map. // the packet listener's live world until the portal engine rebuilds its multiworld map.
if (packetLevel != null) packetLevel.handleBlockChangedAck(sequence); if (packetLevel != null) packetLevel.handleBlockChangedAck(sequence);
return true; return true;
} }
@@ -0,0 +1,20 @@
package net.dnorberg.rivencraft.client;
import net.dnorberg.rivencraft.mixin.ViewAreaSectionAccessor;
import net.minecraft.client.renderer.ViewArea;
import net.minecraft.client.renderer.state.level.LevelRenderState;
/** Extracted section jobs may outlive the view area that originally supplied them. */
public final class ImmersiveSectionRebuilds {
private ImmersiveSectionRebuilds() {}
public static void discardUnavailable(ViewArea viewArea, LevelRenderState state) {
if (viewArea == null || state.sectionUpdateRenderStates.isEmpty()) return;
var sections = (ViewAreaSectionAccessor) viewArea;
// A missing section cannot be compiled in this view. Leave every existing
// section/job untouched, including dirty state and additional renderers.
// Newly allocated sections start dirty and use normal extraction afterward.
state.sectionUpdateRenderStates.removeIf(job ->
sections.rivencraft$getRenderSection(job.sectionNode()) == null);
}
}
@@ -30,10 +30,15 @@ public final class PortBookPreview {
private net.minecraft.resources.Identifier destination; private net.minecraft.resources.Identifier destination;
PortBookPreview(InteractionHand hand, ItemStack book, UseBookStandPayload stand) { PortBookPreview(InteractionHand hand, ItemStack book, UseBookStandPayload stand) {
this(hand, book, stand, null);
}
PortBookPreview(InteractionHand hand, ItemStack book, UseBookStandPayload stand, DroppedBookActionPayload dropped) {
var minecraft = Minecraft.getInstance(); var minecraft = Minecraft.getInstance();
request = minecraft.level == null ? null : new RequestBookPreviewPayload(session, request = minecraft.level == null ? null : new RequestBookPreviewPayload(session,
hand == InteractionHand.OFF_HAND, stand != null, minecraft.level.dimension().identifier(), hand == InteractionHand.OFF_HAND, stand != null, minecraft.level.dimension().identifier(),
stand == null ? BlockPos.ZERO : stand.pos(), book.copy()); stand == null ? BlockPos.ZERO : stand.pos(), book.copy(),
dropped == null ? null : dropped.entityUuid());
boolean enabled = ImmersiveBookPreviews.bookViewsEnabled(); boolean enabled = ImmersiveBookPreviews.bookViewsEnabled();
live = enabled ? new ImmersiveLiveBookPanel() : null; live = enabled ? new ImmersiveLiveBookPanel() : null;
if (active != null) active.close(); if (active != null) active.close();
@@ -31,6 +31,7 @@ public final class PortDescriptiveBookScreen extends Screen {
private final net.dnorberg.rivencraft.writing.DescriptiveBookPages pages; private final net.dnorberg.rivencraft.writing.DescriptiveBookPages pages;
private int pageIndex; private int pageIndex;
private net.dnorberg.rivencraft.network.UseBookStandPayload standSource; private net.dnorberg.rivencraft.network.UseBookStandPayload standSource;
private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource;
private EditBox titleInput; private EditBox titleInput;
public PortDescriptiveBookScreen(InteractionHand hand, ItemStack book) { public PortDescriptiveBookScreen(InteractionHand hand, ItemStack book) {
@@ -47,11 +48,16 @@ public final class PortDescriptiveBookScreen extends Screen {
standSource = source; standSource = source;
} }
public PortDescriptiveBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source) {
this(InteractionHand.MAIN_HAND, source.book());
droppedSource = source;
}
@Override @Override
protected void init() { protected void init() {
if (bound) { if (bound) {
linkPanel.open(hand, book, standSource); linkPanel.open(hand, book, standSource, droppedSource);
exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null); exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null || droppedSource != null);
return; return;
} }
if (standSource != null) return; if (standSource != null) return;
@@ -151,7 +157,9 @@ public final class PortDescriptiveBookScreen extends Screen {
int direction = PortLegacyBookArtwork.turnDirection(event.x() - left, event.y() - top, pageIndex, pages.lastPage()); int direction = PortLegacyBookArtwork.turnDirection(event.x() - left, event.y() - top, pageIndex, pages.lastPage());
if (direction != 0) { turnPage(direction); return true; } if (direction != 0) { turnPage(direction); return true; }
if (bound && pageIndex == 0 && PortLegacyLinkPanel.contains(event.x() - left, event.y() - top)) { if (bound && pageIndex == 0 && PortLegacyLinkPanel.contains(event.x() - left, event.y() - top)) {
if (standSource != null) ClientPacketDistributor.sendToServer(standSource); if (droppedSource != null) ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.USE, "");
else if (standSource != null) ClientPacketDistributor.sendToServer(standSource);
else ClientPacketDistributor.sendToServer(new UseDescriptiveBookPayload(hand == InteractionHand.OFF_HAND)); else ClientPacketDistributor.sendToServer(new UseDescriptiveBookPayload(hand == InteractionHand.OFF_HAND));
onClose(); onClose();
return true; return true;
@@ -187,6 +195,9 @@ public final class PortDescriptiveBookScreen extends Screen {
} }
@Override public void tick() { @Override public void tick() {
if (droppedSource != null && !ClientDroppedBooks.present(droppedSource)) {
onClose(); return;
}
if (bound) linkPanel.tick(); if (bound) linkPanel.tick();
exploration.tick(pageIndex == 0); exploration.tick(pageIndex == 0);
} }
@@ -202,7 +213,9 @@ public final class PortDescriptiveBookScreen extends Screen {
if (titleInput == null) return; if (titleInput == null) return;
String name = titleInput.getValue().strip(); String name = titleInput.getValue().strip();
if (name.isEmpty()) return; if (name.isEmpty()) return;
ClientPacketDistributor.sendToServer(new BindDescriptiveBookPayload(hand == InteractionHand.OFF_HAND, name)); if (droppedSource != null) ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.BIND, name);
else ClientPacketDistributor.sendToServer(new BindDescriptiveBookPayload(hand == InteractionHand.OFF_HAND, name));
onClose(); onClose();
} }
@@ -17,7 +17,12 @@ final class PortLegacyLinkPanel {
private PortBookPreview preview; private PortBookPreview preview;
void open(net.minecraft.world.InteractionHand hand, net.minecraft.world.item.ItemStack book, void open(net.minecraft.world.InteractionHand hand, net.minecraft.world.item.ItemStack book,
net.dnorberg.rivencraft.network.UseBookStandPayload stand) { net.dnorberg.rivencraft.network.UseBookStandPayload stand) {
if (preview == null) preview = new PortBookPreview(hand, book, stand); open(hand, book, stand, null);
}
void open(net.minecraft.world.InteractionHand hand, net.minecraft.world.item.ItemStack book,
net.dnorberg.rivencraft.network.UseBookStandPayload stand,
net.dnorberg.rivencraft.network.DroppedBookActionPayload dropped) {
if (preview == null) preview = new PortBookPreview(hand, book, stand, dropped);
} }
void close() { if (preview != null) { preview.close(); preview = null; } } void close() { if (preview != null) { preview.close(); preview = null; } }
boolean canExplore() { return preview != null && preview.canExplore(); } boolean canExplore() { return preview != null && preview.canExplore(); }
@@ -32,6 +32,7 @@ public final class PortLinkingBookScreen extends Screen {
private final PortLegacyLinkPanel linkPanel = new PortLegacyLinkPanel(); private final PortLegacyLinkPanel linkPanel = new PortLegacyLinkPanel();
private final PortBookExploration exploration = new PortBookExploration(linkPanel); private final PortBookExploration exploration = new PortBookExploration(linkPanel);
private net.dnorberg.rivencraft.network.UseBookStandPayload standSource; private net.dnorberg.rivencraft.network.UseBookStandPayload standSource;
private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource;
private EditBox titleInput; private EditBox titleInput;
public PortLinkingBookScreen(InteractionHand hand, ItemStack book) { public PortLinkingBookScreen(InteractionHand hand, ItemStack book) {
@@ -52,11 +53,16 @@ public final class PortLinkingBookScreen extends Screen {
standSource = source; standSource = source;
} }
public PortLinkingBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source) {
this(InteractionHand.MAIN_HAND, source.book());
droppedSource = source;
}
@Override @Override
protected void init() { protected void init() {
if (bound) { if (bound) {
linkPanel.open(hand, book, standSource); linkPanel.open(hand, book, standSource, droppedSource);
exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null); exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null || droppedSource != null);
return; return;
} }
if (standSource != null) return; if (standSource != null) return;
@@ -119,7 +125,9 @@ public final class PortLinkingBookScreen extends Screen {
int direction = PortLegacyBookArtwork.turnDirection(event.x() - left, event.y() - top, pageIndex, 1); int direction = PortLegacyBookArtwork.turnDirection(event.x() - left, event.y() - top, pageIndex, 1);
if (direction != 0) { turnPage(direction); return true; } if (direction != 0) { turnPage(direction); return true; }
if (bound && pageIndex == 0 && PortLegacyLinkPanel.contains(event.x() - left, event.y() - top)) { if (bound && pageIndex == 0 && PortLegacyLinkPanel.contains(event.x() - left, event.y() - top)) {
if (standSource != null) ClientPacketDistributor.sendToServer(standSource); if (droppedSource != null) ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.USE, "");
else if (standSource != null) ClientPacketDistributor.sendToServer(standSource);
else ClientPacketDistributor.sendToServer(new UseLinkingBookPayload(hand == InteractionHand.OFF_HAND)); else ClientPacketDistributor.sendToServer(new UseLinkingBookPayload(hand == InteractionHand.OFF_HAND));
onClose(); onClose();
return true; return true;
@@ -152,6 +160,9 @@ public final class PortLinkingBookScreen extends Screen {
} }
@Override public void tick() { @Override public void tick() {
if (droppedSource != null && !ClientDroppedBooks.present(droppedSource)) {
onClose(); return;
}
if (bound) linkPanel.tick(); if (bound) linkPanel.tick();
exploration.tick(pageIndex == 0); exploration.tick(pageIndex == 0);
} }
@@ -167,7 +178,9 @@ public final class PortLinkingBookScreen extends Screen {
if (titleInput == null) return; if (titleInput == null) return;
String name = titleInput.getValue().strip(); String name = titleInput.getValue().strip();
if (name.isEmpty()) return; if (name.isEmpty()) return;
ClientPacketDistributor.sendToServer(new BindLinkingBookPayload(hand == InteractionHand.OFF_HAND, name)); if (droppedSource != null) ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.BIND, name);
else ClientPacketDistributor.sendToServer(new BindLinkingBookPayload(hand == InteractionHand.OFF_HAND, name));
onClose(); onClose();
} }
@@ -14,18 +14,20 @@ import net.minecraft.client.renderer.item.ItemStackRenderState;
import net.minecraft.client.renderer.state.level.CameraRenderState; import net.minecraft.client.renderer.state.level.CameraRenderState;
import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack; import net.dnorberg.rivencraft.shared.WritingDeskDisplayModel;
import net.minecraft.world.item.Items; import net.minecraft.resources.Identifier;
import net.minecraft.client.renderer.rendertype.RenderTypes;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
/** The existing selected-page and white-paper display, extracted for 26.3. */ /** The existing selected-page and white-paper display, extracted for 26.3. */
public final class WritingDeskRenderer implements BlockEntityRenderer<WritingDeskBlockEntity, WritingDeskRenderer.State> { public final class WritingDeskRenderer implements BlockEntityRenderer<WritingDeskBlockEntity, WritingDeskRenderer.State> {
private static final Identifier TEXTURE = Identifier.fromNamespaceAndPath(
"rivencraft", "textures/block/writing_desk.png");
private final ItemModelResolver resolver; private final ItemModelResolver resolver;
public WritingDeskRenderer(BlockEntityRendererProvider.Context context) { resolver = context.itemModelResolver(); } public WritingDeskRenderer(BlockEntityRendererProvider.Context context) { resolver = context.itemModelResolver(); }
public static final class State extends BlockEntityRenderState { public static final class State extends BlockEntityRenderState {
final ItemStackRenderState paper = new ItemStackRenderState();
final ItemStackRenderState page = new ItemStackRenderState(); final ItemStackRenderState page = new ItemStackRenderState();
int layers; int paperCount;
float rotation; float rotation;
} }
@Override public State createRenderState() { return new State(); } @Override public State createRenderState() { return new State(); }
@@ -33,18 +35,31 @@ public final class WritingDeskRenderer implements BlockEntityRenderer<WritingDes
Vec3 camera, ModelFeatureRenderer.CrumblingOverlay overlay) { Vec3 camera, ModelFeatureRenderer.CrumblingOverlay overlay) {
BlockEntityRenderer.super.extractRenderState(desk, state, partialTick, camera, overlay); BlockEntityRenderer.super.extractRenderState(desk, state, partialTick, camera, overlay);
int count = desk.getItem(WritingDeskBlockEntity.PAPER).getCount(); int count = desk.getItem(WritingDeskBlockEntity.PAPER).getCount();
state.layers = count == 0 ? 0 : Math.min(4, 1 + count / 16); state.paperCount = count;
state.rotation = 180 - desk.getBlockState().getValue(WritingDeskBlock.FACING).toYRot(); state.rotation = 180 - desk.getBlockState().getValue(WritingDeskBlock.FACING).toYRot();
resolver.updateForTopItem(state.paper, new ItemStack(Items.PAPER), ItemDisplayContext.FIXED, desk.getLevel(), null, 0);
resolver.updateForTopItem(state.page, desk.displayPage(), ItemDisplayContext.FIXED, desk.getLevel(), null, 0); resolver.updateForTopItem(state.page, desk.displayPage(), ItemDisplayContext.FIXED, desk.getLevel(), null, 0);
} }
@Override public void submit(State state, PoseStack pose, SubmitNodeCollector collector, CameraRenderState camera) { @Override public void submit(State state, PoseStack pose, SubmitNodeCollector collector, CameraRenderState camera) {
pose.pushPose(); pose.pushPose();
pose.translate(0.5, 0, 0.5); pose.translate(0.5, 0, 0.5);
pose.rotateDegrees(Axis.YP, state.rotation); pose.rotateDegrees(Axis.YP, state.rotation);
for (int i = 0; i < state.layers; i++) draw(state.paper, pose, collector, state.lightCoords, var faces = WritingDeskDisplayModel.paper(state.paperCount);
1.22, 0.27 + i * 0.008, -0.14, 0.55F); if (!faces.isEmpty()) {
if (!state.page.isEmpty()) draw(state.page, pose, collector, state.lightCoords, 1.0, 0.572, 0, 0.8F); int light = state.lightCoords;
collector.submitCustomGeometry(pose, RenderTypes.entitySolid(TEXTURE), (matrix, vertices) -> {
for (var face : faces) {
for (var vertex : face.vertices()) {
vertices.addVertex(matrix, vertex.x(), vertex.y(), vertex.z())
.setColor(face.color()).setUv(vertex.u(), vertex.v())
.setOverlay(OverlayTexture.NO_OVERLAY).setLight(light)
.setNormal(matrix, face.nx(), face.ny(), face.nz());
}
}
});
}
if (!state.page.isEmpty()) draw(state.page, pose, collector, state.lightCoords,
WritingDeskDisplayModel.PAGE_X, WritingDeskDisplayModel.PAGE_Y,
WritingDeskDisplayModel.PAGE_Z, WritingDeskDisplayModel.PAGE_SCALE);
pose.popPose(); pose.popPose();
} }
private static void draw(ItemStackRenderState item, PoseStack pose, SubmitNodeCollector collector, private static void draw(ItemStackRenderState item, PoseStack pose, SubmitNodeCollector collector,
@@ -40,6 +40,7 @@ final class ImmersivePreviewChunks {
if (previous != null && previous.session().equals(request.session()) if (previous != null && previous.session().equals(request.session())
&& previous.source().offhand() == request.offhand() && previous.source().offhand() == request.offhand()
&& previous.source().fromStand() == request.fromStand() && previous.source().fromStand() == request.fromStand()
&& java.util.Objects.equals(previous.source().droppedBook(), request.droppedBook())
&& previous.source().sourceDimension().equals(request.sourceDimension()) && previous.source().sourceDimension().equals(request.sourceDimension())
&& previous.source().standPos().equals(request.standPos()) && previous.source().standPos().equals(request.standPos())
&& ItemStack.matches(previous.source().book(), request.book())) { && ItemStack.matches(previous.source().book(), request.book())) {
@@ -80,6 +81,13 @@ final class ImmersivePreviewChunks {
private static ItemStack validated(ServerPlayer player, RequestBookPreviewPayload request) { private static ItemStack validated(ServerPlayer player, RequestBookPreviewPayload request) {
if (!player.level().dimension().identifier().equals(request.sourceDimension()) || !player.isAlive()) return ItemStack.EMPTY; if (!player.level().dimension().identifier().equals(request.sourceDimension()) || !player.isAlive()) return ItemStack.EMPTY;
if (request.droppedBook() != null) {
var entity = player.level().getEntity(request.droppedBook());
if (!(entity instanceof net.dnorberg.rivencraft.entity.DroppedBookEntity dropped)) return ItemStack.EMPTY;
var validated = net.dnorberg.rivencraft.entity.DroppedBookEntity.validated(
player, dropped.getId(), request.droppedBook(), request.book());
return validated == null ? ItemStack.EMPTY : validated.getItem();
}
if (request.fromStand()) return PortBookNetworking.validatedStandBook(player, if (request.fromStand()) return PortBookNetworking.validatedStandBook(player,
new net.dnorberg.rivencraft.network.UseBookStandPayload(request.sourceDimension(), request.standPos(), request.book())); new net.dnorberg.rivencraft.network.UseBookStandPayload(request.sourceDimension(), request.standPos(), request.book()));
ItemStack held = player.getItemInHand(request.offhand() ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND); ItemStack held = player.getItemInHand(request.offhand() ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND);
@@ -37,6 +37,37 @@ public final class DroppedBookEntity extends ItemEntity {
return book; return book;
} }
/** Contact must never take a book away from its world GUI. */
@Override public void playerTouch(net.minecraft.world.entity.player.Player player) {}
@Override public boolean isPickable() { return !isRemoved() && !getItem().isEmpty(); }
@Override
public net.minecraft.world.InteractionResult interact(net.minecraft.world.entity.player.Player player,
net.minecraft.world.InteractionHand hand, Vec3 hit) {
if (level().isClientSide()) return net.minecraft.world.InteractionResult.SUCCESS;
if (!(player instanceof net.minecraft.server.level.ServerPlayer serverPlayer)
|| !player.isAlive() || player.isSpectator() || player.distanceToSqr(this) > 64
|| isRemoved() || getItem().isEmpty()) return net.minecraft.world.InteractionResult.PASS;
if (player.isShiftKeyDown()) {
// Explicit interaction uses normal ownership, delay, inventory and NeoForge pickup hooks.
super.playerTouch(player);
} else {
net.dnorberg.rivencraft.network.PortBookNetworking.openDroppedBook(serverPlayer, this);
}
return net.minecraft.world.InteractionResult.SUCCESS;
}
/** Only the nearby, still-present world book can authorize an action or preview. */
public static DroppedBookEntity validated(net.minecraft.server.level.ServerPlayer player,
int id, java.util.UUID uuid, ItemStack expected) {
var entity = player.level().getEntity(id);
return player.isAlive() && !player.isSpectator()
&& entity instanceof DroppedBookEntity book && !book.isRemoved() && !book.getItem().isEmpty() && book.isAddedToLevel()
&& book.getUUID().equals(uuid) && player.distanceToSqr(book) <= 64
&& ItemStack.matches(book.getItem(), expected) ? book : null;
}
@Override @Override
public void tick() { public void tick() {
super.tick(); super.tick();
@@ -1,6 +1,6 @@
package net.dnorberg.rivencraft.mixin; package net.dnorberg.rivencraft.mixin;
import net.dnorberg.rivencraft.client.RebornPredictionAcks; import net.dnorberg.rivencraft.client.ImmersivePredictionAcks;
import net.dnorberg.rivencraft.compat.ImmersiveBookPreviews; import net.dnorberg.rivencraft.compat.ImmersiveBookPreviews;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
@@ -12,15 +12,15 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** Keep transitional acks out of Reborn's initialized-world assertion. */ /** Keep transitional acks out of the portal engine's initialized-world assertion. */
@Mixin(value = ClientPacketListener.class, priority = 2000) @Mixin(value = ClientPacketListener.class, priority = 2000)
public abstract class RebornBlockAckMixin { public abstract class ImmersiveBlockAckMixin {
@Shadow private ClientLevel level; @Shadow private ClientLevel level;
@Inject(method = "handleBlockChangedAck", at = @At("HEAD"), cancellable = true) @Inject(method = "handleBlockChangedAck", at = @At("HEAD"), cancellable = true)
private void rivencraft$ackDuringWorldReset(ClientboundBlockChangedAckPacket packet, CallbackInfo callback) { private void rivencraft$ackDuringWorldReset(ClientboundBlockChangedAckPacket packet, CallbackInfo callback) {
// Off-thread packets must reach vanilla's normal scheduling path first. // Off-thread packets must reach vanilla's normal scheduling path first.
if (Minecraft.getInstance().isSameThread() && ImmersiveBookPreviews.reborn() if (Minecraft.getInstance().isSameThread() && ImmersiveBookPreviews.available()
&& RebornPredictionAcks.handleDuringWorldReset(level, packet.sequence())) callback.cancel(); && ImmersivePredictionAcks.handleDuringWorldReset(level, packet.sequence())) callback.cancel();
} }
} }
@@ -0,0 +1,26 @@
package net.dnorberg.rivencraft.mixin;
import net.dnorberg.rivencraft.client.ImmersiveSectionRebuilds;
import net.dnorberg.rivencraft.compat.ImmersiveBookPreviews;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.ViewArea;
import net.minecraft.client.renderer.state.level.CameraRenderState;
import net.minecraft.client.renderer.state.level.LevelRenderState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Final;
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.CallbackInfo;
@Mixin(value = LevelRenderer.class, priority = 2000)
public abstract class ImmersiveSectionRebuildMixin {
@Shadow private ViewArea viewArea;
@Shadow @Final private LevelRenderState levelRenderState;
@Inject(method = "compileSections", at = @At("HEAD"))
private void rivencraft$discardUnavailableSections(CameraRenderState camera, CallbackInfo callback) {
if (ImmersiveBookPreviews.available())
ImmersiveSectionRebuilds.discardUnavailable(viewArea, levelRenderState);
}
}
@@ -0,0 +1,13 @@
package net.dnorberg.rivencraft.mixin;
import java.util.List;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.TickingBlockEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(Level.class)
public interface LevelBlockEntityTickersAccessor {
@Accessor("blockEntityTickers")
List<TickingBlockEntity> rivencraft$blockEntityTickers();
}
@@ -0,0 +1,12 @@
package net.dnorberg.rivencraft.mixin;
import net.minecraft.client.renderer.ViewArea;
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(ViewArea.class)
public interface ViewAreaSectionAccessor {
@Invoker("getRenderSection")
SectionRenderDispatcher.RenderSection rivencraft$getRenderSection(long sectionNode);
}
@@ -0,0 +1,29 @@
package net.dnorberg.rivencraft.network;
import java.util.UUID;
import net.dnorberg.rivencraft.Rivencraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
import net.minecraft.world.item.ItemStack;
/** The stack is an expected identity, never an authoritative destination. */
public record DroppedBookActionPayload(int entityId, UUID entityUuid, ItemStack book,
Action action, String title, boolean immersive) implements CustomPacketPayload {
public enum Action { USE, BIND, PREVIEW }
public static final Type<DroppedBookActionPayload> TYPE = new Type<>(
Identifier.fromNamespaceAndPath(Rivencraft.MOD_ID, "dropped_book_action"));
public static final StreamCodec<RegistryFriendlyByteBuf, DroppedBookActionPayload> STREAM_CODEC =
StreamCodec.of((buf, value) -> {
buf.writeVarInt(value.entityId()); buf.writeUUID(value.entityUuid());
ItemStack.STREAM_CODEC.encode(buf, value.book()); buf.writeEnum(value.action());
buf.writeUtf(value.title(), 32); buf.writeBoolean(value.immersive());
}, buf -> new DroppedBookActionPayload(buf.readVarInt(), buf.readUUID(),
ItemStack.STREAM_CODEC.decode(buf), buf.readEnum(Action.class),
buf.readUtf(32), buf.readBoolean()));
public DroppedBookActionPayload action(Action action, String title, boolean immersive) {
return new DroppedBookActionPayload(entityId, entityUuid, book.copy(), action, title, immersive);
}
@Override public Type<? extends CustomPacketPayload> type() { return TYPE; }
}
@@ -0,0 +1,16 @@
package net.dnorberg.rivencraft.network;
import net.dnorberg.rivencraft.Rivencraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
public record OpenDroppedBookScreenPayload(DroppedBookActionPayload source) implements CustomPacketPayload {
public static final Type<OpenDroppedBookScreenPayload> TYPE = new Type<>(
Identifier.fromNamespaceAndPath(Rivencraft.MOD_ID,"open_dropped_book"));
public static final StreamCodec<RegistryFriendlyByteBuf, OpenDroppedBookScreenPayload> STREAM_CODEC =
StreamCodec.of((buf,value)->{ DroppedBookActionPayload.STREAM_CODEC.encode(buf,value.source()); },
buf->new OpenDroppedBookScreenPayload(DroppedBookActionPayload.STREAM_CODEC.decode(buf)));
@Override public Type<? extends CustomPacketPayload> type() { return TYPE; }
}
@@ -32,7 +32,12 @@ public final class PortBookNetworking {
} }
public static void registerPayloads(RegisterPayloadHandlersEvent event) { public static void registerPayloads(RegisterPayloadHandlersEvent event) {
var registrar = event.registrar("1"); var registrar = event.registrar("2");
registrar.playToClient(OpenDroppedBookScreenPayload.TYPE, OpenDroppedBookScreenPayload.STREAM_CODEC);
registrar.playToServer(DroppedBookActionPayload.TYPE, DroppedBookActionPayload.STREAM_CODEC,
(payload, context) -> {
if (context.player() instanceof ServerPlayer player) droppedBookAction(player, payload);
});
registrar.playToClient(BookPreviewPayload.TYPE, BookPreviewPayload.STREAM_CODEC); registrar.playToClient(BookPreviewPayload.TYPE, BookPreviewPayload.STREAM_CODEC);
registrar.playToServer(RequestBookPreviewPayload.TYPE, RequestBookPreviewPayload.STREAM_CODEC, registrar.playToServer(RequestBookPreviewPayload.TYPE, RequestBookPreviewPayload.STREAM_CODEC,
(payload, context) -> { (payload, context) -> {
@@ -96,9 +101,12 @@ public final class PortBookNetworking {
} }
private static void bind(ServerPlayer player, BindLinkingBookPayload payload) { private static void bind(ServerPlayer player, BindLinkingBookPayload payload) {
ItemStack stack = player.getItemInHand(hand(payload.offhand())); bindLinking(player, player.getItemInHand(hand(payload.offhand())), payload.title());
}
private static void bindLinking(ServerPlayer player, ItemStack stack, String requestedTitle) {
if (!stack.is(Rivencraft.LINKING_BOOK.get()) || stack.has(Rivencraft.LINK_BOOK_TARGET.get())) return; if (!stack.is(Rivencraft.LINKING_BOOK.get()) || stack.has(Rivencraft.LINK_BOOK_TARGET.get())) return;
String title = payload.title().strip(); String title = requestedTitle.strip();
if (title.isEmpty() || title.length() > MAX_BOOK_TITLE_LENGTH) return; if (title.isEmpty() || title.length() > MAX_BOOK_TITLE_LENGTH) return;
stack.set(Rivencraft.LINK_BOOK_TARGET.get(), LinkBookTarget.at(player)); stack.set(Rivencraft.LINK_BOOK_TARGET.get(), LinkBookTarget.at(player));
stack.set(Rivencraft.LINK_DESTINATION_NAME.get(), LinkingBookItem.destinationName(player.level())); stack.set(Rivencraft.LINK_DESTINATION_NAME.get(), LinkingBookItem.destinationName(player.level()));
@@ -118,9 +126,12 @@ public final class PortBookNetworking {
} }
private static void bindAge(ServerPlayer player, BindDescriptiveBookPayload payload) { private static void bindAge(ServerPlayer player, BindDescriptiveBookPayload payload) {
ItemStack stack = player.getItemInHand(hand(payload.offhand())); bindDescriptive(player, player.getItemInHand(hand(payload.offhand())), payload.title());
}
private static void bindDescriptive(ServerPlayer player, ItemStack stack, String requestedTitle) {
if (!stack.is(Rivencraft.DESCRIPTIVE_BOOK.get()) || stack.has(Rivencraft.AGE_BOOK_ID.get())) return; if (!stack.is(Rivencraft.DESCRIPTIVE_BOOK.get()) || stack.has(Rivencraft.AGE_BOOK_ID.get())) return;
String title = payload.title().strip(); String title = requestedTitle.strip();
if (title.isEmpty() || title.length() > MAX_BOOK_TITLE_LENGTH) return; if (title.isEmpty() || title.length() > MAX_BOOK_TITLE_LENGTH) return;
Identifier id = createAge(player, title); Identifier id = createAge(player, title);
if (id == null) return; if (id == null) return;
@@ -253,6 +264,34 @@ public final class PortBookNetworking {
} }
} }
public static void openDroppedBook(ServerPlayer player, net.dnorberg.rivencraft.entity.DroppedBookEntity entity) {
var source = new DroppedBookActionPayload(entity.getId(), entity.getUUID(), entity.getItem().copy(),
DroppedBookActionPayload.Action.USE, "", false);
net.neoforged.neoforge.network.PacketDistributor.sendToPlayer(player, new OpenDroppedBookScreenPayload(source));
}
public static void droppedBookAction(ServerPlayer player, DroppedBookActionPayload payload) {
var entity = net.dnorberg.rivencraft.entity.DroppedBookEntity.validated(
player, payload.entityId(), payload.entityUuid(), payload.book());
if (entity == null) return;
var stack = entity.getItem();
switch (payload.action()) {
case USE -> {
if (stack.is(Rivencraft.LINKING_BOOK.get())) {
String failure = LinkingBookItem.travel(player, stack);
if (failure != null) player.sendOverlayMessage(Component.literal(failure));
else net.dnorberg.rivencraft.advancement.ProgressionAdvancements.awardAgeTravel(player);
} else if (stack.is(Rivencraft.DESCRIPTIVE_BOOK.get())) travelDescriptive(player, stack, null);
}
case BIND -> {
if (stack.is(Rivencraft.LINKING_BOOK.get())) bindLinking(player, stack, payload.title());
else if (stack.is(Rivencraft.DESCRIPTIVE_BOOK.get())) bindDescriptive(player, stack, payload.title());
entity.setItem(stack.copy());
}
case PREVIEW -> { /* Live views use the existing session-bound preview request. */ }
}
}
private static InteractionHand hand(boolean offhand) { private static InteractionHand hand(boolean offhand) {
return offhand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND; return offhand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;
} }
@@ -9,16 +9,23 @@ import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier; import net.minecraft.resources.Identifier;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
/** The server verifies the actual held/stand book, never a client-supplied destination. */ /** The server verifies the actual held, stand or dropped book, never a client-supplied destination. */
public record RequestBookPreviewPayload(UUID session, boolean offhand, boolean fromStand, public record RequestBookPreviewPayload(UUID session, boolean offhand, boolean fromStand,
Identifier sourceDimension, BlockPos standPos, ItemStack book) implements CustomPacketPayload { Identifier sourceDimension, BlockPos standPos, ItemStack book, UUID droppedBook) implements CustomPacketPayload {
public RequestBookPreviewPayload(UUID session, boolean offhand, boolean fromStand,
Identifier dimension, BlockPos pos, ItemStack book) {
this(session, offhand, fromStand, dimension, pos, book, null);
}
public static final Type<RequestBookPreviewPayload> TYPE = new Type<>(Identifier.fromNamespaceAndPath(Rivencraft.MOD_ID, "request_book_preview")); public static final Type<RequestBookPreviewPayload> TYPE = new Type<>(Identifier.fromNamespaceAndPath(Rivencraft.MOD_ID, "request_book_preview"));
public static final StreamCodec<RegistryFriendlyByteBuf, RequestBookPreviewPayload> STREAM_CODEC = StreamCodec.of( public static final StreamCodec<RegistryFriendlyByteBuf, RequestBookPreviewPayload> STREAM_CODEC = StreamCodec.of(
(buf, value) -> { (buf, value) -> {
buf.writeUUID(value.session()); buf.writeBoolean(value.offhand()); buf.writeBoolean(value.fromStand()); buf.writeUUID(value.session()); buf.writeBoolean(value.offhand()); buf.writeBoolean(value.fromStand());
Identifier.STREAM_CODEC.encode(buf, value.sourceDimension()); Identifier.STREAM_CODEC.encode(buf, value.sourceDimension());
BlockPos.STREAM_CODEC.encode(buf, value.standPos()); ItemStack.STREAM_CODEC.encode(buf, value.book()); BlockPos.STREAM_CODEC.encode(buf, value.standPos()); ItemStack.STREAM_CODEC.encode(buf, value.book());
buf.writeBoolean(value.droppedBook() != null);
if (value.droppedBook() != null) buf.writeUUID(value.droppedBook());
}, buf -> new RequestBookPreviewPayload(buf.readUUID(), buf.readBoolean(), buf.readBoolean(), }, buf -> new RequestBookPreviewPayload(buf.readUUID(), buf.readBoolean(), buf.readBoolean(),
Identifier.STREAM_CODEC.decode(buf), BlockPos.STREAM_CODEC.decode(buf), ItemStack.STREAM_CODEC.decode(buf))); Identifier.STREAM_CODEC.decode(buf), BlockPos.STREAM_CODEC.decode(buf), ItemStack.STREAM_CODEC.decode(buf),
buf.readBoolean() ? buf.readUUID() : null));
@Override public Type<RequestBookPreviewPayload> type() { return TYPE; } @Override public Type<RequestBookPreviewPayload> type() { return TYPE; }
} }
@@ -0,0 +1,23 @@
{
"minecraft_version": "26.3",
"source_sample_count": 1024,
"source_sha256": "07a9989118b5079f75e9c03d04126b82509555082829a8f610481add9740a162",
"blocks_per_chunk": {
"minecraft:coal_ore": 95.7587890625,
"minecraft:deepslate_coal_ore": 0.642578125,
"minecraft:deepslate_diamond_ore": 24.1845703125,
"minecraft:deepslate_emerald_ore": 0.03125,
"minecraft:deepslate_gold_ore": 21.470703125,
"minecraft:deepslate_iron_ore": 24.6806640625,
"minecraft:deepslate_lapis_ore": 13.30078125,
"minecraft:deepslate_redstone_ore": 32.9697265625,
"minecraft:diamond_ore": 0.4580078125,
"minecraft:emerald_ore": 0.6337890625,
"minecraft:gold_ore": 4.158203125,
"minecraft:iron_ore": 51.85546875,
"minecraft:lapis_ore": 11.046875,
"minecraft:raw_iron_block": 0.0390625,
"minecraft:redstone_ore": 3.0068359375,
"rivencraft:crystal_block": 0.015625
}
}
@@ -12,14 +12,17 @@
"AgeDayTimelineMixin", "AgeDayTimelineMixin",
"RuinsDimensionMixin", "RuinsDimensionMixin",
"RuinsTemplateDimensionMixin", "RuinsTemplateDimensionMixin",
"RuinsAttemptMixin" "RuinsAttemptMixin",
"LevelBlockEntityTickersAccessor"
], ],
"client": [ "client": [
"StaticSkyStateMixin", "StaticSkyStateMixin",
"StaticSkyRendererMixin", "StaticSkyRendererMixin",
"ImmersiveGuiRenderingMixin", "ImmersiveGuiRenderingMixin",
"ClientLevelSoundMixin", "ClientLevelSoundMixin",
"RebornBlockAckMixin" "ImmersiveBlockAckMixin",
"ViewAreaSectionAccessor",
"ImmersiveSectionRebuildMixin"
], ],
"injectors": { "injectors": {
"defaultRequire": 1 "defaultRequire": 1
@@ -0,0 +1,162 @@
package net.dnorberg.rivencraft.regression;
import java.util.List;
import java.util.UUID;
import net.dnorberg.rivencraft.entity.DroppedBookEntity;
import net.dnorberg.rivencraft.registry.*;
import net.dnorberg.rivencraft.book.*;
import net.dnorberg.rivencraft.writing.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.GlobalPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.*;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.phys.*;
import net.neoforged.bus.api.*;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
@EventBusSubscriber(modid="rivencraft")
public class BookDropProbe {
static int checks, wait, stage;
static boolean cancelReplacement;
static ServerLevel level;
static final UUID OWNER=UUID.fromString("cc5909e5-aafa-43d6-b841-a917ec9c0115");
static final AABB AREA=new AABB(-16,0,-16,32,100,32);
static void check(boolean value,String label) { if(!value)throw new AssertionError(label);checks++; }
static ItemStack book(boolean descriptive,String name) {
var stack=new ItemStack(descriptive?ModItems.DESCRIPTIVE_BOOK.get():ModItems.LINKING_BOOK.get());
stack.set(DataComponents.CUSTOM_NAME,Component.literal(name));return stack;
}
@SubscribeEvent(priority=EventPriority.HIGHEST)
public static void cancel(EntityJoinLevelEvent event) {
if(event.getLevel()!=level || !(event.getEntity() instanceof ItemEntity item))return;
String name=item.getItem().getHoverName().getString();
if(name.equals("cancel_original") || cancelReplacement && item instanceof DroppedBookEntity
&& name.equals("cancel_preserve"))event.setCanceled(true);
}
@SubscribeEvent public static void start(ServerStartedEvent event) {
level=event.getServer().overworld();level.setChunkForced(0,0,true);wait=5;
}
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
if(wait<=0 || --wait!=0)return;
try {
if(stage==0) { create();stage=1;wait=3; }
else if(stage==1) { verify();stage=2;wait=3; }
else { check(find("retry_after_reload") instanceof DroppedBookEntity,"Canceled replacement converts after reload");
System.out.println("DROP114_PASS checks="+checks);event.getServer().halt(false); }
} catch(Throwable error) { System.out.println("DROP114_FAIL "+error);error.printStackTrace();event.getServer().halt(false); }
}
static void create() {
for(int x=0;x<16;x++)for(int z=0;z<16;z++)level.setBlock(new BlockPos(x,63,z),Blocks.STONE.defaultBlockState(),2);
var player=net.neoforged.neoforge.common.util.FakePlayerFactory.get(level,
new com.mojang.authlib.GameProfile(UUID.randomUUID(),"RivenDropProbe"));
player.setPos(8.5,64,8.5);
var stack=book(false,"state_copy");stack.setCount(3);
stack.set(ModDataComponents.LINK_TARGET.get(),new LinkTarget(GlobalPos.of(level.dimension(),new BlockPos(-1,64,-2)),135,-20));
stack.set(ModDataComponents.LINK_DESTINATION_NAME.get(),"Named destination");
stack.set(ModDataComponents.LINK_PROPERTIES.get(),new LinkProperties(LinkProperties.DISARM|LinkProperties.MAINTAIN_MOMENTUM));
stack.set(ModDataComponents.AGE_REFERENCE.get(),new AgeReference(UUID.randomUUID(),"Authored Age"));
stack.set(ModDataComponents.BOOK_AUTHOR.get(),"Test author");
stack.set(ModDataComponents.BOOK_WRITING.get(),new OrderedWriting(List.of(WritingEntry.linkPanel(),
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:terrain/flat"))))));
var source=new ItemEntity(level,8.5,66,8.5,stack);
source.setTarget(OWNER);source.setThrower(player);source.setPickUpDelay(80);
source.setDeltaMovement(12.5,.1,-13.25);source.setYRot(37);source.setXRot(12);
source.setNoGravity(true);source.setInvulnerable(true);source.addTag("drop_probe");
source.getPersistentData().putString("test_attachment","kept");
var copy=DroppedBookEntity.fromDrop(source);
check(copy.position().equals(source.position()) && copy.getDeltaMovement().equals(source.getDeltaMovement()),"No departure offset or motion reset");
check(copy.getYRot()==37 && copy.getXRot()==12 && copy.isNoGravity() && copy.isInvulnerable(),"Rotation and entity flags");
check(ItemStack.matches(source.getItem(),copy.getItem()) && copy.getItem().getCount()==3,"All components and count");
check(!copy.getUUID().equals(source.getUUID()) && copy.getAge()==-32768,"Fresh identity and open-book lifetime");
check(copy.copy() instanceof DroppedBookEntity && copy.copy().getType()==ModEntities.DROPPED_BOOK.get(),"Pickup-particle copy retains custom renderer type");
CompoundTag original=source.saveWithoutId(new CompoundTag()),saved=copy.saveWithoutId(new CompoundTag());
for(String key:original.getAllKeys()) {
if(key.equals("UUID") || key.equals("Age"))continue;
check(java.util.Objects.equals(original.get(key),saved.get(key)),"Native metadata retained: "+key);
}
var restored=new DroppedBookEntity(ModEntities.DROPPED_BOOK.get(),level);
restored.load(saved);
check(ItemStack.matches(restored.getItem(),copy.getItem()) && OWNER.equals(restored.getTarget()),"Custom entity NBT reload");
for(String name:List.of("bound_link","bound_description","unwritten_link","unwritten_description")) {
var item=book(name.endsWith("description"),name);
if(name.equals("bound_link")) {
item.set(ModDataComponents.LINK_TARGET.get(),stack.get(ModDataComponents.LINK_TARGET.get()));
item.set(ModDataComponents.LINK_DESTINATION_NAME.get(),"Named destination");
}
if(name.equals("bound_description"))item.set(ModDataComponents.AGE_REFERENCE.get(),stack.get(ModDataComponents.AGE_REFERENCE.get()));
spawn(item);
}
player.drop(book(false,"player_toss"),false);
net.minecraft.world.Containers.dropItemStack(level,8.5,65,8.5,book(true,"container"));
var stand=new BlockPos(10,64,8);
level.setBlock(stand,ModBlocks.BOOK_STAND.get().defaultBlockState(),3);
((net.dnorberg.rivencraft.block.entity.BookStandBlockEntity)level.getBlockEntity(stand)).setBook(book(false,"stand_break"));
level.destroyBlock(stand,true);
for(int slot=0;slot<36;slot++)player.getInventory().setItem(slot,new ItemStack(Items.STONE,64));
stand=new BlockPos(11,64,8);
level.setBlock(stand,ModBlocks.BOOK_STAND.get().defaultBlockState(),3);
((net.dnorberg.rivencraft.block.entity.BookStandBlockEntity)level.getBlockEntity(stand)).setBook(book(false,"full_inventory"));
player.setShiftKeyDown(true);
level.getBlockState(stand).useWithoutItem(level,player,new BlockHitResult(Vec3.atCenterOf(stand),net.minecraft.core.Direction.UP,stand,false));
player.setShiftKeyDown(false);player.getInventory().clearContent();
player.getInventory().setItem(0,book(false,"disarm"));
LinkDisarmService.disarm(player);
check(player.getInventory().getItem(0).isEmpty(),"Disarm emptied book slot");
player.getInventory().setItem(0,book(true,"inventory_death_path"));
player.getInventory().dropAll();
var modifier=new BlockPos(12,64,8);
level.setBlock(modifier,ModBlocks.LINK_MODIFIER.get().defaultBlockState(),3);
((net.dnorberg.rivencraft.block.entity.LinkModifierBlockEntity)level.getBlockEntity(modifier)).setItem(0,book(false,"station"));
level.destroyBlock(modifier,true);
var custom=new DroppedBookEntity(level,new Vec3(8.5,66,8.5),book(false,"already_custom"));
custom.setNoGravity(true);level.addFreshEntity(custom);
for(var item:List.of(ModItems.PAGE.get(),ModItems.NOTEBOOK.get(),ModItems.COLLATION_FOLDER.get(),ModItems.SYMBOL_PORTFOLIO.get())) {
var ordinary=new ItemStack(item);ordinary.set(DataComponents.CUSTOM_NAME,Component.literal("ordinary_"+item.toString()));spawn(ordinary);
}
cancelReplacement=true;spawn(book(false,"cancel_preserve"));
var canceled=new ItemEntity(level,8.5,66,8.5,book(false,"cancel_original"));
check(!level.addFreshEntity(canceled),"Original spawn cancellation honored");
var loaded=new ItemEntity(level,8.5,66,8.5,book(false,"loaded_ordinary"));
var tag=loaded.saveWithoutId(new CompoundTag());
var fromDisk=new ItemEntity(EntityType.ITEM,level);fromDisk.load(tag);fromDisk.setUUID(UUID.randomUUID());
level.addFreshEntity(fromDisk);
}
static void spawn(ItemStack stack) {
var item=new ItemEntity(level,8.5,66,8.5,stack);item.setNoGravity(true);
item.setDeltaMovement(Vec3.ZERO);item.setTarget(OWNER);level.addFreshEntity(item);
}
static ItemEntity find(String name) {
var found=level.getEntitiesOfClass(ItemEntity.class,AREA).stream()
.filter(e->e.getItem().getHoverName().getString().equals(name)).toList();
check(found.size()==1,"Exactly one entity: "+name);
return found.getFirst();
}
static void verify() {
for(String name:List.of("bound_link","bound_description","unwritten_link","unwritten_description",
"player_toss","container","stand_break","full_inventory","disarm","inventory_death_path","station","already_custom","loaded_ordinary"))
check(find(name) instanceof DroppedBookEntity,"Open model: "+name);
check("Named destination".equals(find("bound_link").getItem().get(ModDataComponents.LINK_DESTINATION_NAME.get())),"Bound destination retained");
var drops=level.getEntitiesOfClass(ItemEntity.class,AREA);
check(drops.stream().filter(e->e.getItem().is(Items.LECTERN)).mapToInt(e->e.getItem().getCount()).sum()==1,"One lectern on break");
check(drops.stream().filter(e->e.getItem().getHoverName().getString().startsWith("ordinary_")).count()==4,"All non-book drops present");
check(drops.stream().noneMatch(e->e instanceof DroppedBookEntity && e.getItem().getHoverName().getString().startsWith("ordinary_")),"Pages and collections stay ordinary");
check(drops.stream().noneMatch(e->e.getItem().getHoverName().getString().equals("cancel_original")),"Canceled source produced no ghost");
var canceled=find("cancel_preserve");
check(!(canceled instanceof DroppedBookEntity),"Canceled replacement keeps source");
cancelReplacement=false;
var tag=canceled.saveWithoutId(new CompoundTag());canceled.discard();
var reloaded=new ItemEntity(EntityType.ITEM,level);reloaded.load(tag);reloaded.setUUID(UUID.randomUUID());
reloaded.getItem().set(DataComponents.CUSTOM_NAME,Component.literal("retry_after_reload"));
level.addFreshEntity(reloaded);
}
}
@@ -0,0 +1,120 @@
package net.dnorberg.rivencraft.regression;
import java.util.UUID;
import net.dnorberg.rivencraft.entity.DroppedBookEntity;
import net.dnorberg.rivencraft.network.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.RegistryFriendlyByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.*;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
import net.dnorberg.rivencraft.registry.*;
import net.dnorberg.rivencraft.book.*;
@EventBusSubscriber(modid="rivencraft")
public class DroppedInteractionProbe {
static int checks,wait;
static ServerLevel level;
static void check(boolean value,String name) { if(!value)throw new AssertionError(name);checks++; }
@SubscribeEvent public static void start(ServerStartedEvent event) {
level=event.getServer().overworld();level.setChunkForced(0,0,true);wait=5;
}
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
if(wait<=0 || --wait!=0)return;
try { run();System.out.println("DROPINTERACT_PASS checks="+checks); }
catch(Throwable e) { System.out.println("DROPINTERACT_FAIL "+e);e.printStackTrace(); }
finally { event.getServer().halt(false); }
}
static class ProbePlayer extends net.neoforged.neoforge.common.util.FakePlayer {
Vec3 requested;
ProbePlayer(ServerLevel level,com.mojang.authlib.GameProfile profile) { super(level,profile); }
@Override public void teleportTo(ServerLevel destination,double x,double y,double z,float yaw,float pitch) {
requested=new Vec3(x,y,z);setPos(x,y,z);
}
}
static void click(DroppedBookEntity book,net.minecraft.server.level.ServerPlayer player) {
book.interact(player,InteractionHand.MAIN_HAND);
}
static DroppedBookEntity spawn() {
var stack=new ItemStack(ModItems.LINKING_BOOK.get());
stack.set(DataComponents.CUSTOM_NAME,Component.literal("World book"));
var book=new DroppedBookEntity(level,new Vec3(8.5,64,8.5),stack);
book.setNoGravity(true);book.setDeltaMovement(Vec3.ZERO);book.setNoPickUpDelay();
check(level.addFreshEntity(book),"Spawn clickable book");
return book;
}
static DroppedBookActionPayload source(DroppedBookEntity book) {
return new DroppedBookActionPayload(book.getId(),book.getUUID(),book.getItem().copy(),
DroppedBookActionPayload.Action.USE,"",false);
}
static void run() throws Exception {
for(int x=0;x<16;x++)for(int z=0;z<16;z++)level.setBlock(new BlockPos(x,63,z),Blocks.STONE.defaultBlockState(),2);
var player=new ProbePlayer(level,
new com.mojang.authlib.GameProfile(UUID.randomUUID(),"RivenInteraction"));
player.setPos(8.5,64,8.5);player.getInventory().clearContent();
var book=spawn();var expected=source(book);
check(book.isPickable(),"Raycast can hit book");
book.playerTouch(player);
check(!book.isRemoved() && player.getInventory().isEmpty(),"Walking does not pick up");
player.setShiftKeyDown(false);click(book,player);
check(!book.isRemoved() && player.getInventory().isEmpty(),"Right click opens without pickup");
check(DroppedBookEntity.validated(player,book.getId(),book.getUUID(),book.getItem().copy())==book,"Valid source");
check(DroppedBookEntity.validated(player,book.getId(),UUID.randomUUID(),book.getItem())==null,"Wrong UUID rejected");
var forged=book.getItem().copy();forged.set(DataComponents.CUSTOM_NAME,Component.literal("Forged"));
check(DroppedBookEntity.validated(player,book.getId(),book.getUUID(),forged)==null,"Changed stack rejected");
player.setPos(100,64,100);
check(DroppedBookEntity.validated(player,book.getId(),book.getUUID(),book.getItem())==null,"Remote action rejected");
ModNetworking.droppedBookAction(player,expected.action(DroppedBookActionPayload.Action.BIND,"Remote",false));
check(!book.getItem().has(ModDataComponents.LINK_TARGET.get()),"Remote bind cannot mutate book");
player.setPos(8.5,64,8.5);
ModNetworking.droppedBookAction(player,source(book).action(DroppedBookActionPayload.Action.BIND,"Ground binding",false));
check(book.getItem().has(ModDataComponents.LINK_TARGET.get()) && book.getItem().getHoverName().getString().equals("Ground binding"),"Ground book binding shares normal handler");
check(DroppedBookEntity.validated(player,expected.entityId(),expected.entityUuid(),expected.book())==null,"Stale pre-bind request rejected");
book.getItem().set(ModDataComponents.LINK_TARGET.get(),new LinkTarget(net.minecraft.core.GlobalPos.of(level.dimension(),new BlockPos(14,64,14)),0,0));
book.getItem().set(ModDataComponents.LINK_PROPERTIES.get(),new LinkProperties(LinkProperties.INTRA_LINKING));
var use=source(book);
ModNetworking.droppedBookAction(player,use);
check(player.requested!=null && player.requested.x>13 && player.requested.z>13,"Ground handler requests normal link teleport");
check(!book.isRemoved() && book.getItem().getCount()==1,"Travel leaves the same world book");
player.setPos(8.5,64,8.5);
// Ownership and the original pickup delay are still enforced for explicit pickup.
player.setShiftKeyDown(true);book.setTarget(UUID.randomUUID());click(book,player);
check(!book.isRemoved() && player.getInventory().isEmpty(),"Owner restriction retained");
book.setTarget(player.getUUID());book.setPickUpDelay(80);click(book,player);
check(!book.isRemoved(),"Pickup delay retained");
book.setNoPickUpDelay();
for(int i=0;i<36;i++)player.getInventory().setItem(i,new ItemStack(Items.STONE,64));
click(book,player);
check(!book.isRemoved() && book.getItem().getCount()==1,"Full inventory keeps world book");
player.getInventory().clearContent();click(book,player);
check(book.isRemoved(),"Shift right click picks up");
check(player.getInventory().countItem(ModItems.LINKING_BOOK.get())==1,"Exactly one book recovered");
check(DroppedBookEntity.validated(player,use.entityId(),use.entityUuid(),use.book())==null,"Picked-up source invalidated");
var buffer=new RegistryFriendlyByteBuf(Unpooled.buffer(),level.registryAccess());
try {
DroppedBookActionPayload.STREAM_CODEC.encode(buffer,use);
var decoded=DroppedBookActionPayload.STREAM_CODEC.decode(buffer);
check(decoded.entityUuid().equals(use.entityUuid()) && decoded.entityId()==use.entityId()
&& decoded.action()==use.action() && ItemStack.matches(decoded.book(),use.book()) && buffer.readableBytes()==0,"Action wire round trip");
} finally { buffer.release(); }
var b=new RegistryFriendlyByteBuf(Unpooled.buffer(),level.registryAccess());
try {
var contents=new OpenDescriptiveBookScreenPayload(false,false,net.minecraft.core.GlobalPos.of(level.dimension(),BlockPos.ZERO),
use.book(),null,java.util.List.of());
OpenDroppedBookScreenPayload.STREAM_CODEC.encode(b,new OpenDroppedBookScreenPayload(use,contents));
var reply=OpenDroppedBookScreenPayload.STREAM_CODEC.decode(b);
check(reply.source().entityUuid().equals(use.entityUuid()) && ItemStack.matches(reply.contents().book(),use.book())
&& b.readableBytes()==0,"Open screen metadata round trip");
} finally { b.release(); }
}
}
@@ -0,0 +1,127 @@
package net.dnorberg.rivencraft.regression;
import java.util.UUID;
import net.dnorberg.rivencraft.entity.DroppedBookEntity;
import net.dnorberg.rivencraft.network.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.RegistryFriendlyByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.*;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
import net.dnorberg.rivencraft.Rivencraft;
@EventBusSubscriber(modid="rivencraft")
public class DroppedInteractionProbe {
static int checks,wait;
static ServerLevel level;
static void check(boolean value,String name) { if(!value)throw new AssertionError(name);checks++; }
@SubscribeEvent public static void start(ServerStartedEvent event) {
level=event.getServer().overworld();level.setChunkForced(0,0,true);wait=5;
}
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
if(wait<=0 || --wait!=0)return;
try { run();System.out.println("DROPINTERACT_PASS checks="+checks); }
catch(Throwable e) { System.out.println("DROPINTERACT_FAIL "+e);e.printStackTrace(); }
finally { event.getServer().halt(false); }
}
static class ProbePlayer extends net.neoforged.neoforge.common.util.FakePlayer {
Vec3 requested;
ProbePlayer(ServerLevel level,com.mojang.authlib.GameProfile profile) { super(level,profile); }
@Override public boolean teleportTo(ServerLevel destination,double x,double y,double z,
java.util.Set<net.minecraft.world.entity.Relative> relative,float yaw,float pitch,boolean resetCamera) {
requested=new Vec3(x,y,z);setPos(x,y,z);return true;
}
}
static void click(DroppedBookEntity book,net.minecraft.server.level.ServerPlayer player) {
book.interact(player,InteractionHand.MAIN_HAND,Vec3.ZERO);
}
static DroppedBookEntity spawn() {
var stack=new ItemStack(Rivencraft.LINKING_BOOK.get());
stack.set(DataComponents.CUSTOM_NAME,Component.literal("World book"));
var book=new DroppedBookEntity(level,new Vec3(8.5,64,8.5),stack);
book.setNoGravity(true);book.setDeltaMovement(Vec3.ZERO);book.setNoPickUpDelay();
check(level.addFreshEntity(book),"Spawn clickable book");
return book;
}
static DroppedBookActionPayload source(DroppedBookEntity book) {
return new DroppedBookActionPayload(book.getId(),book.getUUID(),book.getItem().copy(),
DroppedBookActionPayload.Action.USE,"",false);
}
static void run() throws Exception {
for(int x=0;x<16;x++)for(int z=0;z<16;z++)level.setBlock(new BlockPos(x,63,z),Blocks.STONE.defaultBlockState(),2);
var player=new ProbePlayer(level,
new com.mojang.authlib.GameProfile(UUID.randomUUID(),"RivenInteraction"));
player.setPos(8.5,64,8.5);player.getInventory().clearContent();
var book=spawn();var expected=source(book);
check(book.isPickable(),"Raycast can hit book");
book.playerTouch(player);
check(!book.isRemoved() && player.getInventory().isEmpty(),"Walking does not pick up");
player.setShiftKeyDown(false);click(book,player);
check(!book.isRemoved() && player.getInventory().isEmpty(),"Right click opens without pickup");
check(DroppedBookEntity.validated(player,book.getId(),book.getUUID(),book.getItem().copy())==book,"Valid source");
check(DroppedBookEntity.validated(player,book.getId(),UUID.randomUUID(),book.getItem())==null,"Wrong UUID rejected");
var forged=book.getItem().copy();forged.set(DataComponents.CUSTOM_NAME,Component.literal("Forged"));
check(DroppedBookEntity.validated(player,book.getId(),book.getUUID(),forged)==null,"Changed stack rejected");
player.setPos(100,64,100);
check(DroppedBookEntity.validated(player,book.getId(),book.getUUID(),book.getItem())==null,"Remote action rejected");
PortBookNetworking.droppedBookAction(player,expected.action(DroppedBookActionPayload.Action.BIND,"Remote",false));
check(!book.getItem().has(Rivencraft.LINK_BOOK_TARGET.get()),"Remote bind cannot mutate book");
player.setPos(8.5,64,8.5);
PortBookNetworking.droppedBookAction(player,source(book).action(DroppedBookActionPayload.Action.BIND,"Ground binding",false));
check(book.getItem().has(Rivencraft.LINK_BOOK_TARGET.get()) && book.getItem().getHoverName().getString().equals("Ground binding"),"Ground book binding shares normal handler");
check(DroppedBookEntity.validated(player,expected.entityId(),expected.entityUuid(),expected.book())==null,"Stale pre-bind request rejected");
book.getItem().set(Rivencraft.LINK_BOOK_TARGET.get(),new net.dnorberg.rivencraft.item.LinkBookTarget(level.dimension().identifier(),14.5,64,14.5,0,0));
book.getItem().set(Rivencraft.LINK_PROPERTIES.get(),new net.dnorberg.rivencraft.item.LinkProperties(net.dnorberg.rivencraft.item.LinkProperties.INTRA_LINKING));
var use=source(book);
PortBookNetworking.droppedBookAction(player,use);
check(player.requested==null,"Ground travel still requires catalog acknowledgement");
var stateMethod=net.dnorberg.rivencraft.age.AgeCatalogSync.class.getDeclaredMethod("state",net.minecraft.server.MinecraftServer.class);
stateMethod.setAccessible(true);var state=stateMethod.invoke(null,level.getServer());
var version=state.getClass().getDeclaredField("version");version.setAccessible(true);
var ack=net.dnorberg.rivencraft.age.AgeCatalogSync.class.getDeclaredMethod("acknowledge",net.minecraft.server.level.ServerPlayer.class,int.class);
ack.setAccessible(true);ack.invoke(null,player,version.getInt(state));
PortBookNetworking.droppedBookAction(player,use);
check(player.requested!=null && player.requested.x>13 && player.requested.z>13,"Ground handler requests normal link teleport");
check(!book.isRemoved() && book.getItem().getCount()==1,"Travel leaves the same world book");
player.setPos(8.5,64,8.5);
// Ownership and the original pickup delay are still enforced for explicit pickup.
player.setShiftKeyDown(true);book.setTarget(UUID.randomUUID());click(book,player);
check(!book.isRemoved() && player.getInventory().isEmpty(),"Owner restriction retained");
book.setTarget(player.getUUID());book.setPickUpDelay(80);click(book,player);
check(!book.isRemoved(),"Pickup delay retained");
book.setNoPickUpDelay();
for(int i=0;i<36;i++)player.getInventory().setItem(i,new ItemStack(Items.STONE,64));
click(book,player);
check(!book.isRemoved() && book.getItem().getCount()==1,"Full inventory keeps world book");
player.getInventory().clearContent();click(book,player);
check(book.isRemoved(),"Shift right click picks up");
check(player.getInventory().countItem(Rivencraft.LINKING_BOOK.get())==1,"Exactly one book recovered");
check(DroppedBookEntity.validated(player,use.entityId(),use.entityUuid(),use.book())==null,"Picked-up source invalidated");
var buffer=new RegistryFriendlyByteBuf(Unpooled.buffer(),level.registryAccess());
try {
DroppedBookActionPayload.STREAM_CODEC.encode(buffer,use);
var decoded=DroppedBookActionPayload.STREAM_CODEC.decode(buffer);
check(decoded.entityUuid().equals(use.entityUuid()) && decoded.entityId()==use.entityId()
&& decoded.action()==use.action() && ItemStack.matches(decoded.book(),use.book()) && buffer.readableBytes()==0,"Action wire round trip");
} finally { buffer.release(); }
var b=new RegistryFriendlyByteBuf(Unpooled.buffer(),level.registryAccess());
try {
for(UUID id:java.util.Arrays.asList(null,UUID.randomUUID())) {
var preview=new RequestBookPreviewPayload(UUID.randomUUID(),false,false,level.dimension().identifier(),BlockPos.ZERO,use.book(),id);
RequestBookPreviewPayload.STREAM_CODEC.encode(b,preview);
var decoded=RequestBookPreviewPayload.STREAM_CODEC.decode(b);
check(java.util.Objects.equals(decoded.droppedBook(),id) && b.readableBytes()==0,"Preview source wire round trip");
}
} finally { b.release(); }
}
}
@@ -0,0 +1,132 @@
package net.dnorberg.rivencraft.book;
import java.util.ArrayList;
import java.util.List;
import net.dnorberg.rivencraft.mixin.LevelBlockEntityTickersAccessor;
import net.dnorberg.rivencraft.shared.AcceleratedMachineWork;
import net.minecraft.core.BlockPos;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity;
import net.minecraft.world.level.block.entity.TickingBlockEntity;
import net.minecraft.world.inventory.ContainerData;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
@EventBusSubscriber(modid="rivencraft")
public class MachineProbe {
static int checks, warmup;
static void check(boolean value,String label) {
if(!value) throw new AssertionError(label);
checks++;
}
@SubscribeEvent public static void start(ServerStartedEvent event) {
event.getServer().overworld().setChunkForced(0,0,true);
warmup=5;
}
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
if(warmup<=0 || --warmup!=0) return;
event.getServer().execute(()->{
try { run(event.getServer());System.out.println("MACHINE112_PASS checks="+checks); }
catch(Throwable error) { System.out.println("MACHINE112_FAIL "+error);error.printStackTrace(); }
finally { event.getServer().halt(false); }
});
}
static class Counter implements TickingBlockEntity {
final BlockPos pos; int calls; boolean removed;
Counter(BlockPos pos) { this.pos=pos; }
public void tick() { calls++; }
public boolean isRemoved() { return removed; }
public BlockPos getPos() { return pos; }
public String getType() { return "rivencraft:test_machine"; }
}
static void run(MinecraftServer server) throws Exception {
scheduler();
ServerLevel level=server.overworld();
var registered=((LevelBlockEntityTickersAccessor)level).rivencraft$blockEntityTickers();
var near=new BlockPos(1,4,1);
check(level.hasChunkAt(near) && level.shouldTickBlocksAt(near),"Forced chunk normally ticks");
level.setBlockAndUpdate(near,Blocks.FURNACE.defaultBlockState());
var furnace=(AbstractFurnaceBlockEntity)level.getBlockEntity(near);
furnace.setItem(0,new ItemStack(Items.IRON_ORE,4));
furnace.setItem(1,new ItemStack(Items.COAL,4));
var dataField=AbstractFurnaceBlockEntity.class.getDeclaredField("dataAccess");
dataField.setAccessible(true);
var data=(ContainerData)dataField.get(furnace);
// Its ordinary registered ticker is also the one used for acceleration.
var ticker=registered.stream().filter(t->t.getPos().equals(near)).findFirst().orElseThrow();
ticker.tick();
int progress=data.get(2);
check(progress>0,"Ordinary registered furnace ticker smelts");
AgeMachineTicks.tick(level,0);
check(data.get(2)==progress,"Zero pages add no work");
AgeMachineTicks.tick(level,1);
check(data.get(2)==progress+1,"One page one extra registered furnace tick");
AgeMachineTicks.tick(level,4);
check(data.get(2)==progress+5,"Repeated pages stack");
server.tickRateManager().setFrozen(true);
AgeMachineTicks.tick(level,8);
check(data.get(2)==progress+5,"Tick freeze respected");
server.tickRateManager().setFrozen(false);
for(int i=0;i<50;i++) AgeMachineTicks.tick(level,4);
check(furnace.getItem(2).is(Items.IRON_INGOT),"Extra ticks complete real smelting recipe");
// Overworld's normal event must not enable the Age-only effect.
progress=data.get(2);
AgeInstabilityRuntime.onLevelTickPost(new net.neoforged.neoforge.event.tick.LevelTickEvent.Post(()->true,level));
check(data.get(2)==progress,"Normal Overworld not accelerated by runtime event");
level.removeBlock(near,false);
AgeMachineTicks.tick(level,8);
check(furnace.isRemoved(),"Removed furnace no longer valid");
level.setBlockAndUpdate(near,Blocks.FURNACE.defaultBlockState());
var replacement=(AbstractFurnaceBlockEntity)level.getBlockEntity(near);
replacement.setItem(0,new ItemStack(Items.IRON_ORE));
replacement.setItem(1,new ItemStack(Items.COAL));
AgeMachineTicks.tick(level,3);
var replacementData=(ContainerData)dataField.get(replacement);
check(replacement!=furnace && replacementData.get(2)==3,"Replacement uses new bound ticker");
var valid=new Counter(near);
var removed=new Counter(near);removed.removed=true;
var unloaded=new Counter(new BlockPos(50000,4,50000));
var outsideBorder=new Counter(new BlockPos(30000000,4,0));
var original=new ArrayList<>(registered);
try {
registered.clear();registered.addAll(List.of(valid,removed,unloaded,outsideBorder));
AgeMachineTicks.tick(level,3);
check(valid.calls==3,"Custom registered ticker supported");
check(removed.calls==0 && unloaded.calls==0 && outsideBorder.calls==0,"Removal unloaded and border guards");
check(!level.hasChunkAt(unloaded.getPos()),"Does not force-load machinery");
} finally { registered.clear();registered.addAll(original); }
var ids=java.util.List.of("terrain/flat","biome/plains","biome/single",
"environment/accelerated","environment/accelerated","environment/accelerated");
var entries=new ArrayList<net.dnorberg.rivencraft.writing.WritingEntry>();
entries.add(net.dnorberg.rivencraft.writing.WritingEntry.linkPanel());
for(String id:ids) entries.add(net.dnorberg.rivencraft.writing.WritingEntry.symbol(new net.dnorberg.rivencraft.writing.SymbolReference(net.minecraft.resources.ResourceLocation.parse("rivencraft:"+id))));
var plan=AgeGenerationPlan.compile(new net.dnorberg.rivencraft.writing.OrderedWriting(entries),112L,
AgeGenerationProfiles.STANDARD,AgeTraits.select(112L),server.registryAccess());
check(AgeAcceleratedTicks.acceleratedPages(plan)==3,"Repeated authored Accelerated page count");
check(AgeAcceleratedTicks.acceleratedPages(AgeGenerationPlan.load(plan.save()))==3,"Saved plan retains page count");
}
static void scheduler() {
var work=new AcceleratedMachineWork();
var list=new ArrayList<Counter>();
for(int i=0;i<5;i++)list.add(new Counter(BlockPos.ZERO));
for(int i=0;i<5;i++)check(work.run(list,20,5,2,c->!c.removed,Counter::tick)==2,"Budget cap");
check(list.stream().allMatch(c->c.calls==2),"Fair budget across repeated ticks");
work=new AcceleratedMachineWork();
list.forEach(c->c.calls=0);
for(int i=0;i<5;i++)work.run(list,1,2,20,c->true,Counter::tick);
check(list.stream().allMatch(c->c.calls==2),"Candidate window rotates fairly");
var mutating=new ArrayList<Counter>();var first=new Counter(BlockPos.ZERO);
mutating.add(first);
work.run(mutating,4,10,20,c->!c.removed,c->{c.tick();c.removed=true;mutating.clear();});
check(first.calls==1,"Removal and live list mutation safe");
check(work.run(list,10,5,0,c->true,Counter::tick)==0,"Zero machine budget");
check(work.run(list,Integer.MAX_VALUE,5,7,c->true,Counter::tick)==7,"Overflow-safe page budget");
}
}
@@ -0,0 +1,133 @@
package net.dnorberg.rivencraft.age;
import java.util.ArrayList;
import java.util.List;
import net.dnorberg.rivencraft.mixin.LevelBlockEntityTickersAccessor;
import net.dnorberg.rivencraft.shared.AcceleratedMachineWork;
import net.minecraft.core.BlockPos;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity;
import net.minecraft.world.level.block.entity.TickingBlockEntity;
import net.minecraft.world.inventory.ContainerData;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
@EventBusSubscriber(modid="rivencraft")
public class MachineProbe {
static int checks, warmup;
static void check(boolean value,String label) {
if(!value) throw new AssertionError(label);
checks++;
}
@SubscribeEvent public static void start(ServerStartedEvent event) {
event.getServer().overworld().setChunkForced(0,0,true);
warmup=5;
}
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
if(warmup<=0 || --warmup!=0) return;
event.getServer().execute(()->{
try { run(event.getServer());System.out.println("MACHINE112_PASS checks="+checks); }
catch(Throwable error) { System.out.println("MACHINE112_FAIL "+error);error.printStackTrace(); }
finally { event.getServer().halt(false); }
});
}
static class Counter implements TickingBlockEntity {
final BlockPos pos; int calls; boolean removed;
Counter(BlockPos pos) { this.pos=pos; }
public void tick() { calls++; }
public boolean isRemoved() { return removed; }
public BlockPos getPos() { return pos; }
public String getType() { return "rivencraft:test_machine"; }
}
static void run(MinecraftServer server) throws Exception {
scheduler();
ServerLevel level=server.overworld();
var registered=((LevelBlockEntityTickersAccessor)level).rivencraft$blockEntityTickers();
var near=new BlockPos(1,4,1);
check(level.hasChunkAt(near) && level.shouldTickBlocksAt(near),"Forced chunk normally ticks");
level.setBlockAndUpdate(near,Blocks.FURNACE.defaultBlockState());
var furnace=(AbstractFurnaceBlockEntity)level.getBlockEntity(near);
furnace.setItem(0,new ItemStack(Items.IRON_ORE,4));
furnace.setItem(1,new ItemStack(Items.COAL,4));
var dataField=AbstractFurnaceBlockEntity.class.getDeclaredField("dataAccess");
dataField.setAccessible(true);
var data=(ContainerData)dataField.get(furnace);
// Its ordinary registered ticker is also the one used for acceleration.
var ticker=registered.stream().filter(t->t.getPos().equals(near)).findFirst().orElseThrow();
ticker.tick();
int progress=data.get(2);
check(progress>0,"Ordinary registered furnace ticker smelts");
PortMachineTicks.tick(level,0);
check(data.get(2)==progress,"Zero pages add no work");
PortMachineTicks.tick(level,1);
check(data.get(2)==progress+1,"One page one extra registered furnace tick");
PortMachineTicks.tick(level,4);
check(data.get(2)==progress+5,"Repeated pages stack");
server.tickRateManager().setFrozen(true);
PortMachineTicks.tick(level,8);
check(data.get(2)==progress+5,"Tick freeze respected");
server.tickRateManager().setFrozen(false);
for(int i=0;i<50;i++) PortMachineTicks.tick(level,4);
check(furnace.getItem(2).is(Items.IRON_INGOT),"Extra ticks complete real smelting recipe");
// Overworld's normal event must not enable the Age-only effect.
progress=data.get(2);
PortAcceleratedTicks.onLevelTickPost(new net.neoforged.neoforge.event.tick.LevelTickEvent.Post(()->true,level));
check(data.get(2)==progress,"Normal Overworld not accelerated by runtime event");
level.removeBlock(near,false);
PortMachineTicks.tick(level,8);
check(furnace.isRemoved(),"Removed furnace no longer valid");
level.setBlockAndUpdate(near,Blocks.FURNACE.defaultBlockState());
var replacement=(AbstractFurnaceBlockEntity)level.getBlockEntity(near);
replacement.setItem(0,new ItemStack(Items.IRON_ORE));
replacement.setItem(1,new ItemStack(Items.COAL));
PortMachineTicks.tick(level,3);
var replacementData=(ContainerData)dataField.get(replacement);
check(replacement!=furnace && replacementData.get(2)==3,"Replacement uses new bound ticker");
var valid=new Counter(near);
var removed=new Counter(near);removed.removed=true;
var unloaded=new Counter(new BlockPos(50000,4,50000));
var outsideBorder=new Counter(new BlockPos(30000000,4,0));
var original=new ArrayList<>(registered);
try {
registered.clear();registered.addAll(List.of(valid,removed,unloaded,outsideBorder));
PortMachineTicks.tick(level,3);
check(valid.calls==3,"Custom registered ticker supported");
check(removed.calls==0 && unloaded.calls==0 && outsideBorder.calls==0,"Removal unloaded and border guards");
check(!level.hasChunkAt(unloaded.getPos()),"Does not force-load machinery");
} finally { registered.clear();registered.addAll(original); }
var age=RuntimeAgeBackend.create(server,net.minecraft.resources.Identifier.parse("rivencraft:age/machines112"),112L,null,PortAgeTerrain.FLAT);
PortAcceleratedTicks.configure(age,4);
check(PortAcceleratedTicks.pages(age)==4,"Age-local configured page count");
age.getDataStorage().saveAndJoin();
var typeField=PortAccelerationSettings.class.getDeclaredField("CODEC");typeField.setAccessible(true);
@SuppressWarnings("unchecked") var codec=(com.mojang.serialization.Codec<PortAccelerationSettings>)typeField.get(null);
var saved=codec.encodeStart(com.mojang.serialization.JsonOps.INSTANCE,
age.getDataStorage().computeIfAbsent(PortAccelerationSettings.TYPE)).getOrThrow();
check(codec.parse(com.mojang.serialization.JsonOps.INSTANCE,saved).getOrThrow().pages()==4,"Saved page count reload");
check(PortAcceleratedTicks.pages(level)==0,"Other dimension page count unchanged");
}
static void scheduler() {
var work=new AcceleratedMachineWork();
var list=new ArrayList<Counter>();
for(int i=0;i<5;i++)list.add(new Counter(BlockPos.ZERO));
for(int i=0;i<5;i++)check(work.run(list,20,5,2,c->!c.removed,Counter::tick)==2,"Budget cap");
check(list.stream().allMatch(c->c.calls==2),"Fair budget across repeated ticks");
work=new AcceleratedMachineWork();
list.forEach(c->c.calls=0);
for(int i=0;i<5;i++)work.run(list,1,2,20,c->true,Counter::tick);
check(list.stream().allMatch(c->c.calls==2),"Candidate window rotates fairly");
var mutating=new ArrayList<Counter>();var first=new Counter(BlockPos.ZERO);
mutating.add(first);
work.run(mutating,4,10,20,c->!c.removed,c->{c.tick();c.removed=true;mutating.clear();});
check(first.calls==1,"Removal and live list mutation safe");
check(work.run(list,10,5,0,c->true,Counter::tick)==0,"Zero machine budget");
check(work.run(list,Integer.MAX_VALUE,5,7,c->true,Counter::tick)==7,"Overflow-safe page budget");
}
}
@@ -0,0 +1,191 @@
package net.dnorberg.rivencraft.book;
import java.util.*;
import com.mojang.serialization.JsonOps;
import net.dnorberg.rivencraft.shared.NativeBiomeKind;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.Aquifer;
import net.minecraft.world.level.block.Blocks;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
/** Disposable fixture: exercises real generator settings, fluid picker and codecs. */
@EventBusSubscriber(modid="rivencraft")
public final class NativeFluidProbe {
private static int checks;
private static void check(boolean value, String label) {
if (!value) throw new AssertionError(label);
checks++;
}
static ResourceLocation id(String path) { return ResourceLocation.fromNamespaceAndPath("rivencraft", path); }
@SubscribeEvent public static void start(ServerStartedEvent event) {
event.getServer().execute(() -> {
try { run(event.getServer()); System.out.println("NATIVE119_PASS checks=" + checks); }
catch (Throwable error) { System.out.println("NATIVE119_FAIL " + error); error.printStackTrace(); }
finally { event.getServer().halt(false); }
});
}
static void run(MinecraftServer server) throws Exception {
testFlatGround(server);
int index = 0;
for (var family : List.of(NativeBiomeKind.NETHER, NativeBiomeKind.END, NativeBiomeKind.CAVES)) {
for (String terrain : List.of("standard", "amplified", "island", "cave", "flat", "void")) {
var entries = new net.dnorberg.rivencraft.writing.OrderedWriting(List.of(
net.dnorberg.rivencraft.writing.WritingEntry.linkPanel(),
net.dnorberg.rivencraft.writing.WritingEntry.symbol(new net.dnorberg.rivencraft.writing.SymbolReference(id("terrain/" + terrain))),
net.dnorberg.rivencraft.writing.WritingEntry.symbol(new net.dnorberg.rivencraft.writing.SymbolReference(id("biome/native_" + family.name().toLowerCase(Locale.ROOT))))));
var traits = AgeTraits.select(119L).withBiomeDistribution(AgeTraits.BiomeDistribution.NATIVE);
var plan = AgeGenerationPlan.compile(entries,119L,AgeGenerationProfiles.STANDARD,traits,server.registryAccess());
check(plan.biomeSelection().nativeKind() == family, "Frozen family");
var expectedSky = family == NativeBiomeKind.NETHER ? AgeSkyProfile.Style.NETHER
: family == NativeBiomeKind.END ? AgeSkyProfile.Style.END : AgeSkyProfile.Style.INHERITED;
check(AgeSkyProfile.compile(plan,traits).style() == expectedSky, "Native sky default " + family + terrain);
check(AgeSkyProfile.compile(AgeGenerationPlan.load(plan.save()),traits).style() == expectedSky, "Sky plan reload");
if (family != NativeBiomeKind.CAVES) {
var expectedEffect = family == NativeBiomeKind.NETHER
? net.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER_EFFECTS
: net.minecraft.world.level.dimension.BuiltinDimensionTypes.END_EFFECTS;
check(AgeEnvironmentCompiler.skyEffects(plan,
net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD_EFFECTS).equals(expectedEffect),
"Native dimension sky effect");
if (terrain.equals("standard")) {
for (String sky : List.of("overworld", "nether", "end", "static")) {
var written = new ArrayList<>(entries.entries());
written.add(net.dnorberg.rivencraft.writing.WritingEntry.symbol(
new net.dnorberg.rivencraft.writing.SymbolReference(id("sky/" + sky))));
written.add(net.dnorberg.rivencraft.writing.WritingEntry.symbol(
new net.dnorberg.rivencraft.writing.SymbolReference(id("celestial/sun"))));
var override = AgeGenerationPlan.compile(new net.dnorberg.rivencraft.writing.OrderedWriting(written),
119L,AgeGenerationProfiles.STANDARD,traits,server.registryAccess());
check(AgeSkyProfile.compile(override,traits).style() == AgeSkyProfile.Style.valueOf(sky.toUpperCase(Locale.ROOT)),
"Explicit sky wins with celestial");
}
var written = new ArrayList<>(entries.entries());
written.add(net.dnorberg.rivencraft.writing.WritingEntry.symbol(
new net.dnorberg.rivencraft.writing.SymbolReference(id("celestial/sun"))));
var celestial = AgeGenerationPlan.compile(new net.dnorberg.rivencraft.writing.OrderedWriting(written),
119L,AgeGenerationProfiles.STANDARD,traits,server.registryAccess());
check(AgeSkyProfile.compile(celestial,traits).style() == expectedSky, "Celestial does not override Native default");
}
}
var age = new AgeDefinition(UUID.randomUUID(),"probe",119L,AgeGenerationProfiles.STANDARD,
AgeDefinition.CURRENT_GENERATION_VERSION,0L,id("age/fluid119_" + index++),null,traits,plan);
var factory = AgeDimensionService.class.getDeclaredMethod("createGenerator",MinecraftServer.class,AgeDefinition.class);
factory.setAccessible(true);
var generator = (ChunkGenerator) factory.invoke(null,server,age);
var ops = server.registryAccess().createSerializationContext(JsonOps.INSTANCE);
var encoded = ChunkGenerator.CODEC.encodeStart(ops, generator).getOrThrow();
var restored = ChunkGenerator.CODEC.parse(ops, encoded).getOrThrow();
NoiseBasedChunkGenerator noise = generator instanceof NoiseBasedChunkGenerator n ? n : null;
NoiseBasedChunkGenerator restoredNoise = restored instanceof NoiseBasedChunkGenerator n ? n : null;
if (noise == null) {
check(restoredNoise == null, "Flat/Void remains flat: " + terrain);
continue;
}
var settings = noise.generatorSettings().value();
var reloaded = restoredNoise.generatorSettings().value();
check(reloaded.defaultFluid().equals(settings.defaultFluid())
&& reloaded.seaLevel() == settings.seaLevel(), "Fluid codec " + family + terrain);
if (family == NativeBiomeKind.NETHER) {
check(settings.defaultFluid().is(Blocks.LAVA), "Nether natural lava " + terrain);
check(!settings.isAquifersEnabled(), "Nether disables water aquifers " + terrain);
} else if (family == NativeBiomeKind.END) {
check(settings.defaultFluid().isAir(), "End dry " + terrain);
check(settings.seaLevel() < settings.noiseSettings().minY(), "End fluid below dimension " + terrain);
check(!settings.isAquifersEnabled(), "End disables aquifers " + terrain);
} else {
check(terrain.equals("cave") ? settings.defaultFluid().isAir()
: settings.defaultFluid().is(Blocks.WATER), "Other Native family unchanged " + terrain);
continue;
}
var method = NoiseBasedChunkGenerator.class.getDeclaredMethod("createFluidPicker", NoiseGeneratorSettings.class);
method.setAccessible(true);
var picker = (Aquifer.FluidPicker) method.invoke(null, settings);
boolean water = false, lava = false, anyFluid = false;
for (int y = settings.noiseSettings().minY(); y < settings.noiseSettings().minY() + settings.noiseSettings().height(); y++) {
var block = picker.computeFluid(0, y, 0).at(y);
water |= block.is(Blocks.WATER); lava |= block.is(Blocks.LAVA);
anyFluid |= !block.getFluidState().isEmpty();
}
check(!water, "No natural water anywhere in column " + family + terrain);
check(family == NativeBiomeKind.NETHER ? lava == (settings.seaLevel() > settings.noiseSettings().minY()) : !anyFluid, "Nether lava / End dry picker " + terrain);
}
}
}
static void testFlatGround(MinecraftServer server) throws Exception {
var registry = server.registryAccess().lookupOrThrow(Registries.BIOME);
var random = server.overworld().getChunkSource().randomState();
var settings = AgeDimensionService.flatSettings(server,AgeRuntimeProfiles.resolve(AgeGenerationProfiles.FLAT));
var keys = List.of(net.minecraft.world.level.biome.Biomes.THE_END, net.minecraft.world.level.biome.Biomes.CRIMSON_FOREST,
net.minecraft.world.level.biome.Biomes.WARPED_FOREST, net.minecraft.world.level.biome.Biomes.SOUL_SAND_VALLEY,
net.minecraft.world.level.biome.Biomes.BASALT_DELTAS, net.minecraft.world.level.biome.Biomes.NETHER_WASTES,
net.minecraft.world.level.biome.Biomes.PLAINS);
var tops = List.of(Blocks.END_STONE,Blocks.CRIMSON_NYLIUM,Blocks.WARPED_NYLIUM,Blocks.SOUL_SAND,Blocks.BASALT,Blocks.NETHERRACK,Blocks.GRASS_BLOCK);
var soils = List.of(Blocks.END_STONE,Blocks.NETHERRACK,Blocks.NETHERRACK,Blocks.SOUL_SOIL,Blocks.BLACKSTONE,Blocks.NETHERRACK,Blocks.DIRT);
for (int i=0;i<keys.size();i++) {
ChunkGenerator original = new net.dnorberg.rivencraft.world.AgeFlatChunkGenerator(
new net.minecraft.world.level.biome.FixedBiomeSource(registry.getOrThrow(keys.get(i))),settings);
var ops = server.registryAccess().createSerializationContext(JsonOps.INSTANCE);
var saved = ChunkGenerator.CODEC.encodeStart(ops,original).getOrThrow();
for (var generator : List.of(original,ChunkGenerator.CODEC.parse(ops,saved).getOrThrow())) {
var height = net.minecraft.world.level.LevelHeightAccessor.create(-64,384);
var chunk = new net.minecraft.world.level.chunk.ProtoChunk(new net.minecraft.world.level.ChunkPos(-1,2),
net.minecraft.world.level.chunk.UpgradeData.EMPTY,height,
server.registryAccess().registryOrThrow(Registries.BIOME),null);
generator.fillFromNoise(null,random,null,chunk).join();
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,3,33)).is(tops.get(i)), "Actual flat top " + keys.get(i));
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,1,33)).is(soils.get(i)), "Actual flat soil");
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,0,33)).is(Blocks.BEDROCK), "Bedrock retained");
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,-1,33)).isAir()
&& chunk.getBlockState(new net.minecraft.core.BlockPos(-15,4,33)).isAir(), "Flat bounds unchanged");
check(generator.getBaseColumn(-15,33,height,random).getBlock(3).is(tops.get(i)), "Column agrees with placed blocks");
}
}
var plains = registry.getOrThrow(net.minecraft.world.level.biome.Biomes.PLAINS);
var region = new net.dnorberg.rivencraft.world.AgeFlatChunkGenerator(
new net.minecraft.world.level.biome.FixedBiomeSource(plains),settings,List.of(),119L,List.of(),
net.dnorberg.rivencraft.shared.FloodingRules.NONE,List.of(plains.key().location()));
var ops = server.registryAccess().createSerializationContext(JsonOps.INSTANCE);
var loaded = ChunkGenerator.CODEC.parse(ops,ChunkGenerator.CODEC.encodeStart(ops,region).getOrThrow()).getOrThrow();
check(loaded.getBaseColumn(0,0,net.minecraft.world.level.LevelHeightAccessor.create(-64,384),random)
.getBlock(3).is(Blocks.NETHERRACK), "Region-only Nether classification persists without a tag");
var end = registry.getOrThrow(net.minecraft.world.level.biome.Biomes.THE_END);
check(net.dnorberg.rivencraft.shared.FlatBiomeMaterials.layer(Blocks.DIAMOND_BLOCK.defaultBlockState(),end,false)
.is(Blocks.DIAMOND_BLOCK), "Explicit non-soil material retained");
check(net.dnorberg.rivencraft.shared.FlatBiomeMaterials.layer(Blocks.WATER.defaultBlockState(),end,false)
.is(Blocks.WATER), "Authored fluid retained");
var bind = net.minecraft.core.Holder.Reference.class.getDeclaredMethod("bindTags",Collection.class);
bind.setAccessible(true);var old = plains.tags().toList();
try {
var tags = new ArrayList<>(old);tags.add(net.minecraft.tags.BiomeTags.IS_END);bind.invoke(plains,tags);
var tagged = new net.dnorberg.rivencraft.world.AgeFlatChunkGenerator(
new net.minecraft.world.level.biome.FixedBiomeSource(plains),settings);
check(tagged.getBaseColumn(0,0,net.minecraft.world.level.LevelHeightAccessor.create(-64,384),random)
.getBlock(3).is(Blocks.END_STONE), "Tag-classified modded-style End biome");
} finally { bind.invoke(plains,old); }
var mixedSource = new net.minecraft.world.level.biome.CheckerboardColumnBiomeSource(
net.minecraft.core.HolderSet.direct(List.<net.minecraft.core.Holder<net.minecraft.world.level.biome.Biome>>of(
end,plains,registry.getOrThrow(net.minecraft.world.level.biome.Biomes.CRIMSON_FOREST))),0);
var mixed = new net.dnorberg.rivencraft.world.AgeFlatChunkGenerator(mixedSource,settings);
var seen = new HashSet<net.minecraft.world.level.block.Block>();
for (int cx=-2;cx<=2;cx++) {
int x=cx*16+1;
var biome = mixedSource.getNoiseBiome(net.minecraft.core.QuartPos.fromBlock(x),0,0,random.sampler());
var expected = biome.is(net.minecraft.world.level.biome.Biomes.THE_END) ? Blocks.END_STONE
: biome.is(net.minecraft.world.level.biome.Biomes.CRIMSON_FOREST) ? Blocks.CRIMSON_NYLIUM : Blocks.GRASS_BLOCK;
seen.add(expected);
var height = net.minecraft.world.level.LevelHeightAccessor.create(-64,384);
var chunk = new net.minecraft.world.level.chunk.ProtoChunk(new net.minecraft.world.level.ChunkPos(cx,0),net.minecraft.world.level.chunk.UpgradeData.EMPTY,height,server.registryAccess().registryOrThrow(Registries.BIOME),null);
mixed.fillFromNoise(null,random,null,chunk).join();
check(chunk.getBlockState(new net.minecraft.core.BlockPos(x,3,1)).is(expected), "Mixed biome actual surface");
check(mixed.getBaseColumn(x,1,height,random).getBlock(3).is(expected), "Mixed biome spawn column");
}
check(seen.size()==3, "Mixed test visits End, Nether and Overworld");
}
}
@@ -0,0 +1,174 @@
package net.dnorberg.rivencraft.age;
import java.util.*;
import com.mojang.serialization.JsonOps;
import net.dnorberg.rivencraft.shared.NativeBiomeKind;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.Aquifer;
import net.minecraft.world.level.block.Blocks;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
/** Disposable fixture: exercises real generator settings, fluid picker and codecs. */
@EventBusSubscriber(modid="rivencraft")
public final class NativeFluidProbe {
private static int checks;
private static void check(boolean value, String label) {
if (!value) throw new AssertionError(label);
checks++;
}
static Identifier id(String path) { return Identifier.fromNamespaceAndPath("rivencraft", path); }
@SubscribeEvent public static void start(ServerStartedEvent event) {
event.getServer().execute(() -> {
try { run(event.getServer()); System.out.println("NATIVE119_PASS checks=" + checks); }
catch (Throwable error) { System.out.println("NATIVE119_FAIL " + error); error.printStackTrace(); }
finally { event.getServer().halt(false); }
});
}
static void run(MinecraftServer server) throws Exception {
testFlatGround(server);
int index = 0;
for (var family : List.of(NativeBiomeKind.NETHER, NativeBiomeKind.END, NativeBiomeKind.CAVES)) {
for (String terrain : List.of("standard", "amplified", "island", "cave", "flat", "void")) {
var selection = net.dnorberg.rivencraft.writing.PortAuthoredTerrainSelection.select(server,
List.of(id("terrain/" + terrain), id("biome/native_" + family.name().toLowerCase(Locale.ROOT))),119L);
check(selection.biomes().nativeKind() == family, "Frozen family");
var pages = List.of(id("terrain/" + terrain), id("biome/native_" + family.name().toLowerCase(Locale.ROOT)));
var sky = PortEnvironmentSelection.resolve(pages,119L,selection.terrain()).sky();
if (family != NativeBiomeKind.CAVES) {
var expectedSky = family == NativeBiomeKind.NETHER ? PortSkyStyle.NETHER : PortSkyStyle.END;
check(sky == expectedSky, "Native sky default " + family + terrain);
check(PortSkyStyle.CODEC.parse(JsonOps.INSTANCE,PortSkyStyle.CODEC.encodeStart(JsonOps.INSTANCE,sky)
.getOrThrow()).getOrThrow() == expectedSky, "Sky codec reload");
if (terrain.equals("standard")) {
for (String choice : List.of("overworld", "nether", "end", "static")) {
var authored = new ArrayList<>(pages);
authored.add(id("sky/" + choice)); authored.add(id("celestial/sun"));
check(PortEnvironmentSelection.resolve(authored,119L,selection.terrain()).sky()
== PortSkyStyle.valueOf(choice.toUpperCase(Locale.ROOT)), "Explicit sky wins with celestial");
}
var celestial = new ArrayList<>(pages); celestial.add(id("celestial/sun"));
check(PortSkyStyle.resolve(celestial,119L) == expectedSky, "Celestial does not override Native default");
}
}
var level = RuntimeAgeBackend.create(server,id("age/fluid119_" + index++),119L,selection.biomes(),selection.terrain());
var generator = level.getChunkSource().getGenerator();
if (family != NativeBiomeKind.CAVES) check(level.dimensionTypeRegistration().unwrapKey().orElseThrow()
.identifier().getPath().endsWith("_sky_" + family.name().toLowerCase(Locale.ROOT)), "Runtime dimension sky");
var ops = server.registryAccess().createSerializationContext(JsonOps.INSTANCE);
var encoded = ChunkGenerator.CODEC.encodeStart(ops, generator).getOrThrow();
var restored = ChunkGenerator.CODEC.parse(ops, encoded).getOrThrow();
NoiseBasedChunkGenerator noise = ((PortFeatureChunkGenerator) generator).base() instanceof NoiseBasedChunkGenerator n ? n : null;
NoiseBasedChunkGenerator restoredNoise = ((PortFeatureChunkGenerator) restored).base() instanceof NoiseBasedChunkGenerator n ? n : null;
if (noise == null) {
check(restoredNoise == null, "Flat/Void remains flat: " + terrain);
continue;
}
var settings = noise.generatorSettings().value();
var reloaded = restoredNoise.generatorSettings().value();
check(reloaded.defaultFluid().equals(settings.defaultFluid())
&& reloaded.seaLevel() == settings.seaLevel(), "Fluid codec " + family + terrain);
if (family == NativeBiomeKind.NETHER) {
check(settings.defaultFluid().is(Blocks.LAVA), "Nether natural lava " + terrain);
check(!settings.aquifers().isPresent(), "Nether disables water aquifers " + terrain);
} else if (family == NativeBiomeKind.END) {
check(settings.defaultFluid().isAir(), "End dry " + terrain);
check(settings.seaLevel() < settings.noiseSettings().minY(), "End fluid below dimension " + terrain);
check(!settings.aquifers().isPresent(), "End disables aquifers " + terrain);
} else {
check(terrain.equals("cave") ? settings.defaultFluid().isAir()
: settings.defaultFluid().is(Blocks.WATER), "Other Native family unchanged " + terrain);
continue;
}
var method = NoiseBasedChunkGenerator.class.getDeclaredMethod("createFluidPicker", NoiseGeneratorSettings.class);
method.setAccessible(true);
var picker = (Aquifer.FluidPicker) method.invoke(null, settings);
boolean water = false, lava = false, anyFluid = false;
for (int y = settings.noiseSettings().minY(); y < settings.noiseSettings().minY() + settings.noiseSettings().height(); y++) {
var block = picker.computeFluid(0, y, 0).at(y);
water |= block.is(Blocks.WATER); lava |= block.is(Blocks.LAVA);
anyFluid |= !block.getFluidState().isEmpty();
}
check(!water, "No natural water anywhere in column " + family + terrain);
check(family == NativeBiomeKind.NETHER ? lava == (settings.seaLevel() > settings.noiseSettings().minY()) : !anyFluid, "Nether lava / End dry picker " + terrain);
}
}
}
static void testFlatGround(MinecraftServer server) throws Exception {
var registry = server.registryAccess().lookupOrThrow(Registries.BIOME);
var random = server.overworld().getChunkSource().randomState();
var keys = List.of(net.minecraft.world.level.biome.Biomes.THE_END, net.minecraft.world.level.biome.Biomes.CRIMSON_FOREST,
net.minecraft.world.level.biome.Biomes.WARPED_FOREST, net.minecraft.world.level.biome.Biomes.SOUL_SAND_VALLEY,
net.minecraft.world.level.biome.Biomes.BASALT_DELTAS, net.minecraft.world.level.biome.Biomes.NETHER_WASTES,
net.minecraft.world.level.biome.Biomes.PLAINS);
var tops = List.of(Blocks.END_STONE,Blocks.CRIMSON_NYLIUM,Blocks.WARPED_NYLIUM,Blocks.SOUL_SAND,Blocks.BASALT,Blocks.NETHERRACK,Blocks.GRASS_BLOCK);
var soils = List.of(Blocks.END_STONE,Blocks.NETHERRACK,Blocks.NETHERRACK,Blocks.SOUL_SOIL,Blocks.BLACKSTONE,Blocks.NETHERRACK,Blocks.DIRT);
net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings settings = null;
for (int i=0;i<keys.size();i++) {
var plan = new PortBiomePlan(PortBiomePlan.Distribution.SINGLE,List.of(keys.get(i).identifier()));
var level = RuntimeAgeBackend.create(server,id("age/flat_ground_" + i),119L,plan,PortAgeTerrain.FLAT);
ChunkGenerator original = ((PortFeatureChunkGenerator)level.getChunkSource().getGenerator()).base();
if (i<6) check(original instanceof PortFlatChunkGenerator, "Single End/Nether bypass fixed");
if (original instanceof PortFlatChunkGenerator flat) settings = flat.settings();
var ops = server.registryAccess().createSerializationContext(JsonOps.INSTANCE);
var saved = ChunkGenerator.CODEC.encodeStart(ops,original).getOrThrow();
for (var generator : List.of(original,ChunkGenerator.CODEC.parse(ops,saved).getOrThrow())) {
var height = net.minecraft.world.level.LevelHeightAccessor.create(-64,384);
var chunk = new net.minecraft.world.level.chunk.ProtoChunk(new net.minecraft.world.level.ChunkPos(-1,2),
net.minecraft.world.level.chunk.UpgradeData.EMPTY,height,
net.minecraft.world.level.chunk.PalettedContainerFactory.create(server.registryAccess()),null);
generator.buildTerrain(chunk,null,random,null,server.overworld().getBiomeManager(),null,generator.getBiomeSource().possibleBiomes()).join();
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,3,33)).is(tops.get(i)), "Actual flat top " + keys.get(i));
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,1,33)).is(soils.get(i)), "Actual flat soil");
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,0,33)).is(Blocks.BEDROCK), "Bedrock retained");
check(chunk.getBlockState(new net.minecraft.core.BlockPos(-15,-1,33)).isAir()
&& chunk.getBlockState(new net.minecraft.core.BlockPos(-15,4,33)).isAir(), "Flat bounds unchanged");
check(generator.getBaseColumn(-15,33,height,random).getBlock(3).is(tops.get(i)), "Column agrees with placed blocks");
}
}
var plains = registry.getOrThrow(net.minecraft.world.level.biome.Biomes.PLAINS);
var region = new PortFlatChunkGenerator(new net.minecraft.world.level.biome.FixedBiomeSource(plains),settings,
List.of(plains.key().identifier()));
var ops = server.registryAccess().createSerializationContext(JsonOps.INSTANCE);
var loaded = ChunkGenerator.CODEC.parse(ops,ChunkGenerator.CODEC.encodeStart(ops,region).getOrThrow()).getOrThrow();
check(loaded.getBaseColumn(0,0,net.minecraft.world.level.LevelHeightAccessor.create(-64,384),random)
.getBlock(3).is(Blocks.NETHERRACK), "Region-only Nether classification persists without a tag");
var end = registry.getOrThrow(net.minecraft.world.level.biome.Biomes.THE_END);
check(net.dnorberg.rivencraft.shared.FlatBiomeMaterials.layer(Blocks.DIAMOND_BLOCK.defaultBlockState(),end,false)
.is(Blocks.DIAMOND_BLOCK), "Explicit non-soil material retained");
check(net.dnorberg.rivencraft.shared.FlatBiomeMaterials.layer(Blocks.WATER.defaultBlockState(),end,false)
.is(Blocks.WATER), "Authored fluid retained");
var bind = net.minecraft.core.Holder.Reference.class.getDeclaredMethod("bindTags",Collection.class);
bind.setAccessible(true);var old = plains.tags().toList();
try {
var tags = new ArrayList<>(old);tags.add(net.minecraft.tags.BiomeTags.IS_END);bind.invoke(plains,tags);
var tagged = new PortFlatChunkGenerator(new net.minecraft.world.level.biome.FixedBiomeSource(plains),settings);
check(tagged.getBaseColumn(0,0,net.minecraft.world.level.LevelHeightAccessor.create(-64,384),random)
.getBlock(3).is(Blocks.END_STONE), "Tag-classified modded-style End biome");
} finally { bind.invoke(plains,old); }
var mixedSource = new net.minecraft.world.level.biome.CheckerboardColumnBiomeSource(
net.minecraft.core.HolderSet.direct(List.<net.minecraft.core.Holder<net.minecraft.world.level.biome.Biome>>of(
end,plains,registry.getOrThrow(net.minecraft.world.level.biome.Biomes.CRIMSON_FOREST))),0);
var mixed = new PortFlatChunkGenerator(mixedSource,settings);
var seen = new HashSet<net.minecraft.world.level.block.Block>();
for (int cx=-2;cx<=2;cx++) {
int x=cx*16+1;
var biome = mixedSource.getNoiseBiome(net.minecraft.core.QuartPos.fromBlock(x),0,0);
var expected = biome.is(net.minecraft.world.level.biome.Biomes.THE_END) ? Blocks.END_STONE
: biome.is(net.minecraft.world.level.biome.Biomes.CRIMSON_FOREST) ? Blocks.CRIMSON_NYLIUM : Blocks.GRASS_BLOCK;
seen.add(expected);
var height = net.minecraft.world.level.LevelHeightAccessor.create(-64,384);
var chunk = new net.minecraft.world.level.chunk.ProtoChunk(new net.minecraft.world.level.ChunkPos(cx,0),net.minecraft.world.level.chunk.UpgradeData.EMPTY,height,net.minecraft.world.level.chunk.PalettedContainerFactory.create(server.registryAccess()),null);
mixed.buildTerrain(chunk,null,random,null,server.overworld().getBiomeManager(),null,mixed.getBiomeSource().possibleBiomes()).join();
check(chunk.getBlockState(new net.minecraft.core.BlockPos(x,3,1)).is(expected), "Mixed biome actual surface");
check(mixed.getBaseColumn(x,1,height,random).getBlock(3).is(expected), "Mixed biome spawn column");
}
check(seen.size()==3, "Mixed test visits End, Nether and Overworld");
}
}
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Average a JSON-exported SavedData block profile, including zero-count chunks."""
import argparse
import collections
import hashlib
import json
from pathlib import Path
def generate(source, version):
raw = source.read_bytes()
data = json.loads(raw)["nbt"]["data"]
samples = data.get("Samples", data.get("samples"))
if not samples:
raise ValueError("The source profile has no sampled chunks")
totals = collections.Counter()
for sample in samples:
counts = sample.get("Blocks", sample.get("blocks"))
if not isinstance(counts, dict) or any(not isinstance(n, int) or n < 0 for n in counts.values()):
raise ValueError("Invalid sampled block counts")
totals.update(counts)
return {
"minecraft_version": version,
"source_sample_count": len(samples),
"source_sha256": hashlib.sha256(raw).hexdigest(),
"blocks_per_chunk": {key: total / len(samples) for key, total in sorted(totals.items())},
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("version", choices=("1.21.1", "26.3"))
parser.add_argument("output", type=Path)
args = parser.parse_args()
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(generate(args.source, args.version), indent=2) + "\n")
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Exercise the bundled-baseline Java policy without a server or test world."""
import argparse
import json
from pathlib import Path
import subprocess
import tempfile
from generate_block_baseline import generate
ROOT = Path(__file__).resolve().parents[1]
JAVA = r"""
import java.util.Map;
import net.dnorberg.rivencraft.shared.MaterialBaselinePolicy;
public class BaselineDefaultsChecks {
private static int checks;
private static void equal(double actual, double expected, String label) {
checks++;
if (Math.abs(actual - expected) > 1e-9) throw new AssertionError(label + ": " + actual + " != " + expected);
}
public static void main(String[] args) {
var policy = MaterialBaselinePolicy.load("/assets/rivencraft/instability/default_block_baseline.json");
double iron = Double.parseDouble(args[0]), coal = Double.parseDouble(args[1]);
equal(policy.average("minecraft:coal_ore", 0, 500, false, 0), coal, "Void coal default");
equal(policy.average("minecraft:coal_ore", 25, 500, false, 0), .05, "Measured vanilla wins");
equal(policy.average("test:tin_ore", 0, 500, true, 1000), 2, "Measured iron for missing modded ore");
equal(policy.average("test:tin_ore", 0, 500, true, 0), iron, "Void uses bundled iron");
equal(policy.average("create:zinc_ore", 0, 500, true, 0), iron, "Bundled modded entry cannot replace iron rule");
equal(policy.average("test:tin_ore", 5, 500, true, 0), .01, "Measured modded ore wins");
equal(policy.average("test:tin_ore", 0, 1000, true, 2000), 2, "Chunk-count normalization");
equal(policy.average("test:tin_block", 0, 500, false, 1000), 0, "No iron fallback for storage");
equal(policy.average("test:fluid", 0, 500, false, 1000), 0, "No iron fallback for fluid");
equal(policy.average("minecraft:diamond_block", 0, 500, false, 0), 0, "Absent default remains zero");
equal(policy.average("minecraft:coal_ore", 1, 3, false, 0), 1.0 / 3, "No integer rounding");
try {
policy.average("minecraft:coal_ore", 0, 0, false, 0);
throw new AssertionError("Empty profile accepted");
} catch (IllegalArgumentException expected) { checks++; }
try {
new MaterialBaselinePolicy(Map.of("minecraft:iron_ore", Double.NaN));
throw new AssertionError("NaN accepted");
} catch (IllegalArgumentException expected) { checks++; }
try {
new MaterialBaselinePolicy(Map.of("minecraft:coal_ore", 1.0));
throw new AssertionError("Missing iron accepted");
} catch (IllegalArgumentException expected) { checks++; }
System.out.println("BASELINE_DEFAULTS_PASS version=" + args[2] + " checks=" + checks);
}
}
"""
def main(source_dir):
gson = next((Path.home() / ".gradle/caches/modules-2/files-2.1/com.google.code.gson/gson").rglob("gson-*.jar"))
output = ROOT / "build/verification/baseline115/defaults.txt"
output.parent.mkdir(parents=True, exist_ok=True)
lines = []
with tempfile.TemporaryDirectory(prefix="rivencraft-baseline-policy-") as temp:
work = Path(temp)
fixture = work / "BaselineDefaultsChecks.java"
fixture.write_text(JAVA)
subprocess.run(["javac", "-cp", str(gson), "-d", temp,
str(ROOT / "shared/src/main/java/net/dnorberg/rivencraft/shared/MaterialBaselinePolicy.java"),
str(fixture)], check=True)
for version, resources, iron, coal in [
("1.21.1", ROOT / "src/main/resources", 89.96656534954407, 170.09625126646404),
("26.3", ROOT / "ports/mc263/src/main/resources", 76.5361328125, 95.7587890625),
]:
bundled = json.loads((resources / "assets/rivencraft/instability/default_block_baseline.json").read_text())
if source_dir:
expected = generate(source_dir / ("baseline-" + version + ".json"), version)
assert bundled == expected, "Bundled averages differ from source chunk means: " + version
lines.append("SOURCE_AVERAGES_PASS version=" + version + " chunks=" + str(bundled["source_sample_count"]))
result = subprocess.run(["java", "-cp", ":".join(map(str, [work, gson, resources])),
"BaselineDefaultsChecks", str(iron), str(coal), version], check=True, capture_output=True, text=True)
lines.append(result.stdout.strip())
output.write_text("\n".join(lines) + "\n")
print("\n".join(lines))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-dir", type=Path, help="Optionally verify each bundled mean against the original JSON exports")
main(parser.parse_args().source_dir)
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""Isolated 26.3 client-guard checks; no Minecraft client, GPU, server or world starts."""
from pathlib import Path
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
STUBS = {
"net.minecraft.client.Minecraft": "public class Minecraft { public static boolean sameThread=true; private static final Minecraft INSTANCE=new Minecraft(); public static Minecraft getInstance(){return INSTANCE;} public boolean isSameThread(){return sameThread;} }",
"net.minecraft.client.multiplayer.ClientLevel": "public class ClientLevel { public final java.util.List<Integer> acks=new java.util.ArrayList<>(); public void handleBlockChangedAck(int n){acks.add(n);} }",
"net.minecraft.client.multiplayer.ClientPacketListener": "public class ClientPacketListener {}",
"net.minecraft.network.protocol.game.ClientboundBlockChangedAckPacket": "public record ClientboundBlockChangedAckPacket(int sequence) {}",
"net.dnorberg.rivencraft.compat.ImmersiveBookPreviews": "public class ImmersiveBookPreviews { public static boolean reborn,seamless; public static boolean available(){return reborn||seamless;} }",
"qouteall.imm_ptl.core.ClientWorldLoader": "public class ClientWorldLoader { public static boolean initialized; public static int reads; public static final java.util.List<net.minecraft.client.multiplayer.ClientLevel> worlds=new java.util.ArrayList<>(); public static boolean getIsInitialized(){reads++;return initialized;} public static java.util.Collection<net.minecraft.client.multiplayer.ClientLevel> getClientWorlds(){if(!initialized)throw new IllegalArgumentException();return worlds;} }",
"net.minecraft.client.renderer.chunk.SectionRenderDispatcher": "public class SectionRenderDispatcher { public class RenderSection { public boolean dirty=true; } }",
"net.minecraft.client.renderer.ViewArea": "public class ViewArea implements net.dnorberg.rivencraft.mixin.ViewAreaSectionAccessor { public final java.util.Map<Long,net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection> sections=new java.util.HashMap<>(); public boolean fail; public int reads; public net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection rivencraft$getRenderSection(long n){reads++;if(fail)throw new IllegalStateException();return sections.get(n);} }",
"net.minecraft.client.renderer.LevelRenderer": "public class LevelRenderer {}",
"net.minecraft.client.renderer.state.level.CameraRenderState": "public class CameraRenderState {}",
"net.minecraft.client.renderer.state.level.SectionUpdateRenderState": "public record SectionUpdateRenderState(long sectionNode,boolean playerChanged,Object region,java.util.List<Object> additionalRenderers) {}",
"net.minecraft.client.renderer.state.level.LevelRenderState": "public class LevelRenderState { public final java.util.List<SectionUpdateRenderState> sectionUpdateRenderStates=new java.util.ArrayList<>(); }",
}
EXTRACT = r"""
import java.nio.file.*; import java.util.zip.*; import org.objectweb.asm.*;
public class ExtractForkAck {
public static void main(String[] args)throws Exception {
var writer=new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
writer.visit(Opcodes.V25,Opcodes.ACC_PUBLIC,args[1],null,"java/lang/Object",null);
var init=writer.visitMethod(Opcodes.ACC_PUBLIC,"<init>","()V",null,null);
init.visitCode();init.visitVarInsn(Opcodes.ALOAD,0);init.visitMethodInsn(Opcodes.INVOKESPECIAL,"java/lang/Object","<init>","()V",false);init.visitInsn(Opcodes.RETURN);init.visitMaxs(0,0);init.visitEnd();
int[] copied={0};
try(var zip=new ZipFile(args[0])) {
var bytes=zip.getInputStream(zip.getEntry("qouteall/imm_ptl/core/mixin/client/sync/MixinClientPacketListener.class")).readAllBytes();
new ClassReader(bytes).accept(new ClassVisitor(Opcodes.ASM9) {
@Override public MethodVisitor visitMethod(int access,String name,String desc,String sig,String[] exceptions) {
if(!name.equals("redirectHandleBlockChangedAck"))return null;
copied[0]++;
return new MethodVisitor(Opcodes.ASM9,writer.visitMethod(Opcodes.ACC_PUBLIC,"handle",desc,null,null)) {
@Override public AnnotationVisitor visitAnnotation(String desc,boolean visible){return null;}
};
}
},ClassReader.SKIP_FRAMES|ClassReader.SKIP_DEBUG);
}
if(copied[0]!=1)throw new AssertionError("Expected exactly one fork redirect");
writer.visitEnd();Files.write(Path.of(args[2]),writer.toByteArray());
}
}
"""
CHECKS = r"""
import java.util.*;
import java.lang.reflect.*;
import net.minecraft.client.*;
import net.minecraft.client.multiplayer.*;
import net.minecraft.network.protocol.game.*;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection;
import net.minecraft.client.renderer.state.level.*;
import net.dnorberg.rivencraft.mixin.*;
import net.dnorberg.rivencraft.compat.ImmersiveBookPreviews;
import qouteall.imm_ptl.core.ClientWorldLoader;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
public class Client118Checks {
static int checks;
public static class Ack extends ImmersiveBlockAckMixin {}
public static class Rebuild extends ImmersiveSectionRebuildMixin {}
static void check(boolean pass,String message){if(!pass)throw new AssertionError(message);checks++;}
static void field(Object object,Class<?> owner,String name,Object value)throws Exception{
var field=owner.getDeclaredField(name);field.setAccessible(true);field.set(object,value);
}
static void invoke(Object object,Class<?> owner,String name,Class<?>[] types,Object...args)throws Exception{
var method=owner.getDeclaredMethod(name,types);method.setAccessible(true);method.invoke(object,args);
}
static void ack(Ack hook,CallbackInfo callback)throws Exception{
invoke(hook,ImmersiveBlockAckMixin.class,"rivencraft$ackDuringWorldReset",
new Class<?>[]{ClientboundBlockChangedAckPacket.class,CallbackInfo.class},new ClientboundBlockChangedAckPacket(37),callback);
}
static void render(Rebuild hook,CallbackInfo callback)throws Exception{
invoke(hook,ImmersiveSectionRebuildMixin.class,"rivencraft$discardUnavailableSections",
new Class<?>[]{CameraRenderState.class,CallbackInfo.class},new CameraRenderState(),callback);
}
public static void main(String[] args)throws Exception{
for(String engine:List.of("none","reborn","seamless")){
ImmersiveBookPreviews.reborn=engine.equals("reborn");ImmersiveBookPreviews.seamless=engine.equals("seamless");
Object fork=null;Method redirect=null;
if(!engine.equals("none")){
var type=Class.forName(engine.equals("reborn")?"ForkAckReborn":"ForkAckSeamless");
fork=type.getConstructor().newInstance();redirect=type.getMethod("handle",ClientLevel.class,int.class);
ClientWorldLoader.initialized=false;
try{redirect.invoke(fork,new ClientLevel(),37);throw new AssertionError("Original redirect unexpectedly safe");}
catch(InvocationTargetException error){check(error.getCause() instanceof IllegalArgumentException,"Original "+engine+" precondition reproduced");}
}
for(boolean initialized:List.of(false,true)){
ClientWorldLoader.initialized=initialized;ClientWorldLoader.worlds.clear();ClientWorldLoader.reads=0;Minecraft.sameThread=true;
var local=new ClientLevel();var remote=new ClientLevel();ClientWorldLoader.worlds.addAll(List.of(local,remote));
var hook=new Ack();field(hook,ImmersiveBlockAckMixin.class,"level",local);
var callback=new CallbackInfo("ack",true);ack(hook,callback);
boolean fallback=!engine.equals("none")&&!initialized;
check(callback.isCancelled()==fallback,"Cancellation scope "+engine+initialized);
if(!callback.isCancelled()){
if(engine.equals("none"))local.handleBlockChangedAck(37);else redirect.invoke(fork,local,37);
}
check(local.acks.equals(List.of(37)),"Exactly one local ack "+engine+initialized);
check(remote.acks.equals(!engine.equals("none")&&initialized?List.of(37):List.of()),"Warm-map multiworld delivery retained");
local.acks.clear();remote.acks.clear();ClientWorldLoader.reads=0;Minecraft.sameThread=false;
callback=new CallbackInfo("ack",true);ack(hook,callback);
check(!callback.isCancelled()&&local.acks.isEmpty()&&remote.acks.isEmpty()&&ClientWorldLoader.reads==0,"Network-thread scheduling untouched");
}
Minecraft.sameThread=true;ClientWorldLoader.initialized=false;
var hook=new Ack();field(hook,ImmersiveBlockAckMixin.class,"level",null);
var callback=new CallbackInfo("ack",true);ack(hook,callback);
check(callback.isCancelled()!=engine.equals("none"),"Missing packet world handled only for installed fork");
var area=new ViewArea();var first=new net.minecraft.client.renderer.chunk.SectionRenderDispatcher().new RenderSection();var second=new net.minecraft.client.renderer.chunk.SectionRenderDispatcher().new RenderSection();
area.sections.put(1L,first);area.sections.put(2L,second);
var state=new LevelRenderState();Object region=new Object();List<Object> extras=List.of(new Object());
var a=new SectionUpdateRenderState(1,true,region,extras);
var stale=new SectionUpdateRenderState(9,false,new Object(),List.of());
var b=new SectionUpdateRenderState(2,false,new Object(),List.of());
state.sectionUpdateRenderStates.addAll(List.of(a,stale,b,a));
var rebuild=new Rebuild();field(rebuild,ImmersiveSectionRebuildMixin.class,"viewArea",area);
field(rebuild,ImmersiveSectionRebuildMixin.class,"levelRenderState",state);
callback=new CallbackInfo("compile",true);render(rebuild,callback);
boolean active=!engine.equals("none");
check(state.sectionUpdateRenderStates.equals(active?List.of(a,b,a):List.of(a,stale,b,a)),"Only absent sections removed "+engine);
check(state.sectionUpdateRenderStates.getFirst()==a&&a.region()==region&&a.additionalRenderers()==extras,"Valid identity/order/additional geometry preserved");
check(first.dirty&&second.dirty&&!callback.isCancelled(),"Dirty state and render pipeline untouched");
if(!active)check(area.reads==0,"No renderer workaround without optional engine");
state.sectionUpdateRenderStates.clear();state.sectionUpdateRenderStates.add(stale);area.sections.put(9L,new net.minecraft.client.renderer.chunk.SectionRenderDispatcher().new RenderSection());
render(rebuild,new CallbackInfo("compile",true));
check(state.sectionUpdateRenderStates.equals(List.of(stale)),"Newly available section is not blacklisted");
field(rebuild,ImmersiveSectionRebuildMixin.class,"viewArea",null);
render(rebuild,new CallbackInfo("compile",true));
check(state.sectionUpdateRenderStates.equals(List.of(stale)),"Missing view area not mistaken for stale batch");
field(rebuild,ImmersiveSectionRebuildMixin.class,"viewArea",area);
area.fail=true;
if(active){
try{render(rebuild,new CallbackInfo("compile",true));throw new AssertionError("Unrelated exception swallowed");}
catch(InvocationTargetException error){check(error.getCause() instanceof IllegalStateException,"Unrelated renderer exception propagates");}
}
}
System.out.println("CLIENT118_GUARDS_PASS checks="+checks);
}
}
"""
def main():
homes = list((Path.home() / ".gradle/jdks").glob("*25*/bin/javac"))
if not homes:
homes = list((Path.home() / ".gradle/jdks").glob("*25*/*/bin/javac"))
if not homes:
raise SystemExit("JDK 25 not found in Gradle toolchains")
javac = homes[0]
java = javac.with_name("java")
cache = Path.home() / ".gradle/caches/modules-2/files-2.1"
asm = next((cache / "org.ow2.asm/asm/9.11").rglob("asm-*.jar"))
mixin = next((cache / "net.fabricmc/sponge-mixin").rglob("sponge-mixin-*.jar"))
production = ROOT / "ports/mc263/build/classes/java/main"
mods = Path.home() / ".local/share/PrismLauncher/instances/Dev 26.3/minecraft/mods"
forks = {"Reborn": next(mods.glob("immersive-portals-reborn*.jar*")),
"Seamless": next(mods.glob("seamlessportals*.jar"))}
with tempfile.TemporaryDirectory(prefix="rivencraft-client118-") as temporary:
work = Path(temporary)
classes = work / "classes"
classes.mkdir()
for name in ["client/ImmersivePredictionAcks", "client/ImmersiveSectionRebuilds",
"mixin/ImmersiveBlockAckMixin", "mixin/ImmersiveSectionRebuildMixin", "mixin/ViewAreaSectionAccessor"]:
relative = Path("net/dnorberg/rivencraft") / (name + ".class")
dest = classes / relative
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(production / relative, dest)
sources = []
for name, body in STUBS.items():
package, _, simple = name.rpartition(".")
source = work / Path(name.replace(".", "/") + ".java")
source.parent.mkdir(parents=True, exist_ok=True)
source.write_text("package " + package + ";\n" + body + "\n")
sources.append(source)
for name, body in [("ExtractForkAck", EXTRACT), ("Client118Checks", CHECKS)]:
source = work / (name + ".java")
source.write_text(body)
sources.append(source)
classpath = ":".join(map(str, [classes, asm, mixin]))
subprocess.run([str(javac), "-proc:none", "-cp", classpath, "-d", str(classes), *map(str, sources)], check=True)
for name, jar in forks.items():
subprocess.run([str(java), "-cp", classpath, "ExtractForkAck", str(jar),
"ForkAck" + name, str(classes / ("ForkAck" + name + ".class"))], check=True)
result = subprocess.run([str(java), "-cp", classpath, "Client118Checks"], check=True, capture_output=True, text=True)
output = ROOT / "build/verification/issue118/guards.txt"
output.write_text(result.stdout)
print(result.stdout.strip())
print("No client/server/GPU/world started. Minecraft runtime types were isolated stubs; production guard bytecode and fork redirect bytecode were exercised.")
if __name__ == "__main__":
main()
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Check Dropped-book join conversion and metadata; client rendering remains player validation."""
import argparse
import subprocess
import tempfile
from pathlib import Path
from server_test_lock import server_test_lock
from smoke_server import stop
ROOT = Path(__file__).resolve().parents[1]
def run(target):
log = ROOT / f"build/verification/drop114/{target}.log"
log.parent.mkdir(parents=True, exist_ok=True)
with server_test_lock(), tempfile.TemporaryDirectory(prefix=f"rivencraft-drop114-{target}-") as directory:
work = Path(directory)
init = work / "fixture.gradle"
init.write_text("""
gradle.beforeProject { p ->
p.layout.buildDirectory.set(p.file('""" + str(work / "build") + """'))
p.afterEvaluate {
p.sourceSets.main.java.srcDir(p.file('""" + str(ROOT / "scripts/fixtures/drop114" / target) + """'))
}
}
""")
server = work / "server"
server.mkdir()
(server / "eula.txt").write_text("eula=true\n")
(server / "server.properties").write_text(
"server-ip=127.0.0.1\nserver-port=0\nonline-mode=false\nwhite-list=false\n"
"level-type=minecraft:flat\nlevel-seed=114\nview-distance=2\nsimulation-distance=2\n"
'generator-settings={"layers":[{"height":1,"block":"minecraft:bedrock"}],"biome":"minecraft:plains"}\n')
process = None
try:
args = [str(ROOT / "gradlew")]
if target == "mc263": args += ["-p", str(ROOT / "ports/mc263")]
args += ["--no-daemon", "-I", str(init), "runServer", f"-PserverRunDir={server}", "--console=plain"]
with log.open("w") as output:
process = subprocess.Popen(args, cwd=ROOT, stdin=subprocess.PIPE, stdout=output,
stderr=subprocess.STDOUT, text=True, start_new_session=True)
try:
process.wait(timeout=60)
except subprocess.TimeoutExpired:
print("HANDOFF: Dropped-book probe stalled; stopping without retry. Use docs/DROPPED_BOOKS.md.")
return 2
text = log.read_text()
if process.returncode or "DROP114_PASS" not in text or "DROP114_FAIL" in text:
print(text[-8000:])
return 1
print(next(line for line in text.splitlines() if "DROP114_PASS" in line))
return 0
finally:
stop(process)
print("Removed temporary test world and isolated fixture outputs. Log:", log)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("target", choices=("mc1211",))
raise SystemExit(run(parser.parse_args().target))
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Check Dropped-book interactions and source-validation checks; GPU UI remains player validation."""
import argparse
import subprocess
import tempfile
from pathlib import Path
from server_test_lock import server_test_lock
from smoke_server import stop
ROOT = Path(__file__).resolve().parents[1]
def run(target):
log = ROOT / f"build/verification/drop_interactions/{target}.log"
log.parent.mkdir(parents=True, exist_ok=True)
with server_test_lock(), tempfile.TemporaryDirectory(prefix=f"rivencraft-drop_interactions-{target}-") as directory:
work = Path(directory)
init = work / "fixture.gradle"
init.write_text("""
gradle.beforeProject { p ->
p.layout.buildDirectory.set(p.file('""" + str(work / "build") + """'))
p.afterEvaluate {
p.sourceSets.main.java.srcDir(p.file('""" + str(ROOT / "scripts/fixtures/drop_interactions" / target) + """'))
}
}
""")
server = work / "server"
server.mkdir()
(server / "eula.txt").write_text("eula=true\n")
(server / "server.properties").write_text(
"server-ip=127.0.0.1\nserver-port=0\nonline-mode=false\nwhite-list=false\n"
"level-type=minecraft:flat\nlevel-seed=112\nview-distance=2\nsimulation-distance=2\n"
'generator-settings={"layers":[{"height":1,"block":"minecraft:bedrock"}],"biome":"minecraft:plains"}\n')
process = None
try:
args = [str(ROOT / "gradlew")]
if target == "mc263": args += ["-p", str(ROOT / "ports/mc263")]
args += ["--no-daemon", "-I", str(init), "runServer", f"-PserverRunDir={server}", "--console=plain"]
with log.open("w") as output:
process = subprocess.Popen(args, cwd=ROOT, stdin=subprocess.PIPE, stdout=output,
stderr=subprocess.STDOUT, text=True, start_new_session=True)
try:
process.wait(timeout=60)
except subprocess.TimeoutExpired:
print("HANDOFF: Dropped-book interaction probe stalled; stopping without retry. Use docs/DROPPED_BOOKS.md.")
return 2
text = log.read_text()
if process.returncode or "DROPINTERACT_PASS" not in text or "DROPINTERACT_FAIL" in text:
print(text[-8000:])
return 1
print(next(line for line in text.splitlines() if "DROPINTERACT_PASS" in line))
return 0
finally:
stop(process)
print("Removed temporary test world and isolated fixture outputs. Log:", log)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("target", choices=("mc1211", "mc263"))
raise SystemExit(run(parser.parse_args().target))
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Check Machine acceleration writing/save/network contracts; real rendering remains player validation."""
import argparse
import subprocess
import tempfile
from pathlib import Path
from server_test_lock import server_test_lock
from smoke_server import stop
ROOT = Path(__file__).resolve().parents[1]
def run(target):
log = ROOT / f"build/verification/machine112/{target}.log"
log.parent.mkdir(parents=True, exist_ok=True)
with server_test_lock(), tempfile.TemporaryDirectory(prefix=f"rivencraft-machine112-{target}-") as directory:
work = Path(directory)
init = work / "fixture.gradle"
init.write_text("""
gradle.beforeProject { p ->
p.layout.buildDirectory.set(p.file('""" + str(work / "build") + """'))
p.afterEvaluate {
p.sourceSets.main.java.srcDir(p.file('""" + str(ROOT / "scripts/fixtures/machine112" / target) + """'))
}
}
""")
server = work / "server"
server.mkdir()
(server / "eula.txt").write_text("eula=true\n")
(server / "server.properties").write_text(
"server-ip=127.0.0.1\nserver-port=0\nonline-mode=false\nwhite-list=false\n"
"level-type=minecraft:flat\nlevel-seed=112\nview-distance=2\nsimulation-distance=2\n"
'generator-settings={"layers":[{"height":1,"block":"minecraft:bedrock"}],"biome":"minecraft:plains"}\n')
process = None
try:
args = [str(ROOT / "gradlew")]
if target == "mc263": args += ["-p", str(ROOT / "ports/mc263")]
args += ["--no-daemon", "-I", str(init), "runServer", f"-PserverRunDir={server}", "--console=plain"]
with log.open("w") as output:
process = subprocess.Popen(args, cwd=ROOT, stdin=subprocess.PIPE, stdout=output,
stderr=subprocess.STDOUT, text=True, start_new_session=True)
try:
process.wait(timeout=60)
except subprocess.TimeoutExpired:
print("HANDOFF: Machine acceleration probe stalled; stopping without retry. Use docs/ACCELERATED_MACHINES.md.")
return 2
text = log.read_text()
if process.returncode or "MACHINE112_PASS" not in text or "MACHINE112_FAIL" in text:
print(text[-8000:])
return 1
print(next(line for line in text.splitlines() if "MACHINE112_PASS" in line))
return 0
finally:
stop(process)
print("Removed temporary test world and isolated fixture outputs. Log:", log)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("target", choices=("mc1211", "mc263"))
raise SystemExit(run(parser.parse_args().target))
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Check Native fluid settings/codecs and the real vanilla fluid picker; no chunk generation."""
import argparse
import subprocess
import tempfile
from pathlib import Path
from server_test_lock import server_test_lock
from smoke_server import stop
ROOT = Path(__file__).resolve().parents[1]
def run(target, biome_mods=False):
log = ROOT / f"build/verification/native119/{target}-{'bop' if biome_mods else 'vanilla'}.log"
log.parent.mkdir(parents=True, exist_ok=True)
with server_test_lock(), tempfile.TemporaryDirectory(prefix=f"rivencraft-native119-{target}-") as directory:
work = Path(directory)
init = work / "fixture.gradle"
init.write_text("""
gradle.beforeProject { p ->
p.layout.buildDirectory.set(p.file('""" + str(work / "build") + """'))
p.afterEvaluate {
p.sourceSets.main.java.srcDir(p.file('""" + str(ROOT / "scripts/fixtures/native119" / target) + """'))
}
}
""")
if biome_mods:
game = "1.21.1" if target == "mc1211" else "26.3"
mods = Path.home() / ".local/share/PrismLauncher/instances" / ("Dev " + game) / "minecraft/mods"
jars = [next(mods.glob(pattern)) for pattern in ("BiomesOPlenty*.jar", "TerraBlender*.jar", "GlitchCore*.jar")]
init.write_text(init.read_text() + "\ngradle.projectsEvaluated { gradle.rootProject.dependencies.add('localRuntime', gradle.rootProject.files("
+ ",".join("'" + str(jar) + "'" for jar in jars) + ")) }\n")
server = work / "server"
server.mkdir()
(server / "eula.txt").write_text("eula=true\n")
(server / "server.properties").write_text(
"server-ip=127.0.0.1\nserver-port=0\nonline-mode=false\nwhite-list=false\n"
"level-type=minecraft:flat\nlevel-seed=109\nview-distance=2\nsimulation-distance=2\n"
'generator-settings={"layers":[{"height":1,"block":"minecraft:bedrock"}],"biome":"minecraft:plains"}\n')
process = None
try:
args = [str(ROOT / "gradlew")]
if target == "mc263": args += ["-p", str(ROOT / "ports/mc263")]
args += ["--no-daemon", "-I", str(init), "runServer", f"-PserverRunDir={server}", "--console=plain"]
with log.open("w") as output:
process = subprocess.Popen(args, cwd=ROOT, stdin=subprocess.PIPE, stdout=output,
stderr=subprocess.STDOUT, text=True, start_new_session=True)
try:
process.wait(timeout=60)
except subprocess.TimeoutExpired:
print("HANDOFF: Native fluid probe stalled; stopping without retry. Use docs/NATIVE_FLUIDS.md.")
return 2
text = log.read_text()
if process.returncode or "NATIVE119_PASS" not in text or "NATIVE119_FAIL" in text:
print(text[-8000:])
return 1
print(next(line for line in text.splitlines() if "NATIVE119_PASS" in line))
return 0
finally:
stop(process)
print("Removed temporary test world and isolated fixture outputs. Log:", log)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("target", choices=("mc1211", "mc263"))
parser.add_argument("--biome-mods", action="store_true")
args=parser.parse_args()
raise SystemExit(run(args.target,args.biome_mods))
@@ -0,0 +1,43 @@
package net.dnorberg.rivencraft.shared;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
/** Bounded round-robin work. The owner keeps one cursor per loaded Age. */
public final class AcceleratedMachineWork {
private int scanCursor;
private int tickCursor;
public <T> int run(List<T> registered, int pages, int maximumCandidates, int maximumTicks,
Predicate<T> eligible, Consumer<T> tick) {
if (pages <= 0 || maximumCandidates <= 0 || maximumTicks <= 0 || registered.isEmpty()) return 0;
int size = registered.size();
int first = Math.floorMod(scanCursor, size);
int scanned = Math.min(size, maximumCandidates);
// Ticking can remove/rebind machines or register new tickers. Never iterate
// the world's live ticker list while invoking a machine.
List<T> candidates = new ArrayList<>();
for (int i = 0; i < scanned; i++) {
T candidate = registered.get((int) (((long) first + i) % size));
if (eligible.test(candidate)) candidates.add(candidate);
}
scanCursor = (int) (((long) first + scanned) % size);
if (candidates.isEmpty()) return 0;
int count = candidates.size();
int budget = (int) Math.min(maximumTicks, (long) pages * count);
int offset = Math.floorMod(tickCursor, count);
int calls = 0;
for (int i = 0; i < budget; i++) {
T candidate = candidates.get((int) (((long) offset + i) % count));
// Previous extra ticks may remove/replace this machine or freeze time.
if (eligible.test(candidate)) {
tick.accept(candidate);
calls++;
}
}
tickCursor = (int) (((long) offset + budget) % count);
return calls;
}
}
@@ -0,0 +1,44 @@
package net.dnorberg.rivencraft.shared;
import net.minecraft.core.Holder;
import net.minecraft.tags.BiomeTags;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
/** Biome-aware replacement of Flat terrain's base layers, before authored features. */
public final class FlatBiomeMaterials {
private FlatBiomeMaterials() {}
public static boolean isEnd(Holder<Biome> biome) {
return biome.is(BiomeTags.IS_END) || biome.is(Biomes.THE_END) || biome.is(Biomes.END_HIGHLANDS)
|| biome.is(Biomes.END_MIDLANDS) || biome.is(Biomes.END_BARRENS) || biome.is(Biomes.SMALL_END_ISLANDS);
}
public static boolean isNether(Holder<Biome> biome, boolean regionNether) {
return regionNether || biome.is(BiomeTags.IS_NETHER) || biome.is(Biomes.NETHER_WASTES)
|| biome.is(Biomes.CRIMSON_FOREST) || biome.is(Biomes.WARPED_FOREST)
|| biome.is(Biomes.SOUL_SAND_VALLEY) || biome.is(Biomes.BASALT_DELTAS);
}
public static boolean isBaseMaterial(BlockState state) {
return state.is(Blocks.GRASS_BLOCK) || state.is(Blocks.DIRT) || state.is(Blocks.STONE)
|| state.is(Blocks.DEEPSLATE) || state.is(Blocks.TUFF);
}
public static BlockState layer(BlockState state, Holder<Biome> biome, boolean regionNether) {
if (!isBaseMaterial(state)) return state;
if (isNether(biome, regionNether)) {
boolean cap = state.is(Blocks.GRASS_BLOCK);
if (biome.is(Biomes.CRIMSON_FOREST) && cap) return Blocks.CRIMSON_NYLIUM.defaultBlockState();
if (biome.is(Biomes.WARPED_FOREST) && cap) return Blocks.WARPED_NYLIUM.defaultBlockState();
if (biome.is(Biomes.SOUL_SAND_VALLEY))
return (cap ? Blocks.SOUL_SAND : Blocks.SOUL_SOIL).defaultBlockState();
if (biome.is(Biomes.BASALT_DELTAS))
return (cap ? Blocks.BASALT : Blocks.BLACKSTONE).defaultBlockState();
return Blocks.NETHERRACK.defaultBlockState();
}
return isEnd(biome) ? Blocks.END_STONE.defaultBlockState() : state;
}
}
@@ -0,0 +1,46 @@
package net.dnorberg.rivencraft.shared;
import com.google.gson.JsonParser;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/** Per-chunk defaults for individual zero-count Overworld materials. */
public final class MaterialBaselinePolicy {
private final Map<String, Double> defaults;
public MaterialBaselinePolicy(Map<String, Double> defaults) {
this.defaults = Map.copyOf(defaults);
if (this.defaults.values().stream().anyMatch(value -> !Double.isFinite(value) || value < 0))
throw new IllegalArgumentException("Invalid block baseline average");
if (ironDefault() <= 0) throw new IllegalArgumentException("Missing default iron baseline");
}
public static MaterialBaselinePolicy load(String resource) {
try (var stream = Objects.requireNonNull(MaterialBaselinePolicy.class.getResourceAsStream(resource),
"Missing bundled block baseline: " + resource);
var reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
Map<String, Double> values = new HashMap<>();
JsonParser.parseReader(reader).getAsJsonObject().getAsJsonObject("blocks_per_chunk")
.entrySet().forEach(entry -> values.put(entry.getKey(), entry.getValue().getAsDouble()));
return new MaterialBaselinePolicy(values);
} catch (java.io.IOException exception) {
throw new IllegalStateException("Could not load bundled block baseline", exception);
}
}
private double ironDefault() {
return defaults.getOrDefault("minecraft:iron_ore", 0.0)
+ defaults.getOrDefault("minecraft:deepslate_iron_ore", 0.0);
}
public double average(String id, long observed, int chunks, boolean moddedOre, long ironObserved) {
if (chunks <= 0) throw new IllegalArgumentException("Baseline must contain sampled chunks");
if (observed > 0) return observed / (double) chunks;
// An absent modded ore always uses iron, including ores present in the bundled profile.
if (moddedOre) return ironObserved > 0 ? ironObserved / (double) chunks : ironDefault();
return defaults.getOrDefault(id, 0.0);
}
}
@@ -0,0 +1,68 @@
package net.dnorberg.rivencraft.shared;
import java.util.ArrayList;
import java.util.List;
/** Desk-local attachment geometry; origin is the controller's horizontal center.
* The JSON tabletop is 12/16 high and its red mat straddles the two-block seam.
* Paper uses the existing Legacy desk atlas's white 16x16 patch.
*/
public final class WritingDeskDisplayModel {
public static final double TOP = 12.0 / 16.0;
public static final double PAPER_SHELF_TOP = 6.0 / 16.0;
public static final double PAGE_X = 0.5;
public static final double PAGE_Y = TOP + 0.002;
public static final double PAGE_Z = 0.0;
public static final float PAGE_SCALE = 0.7F;
private static final List<List<Face>> STACKS = List.of(
List.of(), stack(1), stack(2), stack(3), stack(4));
private WritingDeskDisplayModel() {}
public static int layers(int count) {
return count <= 0 ? 0 : (Math.min(64, count) + 15) / 16;
}
public static List<Face> paper(int count) { return STACKS.get(layers(count)); }
private static List<Face> stack(int layers) {
List<Face> faces = new ArrayList<>();
for (int i = 0; i < layers; i++) {
float angle = (float) Math.toRadians(i % 2 == 0 ? 2 : -2);
float bottom = (float) PAPER_SHELF_TOP + 0.001F + i / 32.0F;
float h = 1 / 32.0F, x = 0.25F, z = 0.3125F;
face(faces, angle, bottom, 0, 1, 0, 0xFFFFFFFF,
-x,h,-z, -x,h,z, x,h,z, x,h,-z);
face(faces, angle, bottom, 0,-1,0, 0xFFCCCCCC,
-x,0,-z, x,0,-z, x,0,z, -x,0,z);
face(faces, angle, bottom, 0,0,-1, 0xFFEEEEEE,
-x,0,-z, -x,h,-z, x,h,-z, x,0,-z);
face(faces, angle, bottom, 0,0,1, 0xFFEEEEEE,
x,0,z, x,h,z, -x,h,z, -x,0,z);
face(faces, angle, bottom, 1,0,0, 0xFFDDDDDD,
x,0,-z, x,h,-z, x,h,z, x,0,z);
face(faces, angle, bottom,-1,0,0, 0xFFDDDDDD,
-x,0,z, -x,h,z, -x,h,-z, -x,0,-z);
}
return List.copyOf(faces);
}
private static void face(List<Face> faces, float angle, float bottom,
float nx, float ny, float nz, int color, float... xyz) {
float cos = (float) Math.cos(angle), sin = (float) Math.sin(angle);
List<Vertex> vertices = new ArrayList<>(4);
for (int i = 0; i < 4; i++) {
float x = xyz[i * 3], y = xyz[i * 3 + 1], z = xyz[i * 3 + 2];
// Right shelf, slightly toward its front, inside its support edges.
vertices.add(new Vertex(1.15F + cos*x + sin*z, bottom+y,
-0.1F - sin*x + cos*z,
(i >= 2 ? 15.5F : 0.5F) / 256.0F,
(i == 1 || i == 2 ? 15.5F : 0.5F) / 128.0F));
}
faces.add(new Face(List.copyOf(vertices), cos*nx + sin*nz, ny,
-sin*nx + cos*nz, color));
}
public record Vertex(float x, float y, float z, float u, float v) {}
public record Face(List<Vertex> vertices, float nx, float ny, float nz, int color) {}
}
@@ -15,17 +15,18 @@ import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
/** Extra random block ticks from authored Accelerated pages, bounded to loaded player chunks. */ /** Independent bounded random-block and server-machine acceleration in authored Ages. */
final class AgeAcceleratedTicks { final class AgeAcceleratedTicks {
private AgeAcceleratedTicks() {} private AgeAcceleratedTicks() {}
static void tick(ServerLevel level) { static void tick(ServerLevel level) {
int maximumAttempts = RivencraftConfig.acceleratedMaxAttempts(); int maximumAttempts = RivencraftConfig.acceleratedMaxAttempts();
if (maximumAttempts == 0) return;
AgeDefinition age = AgeRegistrySavedData.get(level) AgeDefinition age = AgeRegistrySavedData.get(level)
.findByDimension(level.dimension().location()).orElse(null); .findByDimension(level.dimension().location()).orElse(null);
int pages = age == null || age.plan() == null ? 0 : acceleratedPages(age.plan()); int pages = age == null || age.plan() == null ? 0 : acceleratedPages(age.plan());
if (pages == 0) return; if (pages == 0 || !level.tickRateManager().runsNormally() || level.tickRateManager().isFrozen()) return;
AgeMachineTicks.tick(level, pages);
if (maximumAttempts == 0) return;
List<ChunkPos> chunks = loadedPlayerChunks(level); List<ChunkPos> chunks = loadedPlayerChunks(level);
if (chunks.isEmpty()) return; if (chunks.isEmpty()) return;
@@ -53,6 +53,32 @@ public final class AgeBlockInstability {
private AgeBlockInstability() {} private AgeBlockInstability() {}
private static final net.dnorberg.rivencraft.shared.MaterialBaselinePolicy DEFAULT_BASELINE =
net.dnorberg.rivencraft.shared.MaterialBaselinePolicy.load(
"/assets/rivencraft/instability/default_block_baseline.json");
public static int baselineSamples(MinecraftServer server) {
return AgeBlockProfileSavedData.get(server.overworld()).count();
}
public static String baselineStatus(MinecraftServer server) {
return "minecraft:overworld; zero counts use bundled defaults, modded ores use iron";
}
private static boolean moddedOre(ResourceLocation id) {
if (id.getNamespace().equals("minecraft") || id.getNamespace().equals("rivencraft")
|| !BuiltInRegistries.BLOCK.containsKey(id)) return false;
var state = BuiltInRegistries.BLOCK.get(id).defaultBlockState();
return state.is(Tags.Blocks.ORES) || id.getPath().endsWith("_ore") || id.getPath().contains("_ore_");
}
static double baselineAverage(ResourceLocation id, Map<ResourceLocation, Long> baseline, int chunks) {
long iron = baseline.getOrDefault(ResourceLocation.withDefaultNamespace("iron_ore"), 0L)
+ baseline.getOrDefault(ResourceLocation.withDefaultNamespace("deepslate_iron_ore"), 0L);
return DEFAULT_BASELINE.average(id.toString(), baseline.getOrDefault(id, 0L),
chunks, moddedOre(id), iron);
}
/** Track recognized materials from installed mods without requiring any mod-specific API. */ /** Track recognized materials from installed mods without requiring any mod-specific API. */
static boolean tracked(ResourceLocation id) { static boolean tracked(ResourceLocation id) {
if (VANILLA_WEIGHTS.containsKey(id)) return true; if (VANILLA_WEIGHTS.containsKey(id)) return true;
@@ -144,7 +170,8 @@ public final class AgeBlockInstability {
} }
if (pending == null) break; if (pending == null) break;
var pos = pending.chunk().getPos(); var pos = pending.chunk().getPos();
if (pending.level().getChunkSource().hasChunk(pos.x, pos.z)) if (pending.level().getServer().getLevel(pending.level().dimension()) == pending.level()
&& pending.level().getChunkSource().getChunkNow(pos.x, pos.z) == pending.chunk())
AgeBlockProfileSavedData.get(pending.level()).sample(pending.chunk()); AgeBlockProfileSavedData.get(pending.level()).sample(pending.chunk());
} }
if (event.getServer().getTickCount() % GENERATION_INTERVAL_TICKS == 0) { if (event.getServer().getTickCount() % GENERATION_INTERVAL_TICKS == 0) {
@@ -159,7 +186,7 @@ public final class AgeBlockInstability {
GENERATION_IN_FLIGHT.remove(event.getServer()); GENERATION_IN_FLIGHT.remove(event.getServer());
} }
/** Generate at most one chunk per second across the active Age and its Overworld baseline. */ /** Generate at most one chunk per second across active Ages and the Overworld baseline. */
private static void generateNextSpawnSample(MinecraftServer server) { private static void generateNextSpawnSample(MinecraftServer server) {
if (GENERATION_IN_FLIGHT.containsKey(server)) return; if (GENERATION_IN_FLIGHT.containsKey(server)) return;
List<SampleTarget> targets = new ArrayList<>(); List<SampleTarget> targets = new ArrayList<>();
@@ -174,8 +201,8 @@ public final class AgeBlockInstability {
AgeBlockProfileSavedData.MIN_AGE_SAMPLES)); AgeBlockProfileSavedData.MIN_AGE_SAMPLES));
} }
if (targets.isEmpty()) return; if (targets.isEmpty()) return;
ServerLevel overworld = server.overworld(); ServerLevel baseline = server.overworld();
targets.add(0, new SampleTarget(overworld, overworld.getSharedSpawnPos(), targets.add(0, new SampleTarget(baseline, baseline.getSharedSpawnPos(),
AgeBlockProfileSavedData.MIN_BASELINE_SAMPLES)); AgeBlockProfileSavedData.MIN_BASELINE_SAMPLES));
int first = Math.floorMod(NEXT_TARGET.getOrDefault(server, 0), targets.size()); int first = Math.floorMod(NEXT_TARGET.getOrDefault(server, 0), targets.size());
for (int offset = 0; offset < targets.size(); offset++) { for (int offset = 0; offset < targets.size(); offset++) {
@@ -208,14 +235,18 @@ public final class AgeBlockInstability {
CompletableFuture.supplyAsync(() -> level.getChunkSource() CompletableFuture.supplyAsync(() -> level.getChunkSource()
.getChunkFuture(target.x, target.z, ChunkStatus.FULL, true)) .getChunkFuture(target.x, target.z, ChunkStatus.FULL, true))
.thenCompose(future -> future) .thenCompose(future -> future)
.whenComplete((result, error) -> server.execute(() -> { .whenComplete((result, error) -> {
GENERATION_IN_FLIGHT.remove(server); if (server.isStopped()) return;
if (error != null) { server.execute(() -> {
Rivencraft.LOGGER.warn("Could not profile chunk {} in {}", target, dimension, error); if (GENERATION_IN_FLIGHT.remove(server) == null) return;
} else if (result.orElse(null) instanceof LevelChunk chunk) { if (error != null) {
profile.sample(chunk); Rivencraft.LOGGER.warn("Could not profile chunk {} in {}", target, dimension, error);
} } else if (server.getLevel(level.dimension()) == level
})); && result.orElse(null) instanceof LevelChunk chunk) {
profile.sample(chunk);
}
});
});
return true; return true;
} }
return false; return false;
@@ -253,7 +284,7 @@ public final class AgeBlockInstability {
double weight = weight(id); double weight = weight(id);
if (weight <= 0) continue; if (weight <= 0) continue;
double excess = age.getOrDefault(id, 0L) / (double) ageChunks double excess = age.getOrDefault(id, 0L) / (double) ageChunks
- 1.05 * baseline.getOrDefault(id, 0L) / (double) baselineChunks; - 1.05 * baselineAverage(id, baseline, baselineChunks);
if (excess > 0) result += excess * weight; if (excess > 0) result += excess * weight;
} }
return (int) Math.min(100_000, Math.round(result)); return (int) Math.min(100_000, Math.round(result));
@@ -263,8 +294,7 @@ public final class AgeBlockInstability {
if (age.instability().version() < 2 if (age.instability().version() < 2
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location()) || !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|| !age.dimensionId().equals(level.dimension().location())) return 0; || !age.dimensionId().equals(level.dimension().location())) return 0;
return score(AgeBlockProfileSavedData.get(level), return score(AgeBlockProfileSavedData.get(level), AgeBlockProfileSavedData.get(level.getServer().overworld()));
AgeBlockProfileSavedData.get(level.getServer().overworld()));
} }
public static int sampledChunks(ServerLevel level) { public static int sampledChunks(ServerLevel level) {
@@ -1,5 +1,7 @@
package net.dnorberg.rivencraft.book; package net.dnorberg.rivencraft.book;
import net.dnorberg.rivencraft.shared.NativeBiomeKind;
import dev.galacticraft.dynamicdimensions.api.DynamicDimensionRegistry; import dev.galacticraft.dynamicdimensions.api.DynamicDimensionRegistry;
import dev.galacticraft.dynamicdimensions.api.PlayerRemover; import dev.galacticraft.dynamicdimensions.api.PlayerRemover;
import dev.galacticraft.dynamicdimensions.api.event.DimensionRemovedCallback; import dev.galacticraft.dynamicdimensions.api.event.DimensionRemovedCallback;
@@ -374,7 +376,8 @@ public final class AgeDimensionService {
if (profile.terrain() == AgeRuntimeProfile.Terrain.FLAT) { if (profile.terrain() == AgeRuntimeProfile.Terrain.FLAT) {
var settings = flatSettings(server, profile); var settings = flatSettings(server, profile);
return age.generationVersion() < AgeDefinition.LEGACY_GENERATOR_CUTOFF return age.generationVersion() < AgeDefinition.LEGACY_GENERATOR_CUTOFF
? new FlatLevelSource(settings) : new AgeFlatChunkGenerator(biomeSource, settings, features, age.seed(), libraryAgeSymbols, AgeFlooding.requested(age.plan())); ? new FlatLevelSource(settings) : new AgeFlatChunkGenerator(biomeSource, settings, features, age.seed(), libraryAgeSymbols,
AgeFlooding.requested(age.plan()), TerraBlenderBiomes.nether(server.registryAccess()));
} }
if (profile.terrain() == AgeRuntimeProfile.Terrain.VOID) { if (profile.terrain() == AgeRuntimeProfile.Terrain.VOID) {
FlatLevelGeneratorSettings settings = new FlatLevelGeneratorSettings( FlatLevelGeneratorSettings settings = new FlatLevelGeneratorSettings(
@@ -384,7 +387,8 @@ public final class AgeDimensionService {
); );
settings.updateLayers(); settings.updateLayers();
return age.generationVersion() < AgeDefinition.LEGACY_GENERATOR_CUTOFF return age.generationVersion() < AgeDefinition.LEGACY_GENERATOR_CUTOFF
? new FlatLevelSource(settings) : new AgeFlatChunkGenerator(biomeSource, settings, features, age.seed(), libraryAgeSymbols, AgeFlooding.requested(age.plan())); ? new FlatLevelSource(settings) : new AgeFlatChunkGenerator(biomeSource, settings, features, age.seed(), libraryAgeSymbols,
AgeFlooding.requested(age.plan()), TerraBlenderBiomes.nether(server.registryAccess()));
} }
var noiseSettings = server.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS); var noiseSettings = server.registryAccess().lookupOrThrow(Registries.NOISE_SETTINGS);
@@ -393,7 +397,13 @@ public final class AgeDimensionService {
NoiseGeneratorSettings baseSettings = noiseSettings.getOrThrow(settingsKey).value(); NoiseGeneratorSettings baseSettings = noiseSettings.getOrThrow(settingsKey).value();
Holder<NoiseGeneratorSettings> settings = Holder.direct(withBiomeMaterialRules(baseSettings)); Holder<NoiseGeneratorSettings> settings = Holder.direct(withBiomeMaterialRules(baseSettings));
boolean caveTerrain = AgeBiomeSelection.isCave(profile); boolean caveTerrain = AgeBiomeSelection.isCave(profile);
if (caveTerrain) settings = Holder.direct(dryCaveSettings(settings.value())); AgeBiomeSelection selection = age.plan() != null && age.plan().biomeSelection() != null
? age.plan().biomeSelection() : age.randomBiomes();
var nativeKind = selection == null ? NativeBiomeKind.TERRAIN
: selection.nativeKind();
if (caveTerrain && nativeKind != NativeBiomeKind.NETHER)
settings = Holder.direct(dryCaveSettings(settings.value()));
settings = Holder.direct(nativeFluidSettings(settings.value(), nativeKind));
return age.generationVersion() < AgeDefinition.LEGACY_GENERATOR_CUTOFF return age.generationVersion() < AgeDefinition.LEGACY_GENERATOR_CUTOFF
? new NoiseBasedChunkGenerator(biomeSource, settings) ? new NoiseBasedChunkGenerator(biomeSource, settings)
: new AgeFeatureChunkGenerator(biomeSource, settings, features, age.seed(), : new AgeFeatureChunkGenerator(biomeSource, settings, features, age.seed(),
@@ -440,6 +450,18 @@ public final class AgeDimensionService {
base.oreVeinsEnabled(), base.useLegacyRandomSource()); base.oreVeinsEnabled(), base.useLegacyRandomSource());
} }
/** Native family controls natural fluid only; authored Flooded/features run later. */
static NoiseGeneratorSettings nativeFluidSettings(NoiseGeneratorSettings base,
NativeBiomeKind kind) {
if (kind != NativeBiomeKind.NETHER
&& kind != NativeBiomeKind.END) return base;
boolean nether = kind == NativeBiomeKind.NETHER;
return new NoiseGeneratorSettings(base.noiseSettings(), base.defaultBlock(),
(nether ? Blocks.LAVA : Blocks.AIR).defaultBlockState(), base.noiseRouter(),
base.surfaceRule(), base.spawnTarget(), nether ? base.seaLevel() : base.noiseSettings().minY() - 1,
base.disableMobGeneration(), false, base.oreVeinsEnabled(), base.useLegacyRandomSource());
}
private static NoiseGeneratorSettings withBiomeMaterialRules(NoiseGeneratorSettings base) { private static NoiseGeneratorSettings withBiomeMaterialRules(NoiseGeneratorSettings base) {
SurfaceRules.RuleSource biomeMaterials = SurfaceRules.sequence( SurfaceRules.RuleSource biomeMaterials = SurfaceRules.sequence(
SurfaceRules.ifTrue( SurfaceRules.ifTrue(
@@ -499,7 +521,7 @@ public final class AgeDimensionService {
age.traits(), profile, age.seed(), server.registryAccess(), age.randomPagePolicy()); age.traits(), profile, age.seed(), server.registryAccess(), age.randomPagePolicy());
var registry = server.registryAccess().lookupOrThrow(Registries.BIOME); var registry = server.registryAccess().lookupOrThrow(Registries.BIOME);
List<Holder<Biome>> biomes = new ArrayList<>(); List<Holder<Biome>> biomes = new ArrayList<>();
List<ResourceLocation> fallbacks = selection.nativeKind() == net.dnorberg.rivencraft.shared.NativeBiomeKind.TERRAIN List<ResourceLocation> fallbacks = selection.nativeKind() == NativeBiomeKind.TERRAIN
? AgeBiomeSelection.eligible(server.registryAccess(), profile) ? AgeBiomeSelection.eligible(server.registryAccess(), profile)
: NativeBiomePools.pool(server.registryAccess(), selection.nativeKind()); : NativeBiomePools.pool(server.registryAccess(), selection.nativeKind());
Set<ResourceLocation> present = new LinkedHashSet<>(); Set<ResourceLocation> present = new LinkedHashSet<>();
@@ -523,7 +545,7 @@ public final class AgeDimensionService {
} }
AgeTraits.BiomeDistribution distribution = selection.distribution(); AgeTraits.BiomeDistribution distribution = selection.distribution();
if (distribution == AgeTraits.BiomeDistribution.NATIVE if (distribution == AgeTraits.BiomeDistribution.NATIVE
&& selection.nativeKind() == net.dnorberg.rivencraft.shared.NativeBiomeKind.TERRAIN && selection.nativeKind() == NativeBiomeKind.TERRAIN
&& !AgeBiomeSelection.isCave(profile) && !AgeBiomeSelection.isCave(profile)
&& profile.terrain() == AgeRuntimeProfile.Terrain.NOISE) { && profile.terrain() == AgeRuntimeProfile.Terrain.NOISE) {
var parameters = server.registryAccess() var parameters = server.registryAccess()
@@ -97,7 +97,11 @@ public final class AgeEnvironmentCompiler {
case "nether" -> BuiltinDimensionTypes.NETHER_EFFECTS; case "nether" -> BuiltinDimensionTypes.NETHER_EFFECTS;
case "end" -> BuiltinDimensionTypes.END_EFFECTS; case "end" -> BuiltinDimensionTypes.END_EFFECTS;
default -> throw new IllegalArgumentException("Unsupported sky effect " + choice); default -> throw new IllegalArgumentException("Unsupported sky effect " + choice);
}).findFirst().orElse(fallback); }).findFirst().orElseGet(() -> switch (AgeSkyProfile.defaultStyle(plan)) {
case NETHER -> BuiltinDimensionTypes.NETHER_EFFECTS;
case END -> BuiltinDimensionTypes.END_EFFECTS;
default -> fallback;
});
} }
public static boolean staticSky(AgeGenerationPlan plan) { public static boolean staticSky(AgeGenerationPlan plan) {
@@ -39,9 +39,10 @@ public final class AgeInstabilityRuntime {
public static void onLevelTickPost(LevelTickEvent.Post event) { public static void onLevelTickPost(LevelTickEvent.Post event) {
if (!(event.getLevel() instanceof ServerLevel level) if (!(event.getLevel() instanceof ServerLevel level)
|| !isAgeDimension(level.dimension().location()) || level.players().isEmpty()) return; || !isAgeDimension(level.dimension().location())) return;
// Authored environmental pages are active Age rules, not selected instability cards. // Authored environmental pages are active Age rules, not selected instability cards.
AgeAcceleratedTicks.tick(level); AgeAcceleratedTicks.tick(level);
if (level.players().isEmpty()) return;
if (!RivencraftConfig.instabilityEnabled()) return; if (!RivencraftConfig.instabilityEnabled()) return;
MinecraftServer server = level.getServer(); MinecraftServer server = level.getServer();
long tick = server.getTickCount(); long tick = server.getTickCount();
@@ -0,0 +1,30 @@
package net.dnorberg.rivencraft.book;
import java.util.Map;
import java.util.WeakHashMap;
import net.dnorberg.rivencraft.config.RivencraftConfig;
import net.dnorberg.rivencraft.mixin.LevelBlockEntityTickersAccessor;
import net.dnorberg.rivencraft.shared.AcceleratedMachineWork;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.entity.TickingBlockEntity;
/** Reuses vanilla/NeoForge bound tickers, including modded server machines. */
public final class AgeMachineTicks {
private static final Map<ServerLevel, AcceleratedMachineWork> WORK = new WeakHashMap<>();
private AgeMachineTicks() {}
public static void tick(ServerLevel level, int pages) {
if (pages <= 0 || !level.tickRateManager().runsNormally() || level.tickRateManager().isFrozen()) return;
WORK.computeIfAbsent(level, ignored -> new AcceleratedMachineWork()).run(
((LevelBlockEntityTickersAccessor) level).rivencraft$blockEntityTickers(),
pages, RivencraftConfig.acceleratedMachineCandidates(), RivencraftConfig.acceleratedMachineTicks(),
ticker -> eligible(level, ticker), TickingBlockEntity::tick);
}
private static boolean eligible(ServerLevel level, TickingBlockEntity ticker) {
var pos = ticker.getPos();
return level.tickRateManager().runsNormally() && !level.tickRateManager().isFrozen() && !ticker.isRemoved()
&& level.getWorldBorder().isWithinBounds(pos)
&& level.hasChunkAt(pos) && level.shouldTickBlocksAt(pos);
}
}
@@ -67,9 +67,19 @@ public record AgeSkyProfile(Style style, int color, List<Body> bodies, int stati
"sky/" + (style == Style.INHERITED ? "inherited" : style.name().toLowerCase(java.util.Locale.ROOT))); "sky/" + (style == Style.INHERITED ? "inherited" : style.name().toLowerCase(java.util.Locale.ROOT)));
} }
/** Family default only; the ordered SKY branch still overrides it. */
public static Style defaultStyle(AgeGenerationPlan plan) {
if (plan == null || plan.biomeSelection() == null) return Style.INHERITED;
return switch (plan.biomeSelection().nativeKind()) {
case NETHER -> Style.NETHER;
case END -> Style.END;
default -> Style.INHERITED;
};
}
public static AgeSkyProfile compile(AgeGenerationPlan plan, AgeTraits traits) { public static AgeSkyProfile compile(AgeGenerationPlan plan, AgeTraits traits) {
if (plan == null) return new AgeSkyProfile(Style.INHERITED, -1, List.of()); if (plan == null) return new AgeSkyProfile(Style.INHERITED, -1, List.of());
Style style = Style.INHERITED; Style style = defaultStyle(plan);
int color = authoredSkyColor(plan); int color = authoredSkyColor(plan);
boolean customBodies = hasCustomCelestials(plan); boolean customBodies = hasCustomCelestials(plan);
List<Body> bodies = new ArrayList<>(); List<Body> bodies = new ArrayList<>();
@@ -0,0 +1,35 @@
package net.dnorberg.rivencraft.client;
import net.dnorberg.rivencraft.network.*;
import net.dnorberg.rivencraft.registry.ModItems;
import net.minecraft.client.Minecraft;
import net.neoforged.neoforge.network.PacketDistributor;
import net.neoforged.neoforge.network.handling.IPayloadContext;
/** Ground books use the existing spreads and previews, without interactive exploration. */
public final class ClientDroppedBooks {
private ClientDroppedBooks() {}
public static boolean present(DroppedBookActionPayload source) {
var mc = Minecraft.getInstance();
var entity = mc.level == null ? null : mc.level.getEntity(source.entityId());
return mc.player != null && entity instanceof net.dnorberg.rivencraft.entity.DroppedBookEntity
&& !entity.isRemoved() && entity.getUUID().equals(source.entityUuid())
&& mc.player.distanceToSqr(entity) <= 64;
}
public static void send(DroppedBookActionPayload source, DroppedBookActionPayload.Action action,
String title, boolean immersive) {
PacketDistributor.sendToServer(source.action(action, title, immersive));
}
public static void open(OpenDroppedBookScreenPayload payload, IPayloadContext context) {
context.enqueueWork(() -> {
var source = payload.source();
var mc = Minecraft.getInstance();
if (!present(source) || !mc.level.dimension().equals(payload.contents().source().dimension())) return;
if (source.book().is(ModItems.LINKING_BOOK.get()))
mc.setScreen(new net.dnorberg.rivencraft.client.screen.LinkingBookScreen(source));
else if (source.book().is(ModItems.DESCRIPTIVE_BOOK.get()))
mc.setScreen(new net.dnorberg.rivencraft.client.screen.DescriptiveBookScreen(
source, payload.contents().traits(), payload.contents().writingSymbols()));
});
}
}
@@ -10,10 +10,15 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items; import net.dnorberg.rivencraft.shared.WritingDeskDisplayModel;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.client.renderer.RenderType;
/** Visible selected page and loaded paper, as on the Legacy desk. */ /** Visible selected page and loaded paper, as on the Legacy desk. */
public final class WritingDeskRenderer implements BlockEntityRenderer<WritingDeskBlockEntity> { public final class WritingDeskRenderer implements BlockEntityRenderer<WritingDeskBlockEntity> {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(
"rivencraft", "textures/block/writing_desk.png");
public WritingDeskRenderer(BlockEntityRendererProvider.Context context) {} public WritingDeskRenderer(BlockEntityRendererProvider.Context context) {}
@Override public void render(WritingDeskBlockEntity desk, float partialTick, PoseStack pose, @Override public void render(WritingDeskBlockEntity desk, float partialTick, PoseStack pose,
@@ -25,22 +30,26 @@ public final class WritingDeskRenderer implements BlockEntityRenderer<WritingDes
pose.translate(0.5, 0, 0.5); pose.translate(0.5, 0, 0.5);
pose.mulPose(Axis.YP.rotationDegrees( pose.mulPose(Axis.YP.rotationDegrees(
180.0F - desk.getBlockState().getValue(WritingDeskBlock.FACING).toYRot())); 180.0F - desk.getBlockState().getValue(WritingDeskBlock.FACING).toYRot()));
if (paper > 0) { var vertices = buffers.getBuffer(RenderType.entitySolid(TEXTURE));
ItemStack sheet = new ItemStack(Items.PAPER); for (var face : WritingDeskDisplayModel.paper(paper)) {
int layers = Math.min(4, 1 + paper / 16); for (var vertex : face.vertices()) {
for (int i = 0; i < layers; i++) { vertices.addVertex(pose.last(), vertex.x(), vertex.y(), vertex.z())
drawFlat(desk, sheet, pose, buffers, light, overlay, 1.22, 0.27 + i * 0.008, -0.14, 0.55F); .setColor(face.color()).setUv(vertex.u(), vertex.v())
.setOverlay(overlay).setLight(light)
.setNormal(pose.last(), face.nx(), face.ny(), face.nz());
} }
} }
if (!page.isEmpty()) { if (!page.isEmpty()) {
drawFlat(desk, page, pose, buffers, light, overlay, 1.0, 0.572, 0.0, 0.8F); drawFlat(page, pose, buffers, light, overlay,
WritingDeskDisplayModel.PAGE_X, WritingDeskDisplayModel.PAGE_Y,
WritingDeskDisplayModel.PAGE_Z, WritingDeskDisplayModel.PAGE_SCALE, desk);
} }
pose.popPose(); pose.popPose();
} }
private static void drawFlat(WritingDeskBlockEntity desk, ItemStack stack, PoseStack pose, private static void drawFlat(ItemStack stack, PoseStack pose,
MultiBufferSource buffers, int light, int overlay, MultiBufferSource buffers, int light, int overlay,
double x, double y, double z, float scale) { double x, double y, double z, float scale, WritingDeskBlockEntity desk) {
pose.pushPose(); pose.pushPose();
pose.translate(x, y, z); pose.translate(x, y, z);
pose.mulPose(Axis.XP.rotationDegrees(90)); pose.mulPose(Axis.XP.rotationDegrees(90));
@@ -58,6 +58,7 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
private final String author; private final String author;
private final InteractionHand hand; private final InteractionHand hand;
private final BlockPos bookStandPos; private final BlockPos bookStandPos;
private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource;
private DestinationPreviewRenderer preview; private DestinationPreviewRenderer preview;
private EditBox titleInput; private EditBox titleInput;
private Button exploreButton; private Button exploreButton;
@@ -96,6 +97,12 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
this.bookStandPos = bookStandPos.immutable(); this.bookStandPos = bookStandPos.immutable();
} }
public DescriptiveBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source,
@Nullable AgeTraits traits, List<SymbolDisplayMetadata> symbols) {
this(InteractionHand.MAIN_HAND, source.book(), traits, symbols);
droppedSource = source;
}
@Override @Override
protected void init() { protected void init() {
int left = (width - BOOK_WIDTH) / 2; int left = (width - BOOK_WIDTH) / 2;
@@ -127,23 +134,33 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
EXPLORE_ICON, button -> enterExploreOverlay()) EXPLORE_ICON, button -> enterExploreOverlay())
.bounds(left + 229, top + 145, 20, 20) .bounds(left + 229, top + 145, 20, 20)
.tooltip(Tooltip.create(Component.translatable("screen.rivencraft.book.explore"))).build()); .tooltip(Tooltip.create(Component.translatable("screen.rivencraft.book.explore"))).build());
exploreButton.active = bookStandPos == null; exploreButton.active = bookStandPos == null && droppedSource == null;
exploreButton.visible = pageIndex == 0; exploreButton.visible = pageIndex == 0;
} }
if (requestPreview) { if (requestPreview) {
PacketDistributor.sendToServer(new RequestLinkPreviewPayload( if (droppedSource != null) {
net.dnorberg.rivencraft.client.ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.PREVIEW, "",
preview.supportsExploration());
} else {
PacketDistributor.sendToServer(new RequestLinkPreviewPayload(
true, true,
bookStandPos != null, bookStandPos != null,
bookStandPos == null && hand == InteractionHand.OFF_HAND, bookStandPos == null && hand == InteractionHand.OFF_HAND,
bookStandPos == null ? BlockPos.ZERO : bookStandPos, bookStandPos == null ? BlockPos.ZERO : bookStandPos,
preview.supportsExploration() preview.supportsExploration()
)); ));
}
} }
} }
} }
@Override @Override
public void tick() { public void tick() {
if (droppedSource != null && !net.dnorberg.rivencraft.client.ClientDroppedBooks.present(droppedSource)) {
onClose();
return;
}
if (preview != null) { if (preview != null) {
preview.tick(); preview.tick();
} }
@@ -386,7 +403,7 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
} }
private void enterExploreOverlay() { private void enterExploreOverlay() {
if (bookStandPos != null) { if (bookStandPos != null || droppedSource != null) {
return; return;
} }
preview.setExploring(true); preview.setExploring(true);
@@ -444,6 +461,12 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
} }
private void link() { private void link() {
if (droppedSource != null) {
net.dnorberg.rivencraft.client.ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.USE, "", false);
onClose();
return;
}
PacketDistributor.sendToServer(new UseDescriptiveBookPayload( PacketDistributor.sendToServer(new UseDescriptiveBookPayload(
bookStandPos != null, bookStandPos != null,
bookStandPos == null && hand == InteractionHand.OFF_HAND, bookStandPos == null && hand == InteractionHand.OFF_HAND,
@@ -457,12 +480,17 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
if (name.isEmpty()) { if (name.isEmpty()) {
return; return;
} }
PacketDistributor.sendToServer(new BindDescriptiveBookPayload( if (droppedSource != null) {
net.dnorberg.rivencraft.client.ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.BIND, name, false);
} else {
PacketDistributor.sendToServer(new BindDescriptiveBookPayload(
bookStandPos != null, bookStandPos != null,
bookStandPos == null && hand == InteractionHand.OFF_HAND, bookStandPos == null && hand == InteractionHand.OFF_HAND,
bookStandPos == null ? BlockPos.ZERO : bookStandPos, bookStandPos == null ? BlockPos.ZERO : bookStandPos,
name name
)); ));
}
onClose(); onClose();
} }
@@ -44,6 +44,7 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr
private final ItemStack book; private final ItemStack book;
private final LinkTarget target; private final LinkTarget target;
private final BlockPos bookStandPos; private final BlockPos bookStandPos;
private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource;
private DestinationPreviewRenderer preview; private DestinationPreviewRenderer preview;
private EditBox titleInput; private EditBox titleInput;
private Button exploreButton; private Button exploreButton;
@@ -68,6 +69,11 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr
this.bookStandPos = bookStandPos.immutable(); this.bookStandPos = bookStandPos.immutable();
} }
public LinkingBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source) {
this(InteractionHand.MAIN_HAND, source.book());
droppedSource = source;
}
@Override @Override
protected void init() { protected void init() {
int left = (width - BOOK_WIDTH) / 2; int left = (width - BOOK_WIDTH) / 2;
@@ -99,23 +105,33 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr
EXPLORE_ICON, button -> enterExploreOverlay()) EXPLORE_ICON, button -> enterExploreOverlay())
.bounds(left + 229, top + 145, 20, 20) .bounds(left + 229, top + 145, 20, 20)
.tooltip(Tooltip.create(Component.translatable("screen.rivencraft.book.explore"))).build()); .tooltip(Tooltip.create(Component.translatable("screen.rivencraft.book.explore"))).build());
exploreButton.active = bookStandPos == null; exploreButton.active = bookStandPos == null && droppedSource == null;
exploreButton.visible = pageIndex == 0; exploreButton.visible = pageIndex == 0;
} }
if (requestPreview) { if (requestPreview) {
PacketDistributor.sendToServer(new RequestLinkPreviewPayload( if (droppedSource != null) {
net.dnorberg.rivencraft.client.ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.PREVIEW, "",
preview.supportsExploration());
} else {
PacketDistributor.sendToServer(new RequestLinkPreviewPayload(
false, false,
bookStandPos != null, bookStandPos != null,
bookStandPos == null && hand == InteractionHand.OFF_HAND, bookStandPos == null && hand == InteractionHand.OFF_HAND,
bookStandPos == null ? BlockPos.ZERO : bookStandPos, bookStandPos == null ? BlockPos.ZERO : bookStandPos,
preview.supportsExploration() preview.supportsExploration()
)); ));
}
} }
} }
} }
@Override @Override
public void tick() { public void tick() {
if (droppedSource != null && !net.dnorberg.rivencraft.client.ClientDroppedBooks.present(droppedSource)) {
onClose();
return;
}
if (preview != null) { if (preview != null) {
preview.tick(); preview.tick();
} }
@@ -263,7 +279,7 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr
} }
private void enterExploreOverlay() { private void enterExploreOverlay() {
if (bookStandPos != null) { if (bookStandPos != null || droppedSource != null) {
return; return;
} }
preview.setExploring(true); preview.setExploring(true);
@@ -329,12 +345,23 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr
private void bind() { private void bind() {
String name = titleInput.getValue().strip(); String name = titleInput.getValue().strip();
if (!name.isEmpty()) { if (!name.isEmpty()) {
PacketDistributor.sendToServer(new BindLinkingBookPayload(hand == InteractionHand.OFF_HAND, name)); if (droppedSource != null) {
net.dnorberg.rivencraft.client.ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.BIND, name, false);
} else {
PacketDistributor.sendToServer(new BindLinkingBookPayload(hand == InteractionHand.OFF_HAND, name));
}
onClose(); onClose();
} }
} }
private void link() { private void link() {
if (droppedSource != null) {
net.dnorberg.rivencraft.client.ClientDroppedBooks.send(droppedSource,
net.dnorberg.rivencraft.network.DroppedBookActionPayload.Action.USE, "", false);
onClose();
return;
}
if (bookStandPos == null) { if (bookStandPos == null) {
PacketDistributor.sendToServer(new UseLinkingBookPayload(hand == InteractionHand.OFF_HAND)); PacketDistributor.sendToServer(new UseLinkingBookPayload(hand == InteractionHand.OFF_HAND));
} else { } else {
@@ -183,10 +183,10 @@ public final class RivencraftCommands {
if (age.instability().version() >= 2) { if (age.instability().version() >= 2) {
int ageSamples = ageLevel == null ? 0 int ageSamples = ageLevel == null ? 0
: net.dnorberg.rivencraft.book.AgeBlockInstability.sampledChunks(ageLevel); : net.dnorberg.rivencraft.book.AgeBlockInstability.sampledChunks(ageLevel);
int baselineSamples = net.dnorberg.rivencraft.book.AgeBlockInstability.sampledChunks( int baselineSamples = net.dnorberg.rivencraft.book.AgeBlockInstability.baselineSamples(source.getServer());
source.getServer().overworld());
source.sendSuccess(() -> Component.literal("Block profile: Age " + ageSamples source.sendSuccess(() -> Component.literal("Block profile: Age " + ageSamples
+ "/401, Overworld baseline " + baselineSamples + "/500" + "/401, baseline " + baselineSamples + "/500 ["
+ net.dnorberg.rivencraft.book.AgeBlockInstability.baselineStatus(source.getServer()) + "]"
+ (ageLevel == null ? " (Age unloaded)" : "")), false); + (ageLevel == null ? " (Age unloaded)" : "")), false);
source.sendSuccess(() -> Component.literal("Modded materials: automatic when installed, " source.sendSuccess(() -> Component.literal("Modded materials: automatic when installed, "
+ RivencraftConfig.moddedMaterialOverrides().size() + " exact block override(s)"), false); + RivencraftConfig.moddedMaterialOverrides().size() + " exact block override(s)"), false);
@@ -37,6 +37,8 @@ public final class RivencraftConfig {
private static final ModConfigSpec.IntValue INSTABILITY_MAX_CHUNKS; private static final ModConfigSpec.IntValue INSTABILITY_MAX_CHUNKS;
private static final ModConfigSpec.IntValue ACCELERATED_MAX_CHUNKS; private static final ModConfigSpec.IntValue ACCELERATED_MAX_CHUNKS;
private static final ModConfigSpec.IntValue ACCELERATED_MAX_ATTEMPTS; private static final ModConfigSpec.IntValue ACCELERATED_MAX_ATTEMPTS;
private static final ModConfigSpec.IntValue ACCELERATED_MACHINE_CANDIDATES;
private static final ModConfigSpec.IntValue ACCELERATED_MACHINE_TICKS;
private static final ModConfigSpec.ConfigValue<List<? extends String>> MODDED_MATERIAL_OVERRIDES; private static final ModConfigSpec.ConfigValue<List<? extends String>> MODDED_MATERIAL_OVERRIDES;
private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_ENABLED; private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_ENABLED;
private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_PLAYERS; private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_PLAYERS;
@@ -135,8 +137,12 @@ public final class RivencraftConfig {
builder.push("accelerated_age"); builder.push("accelerated_age");
ACCELERATED_MAX_CHUNKS = builder.comment("Maximum already-loaded chunks given extra random ticks per Age tick.") ACCELERATED_MAX_CHUNKS = builder.comment("Maximum already-loaded chunks given extra random ticks per Age tick.")
.defineInRange("max_loaded_chunks", 8, 1, 64); .defineInRange("max_loaded_chunks", 8, 1, 64);
ACCELERATED_MAX_ATTEMPTS = builder.comment("Maximum extra random-tick positions sampled per Age tick, shared fairly across loaded sections; zero disables the Accelerated page effect. The previous 1024-attempt default capped heavily accelerated Ages too early.") ACCELERATED_MAX_ATTEMPTS = builder.comment("Maximum extra random-tick positions sampled per Age tick, shared fairly across loaded sections; zero disables extra random ticks. The previous 1024-attempt default capped heavily accelerated Ages too early.")
.defineInRange("max_random_tick_attempts_per_tick", 16384, 0, 65536); .defineInRange("max_random_tick_attempts_per_tick", 16384, 0, 65536);
ACCELERATED_MACHINE_CANDIDATES = builder.comment("Maximum registered server machine tickers inspected per Age tick; rotates fairly without loading chunks.")
.defineInRange("max_machine_candidates_per_tick", 1024, 1, 65536);
ACCELERATED_MACHINE_TICKS = builder.comment("Maximum extra machine ticker calls per Age tick, shared round-robin. Each Accelerated page requests one extra tick per machine; zero disables machine acceleration independently of random ticks.")
.defineInRange("max_machine_ticks_per_tick", 4096, 0, 65536);
builder.pop(); builder.pop();
builder.push("instability_modded_materials"); builder.push("instability_modded_materials");
MODDED_MATERIAL_OVERRIDES = builder.comment( MODDED_MATERIAL_OVERRIDES = builder.comment(
@@ -279,6 +285,8 @@ public final class RivencraftConfig {
public static int instabilityMaxLevel() { return INSTABILITY_MAX_LEVEL.get(); } public static int instabilityMaxLevel() { return INSTABILITY_MAX_LEVEL.get(); }
public static int instabilityMaxChunks() { return INSTABILITY_MAX_CHUNKS.get(); } public static int instabilityMaxChunks() { return INSTABILITY_MAX_CHUNKS.get(); }
public static int acceleratedMaxChunks() { return ACCELERATED_MAX_CHUNKS.get(); } public static int acceleratedMaxChunks() { return ACCELERATED_MAX_CHUNKS.get(); }
public static int acceleratedMachineCandidates() { return ACCELERATED_MACHINE_CANDIDATES.get(); }
public static int acceleratedMachineTicks() { return ACCELERATED_MACHINE_TICKS.get(); }
public static int acceleratedMaxAttempts() { return ACCELERATED_MAX_ATTEMPTS.get(); } public static int acceleratedMaxAttempts() { return ACCELERATED_MAX_ATTEMPTS.get(); }
public static List<? extends String> moddedMaterialOverrides() { return MODDED_MATERIAL_OVERRIDES.get(); } public static List<? extends String> moddedMaterialOverrides() { return MODDED_MATERIAL_OVERRIDES.get(); }
@@ -8,7 +8,7 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
/** A recoverable, model-rendered book left behind by handheld linking. */ /** A recoverable, model-rendered book used for every Linking/Descriptive Book drop. */
public final class DroppedBookEntity extends ItemEntity { public final class DroppedBookEntity extends ItemEntity {
private static final String DECAY_TICKS_TAG = "BookDecayTicks"; private static final String DECAY_TICKS_TAG = "BookDecayTicks";
private static final int SLOW_DECAY_INTERVAL = 10_000; private static final int SLOW_DECAY_INTERVAL = 10_000;
@@ -27,6 +27,20 @@ public final class DroppedBookEntity extends ItemEntity {
setPickUpDelay(20); setPickUpDelay(20);
} }
/** Preserve a toss/load's native item state; do not use departure offset/motion rules. */
public static DroppedBookEntity fromDrop(ItemEntity source) {
DroppedBookEntity book = new DroppedBookEntity(ModEntities.DROPPED_BOOK.get(), source.level());
book.restoreFrom(source);
// Entity.load clamps unusually fast motion; a live toss must retain its exact transform.
book.copyPosition(source);
book.setDeltaMovement(source.getDeltaMovement());
// Keep the source registered until replacement succeeds, so give the new entity its own UUID.
book.setUUID(java.util.UUID.randomUUID());
book.setItem(source.getItem().copy());
book.setUnlimitedLifetime();
return book;
}
/** Vanilla's pickup particle calls ItemEntity.copy() and renders the returned entity. */ /** Vanilla's pickup particle calls ItemEntity.copy() and renders the returned entity. */
@Override @Override
public DroppedBookEntity copy() { public DroppedBookEntity copy() {
@@ -37,6 +51,37 @@ public final class DroppedBookEntity extends ItemEntity {
return copy; return copy;
} }
/** Contact must never take a book away from its world GUI. */
@Override public void playerTouch(net.minecraft.world.entity.player.Player player) {}
@Override public boolean isPickable() { return !isRemoved() && !getItem().isEmpty(); }
@Override
public net.minecraft.world.InteractionResult interact(net.minecraft.world.entity.player.Player player,
net.minecraft.world.InteractionHand hand) {
if (level().isClientSide()) return net.minecraft.world.InteractionResult.SUCCESS;
if (!(player instanceof net.minecraft.server.level.ServerPlayer serverPlayer)
|| !player.isAlive() || player.isSpectator() || player.distanceToSqr(this) > 64
|| isRemoved() || getItem().isEmpty()) return net.minecraft.world.InteractionResult.PASS;
if (player.isShiftKeyDown()) {
// Explicit interaction uses normal ownership, delay, inventory and NeoForge pickup hooks.
super.playerTouch(player);
} else {
net.dnorberg.rivencraft.network.ModNetworking.openDroppedBook(serverPlayer, this);
}
return net.minecraft.world.InteractionResult.SUCCESS;
}
/** Only the nearby, still-present world book can authorize an action or preview. */
public static DroppedBookEntity validated(net.minecraft.server.level.ServerPlayer player,
int id, java.util.UUID uuid, ItemStack expected) {
var entity = player.level().getEntity(id);
return player.isAlive() && !player.isSpectator()
&& entity instanceof DroppedBookEntity book && !book.isRemoved() && !book.getItem().isEmpty() && book.isAddedToLevel()
&& book.getUUID().equals(uuid) && player.distanceToSqr(book) <= 64
&& ItemStack.matches(book.getItem(), expected) ? book : null;
}
@Override @Override
public void tick() { public void tick() {
super.tick(); super.tick();
@@ -0,0 +1,38 @@
package net.dnorberg.rivencraft.event;
import net.dnorberg.rivencraft.Rivencraft;
import net.dnorberg.rivencraft.entity.DroppedBookEntity;
import net.dnorberg.rivencraft.registry.ModItems;
import net.minecraft.server.TickTask;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
/** Converts ordinary book drops from every source, including entities restored from disk. */
@EventBusSubscriber(modid = Rivencraft.MOD_ID)
public final class DroppedBookConversionHandler {
private DroppedBookConversionHandler() {}
@SubscribeEvent(priority = EventPriority.LOWEST)
public static void onJoin(EntityJoinLevelEvent event) {
if (!(event.getLevel() instanceof ServerLevel level)
|| !(event.getEntity() instanceof ItemEntity item) || item instanceof DroppedBookEntity
|| !isBook(item.getItem())) return;
// Join events can run before chunk promotion. Do not add another entity inside that callback.
// Keep the original until the queued replacement has actually been accepted.
level.getServer().tell(new TickTask(0, () -> {
if (level.getServer().getLevel(level.dimension()) != level || item.isRemoved()
|| !item.isAddedToLevel() || item.level() != level || !isBook(item.getItem())) return;
var replacement = DroppedBookEntity.fromDrop(item);
if (level.addFreshEntity(replacement)) item.discard();
}));
}
private static boolean isBook(ItemStack stack) {
return stack.is(ModItems.LINKING_BOOK.get()) || stack.is(ModItems.DESCRIPTIVE_BOOK.get());
}
}
@@ -0,0 +1,13 @@
package net.dnorberg.rivencraft.mixin;
import java.util.List;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.TickingBlockEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(Level.class)
public interface LevelBlockEntityTickersAccessor {
@Accessor("blockEntityTickers")
List<TickingBlockEntity> rivencraft$blockEntityTickers();
}
@@ -0,0 +1,29 @@
package net.dnorberg.rivencraft.network;
import java.util.UUID;
import net.dnorberg.rivencraft.Rivencraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
/** The stack is an expected identity, never an authoritative destination. */
public record DroppedBookActionPayload(int entityId, UUID entityUuid, ItemStack book,
Action action, String title, boolean immersive) implements CustomPacketPayload {
public enum Action { USE, BIND, PREVIEW }
public static final Type<DroppedBookActionPayload> TYPE = new Type<>(
ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, "dropped_book_action"));
public static final StreamCodec<RegistryFriendlyByteBuf, DroppedBookActionPayload> STREAM_CODEC =
StreamCodec.of((buf, value) -> {
buf.writeVarInt(value.entityId()); buf.writeUUID(value.entityUuid());
ItemStack.STREAM_CODEC.encode(buf, value.book()); buf.writeEnum(value.action());
buf.writeUtf(value.title(), 32); buf.writeBoolean(value.immersive());
}, buf -> new DroppedBookActionPayload(buf.readVarInt(), buf.readUUID(),
ItemStack.STREAM_CODEC.decode(buf), buf.readEnum(Action.class),
buf.readUtf(32), buf.readBoolean()));
public DroppedBookActionPayload action(Action action, String title, boolean immersive) {
return new DroppedBookActionPayload(entityId, entityUuid, book.copy(), action, title, immersive);
}
@Override public Type<? extends CustomPacketPayload> type() { return TYPE; }
}
@@ -61,7 +61,7 @@ public final class ModNetworking {
} }
public static void register(RegisterPayloadHandlersEvent event) { public static void register(RegisterPayloadHandlersEvent event) {
PayloadRegistrar registrar = event.registrar("19"); PayloadRegistrar registrar = event.registrar("20");
registrar.playToServer(RequestDescriptiveBookScreenPayload.TYPE, RequestDescriptiveBookScreenPayload.STREAM_CODEC, registrar.playToServer(RequestDescriptiveBookScreenPayload.TYPE, RequestDescriptiveBookScreenPayload.STREAM_CODEC,
ModNetworking::requestDescriptiveBookScreen); ModNetworking::requestDescriptiveBookScreen);
registrar.playToClient(OpenDescriptiveBookScreenPayload.TYPE, OpenDescriptiveBookScreenPayload.STREAM_CODEC, registrar.playToClient(OpenDescriptiveBookScreenPayload.TYPE, OpenDescriptiveBookScreenPayload.STREAM_CODEC,
@@ -77,6 +77,12 @@ public final class ModNetworking {
ModNetworking::requestLinkPreview); ModNetworking::requestLinkPreview);
registrar.playToServer(ReleaseLinkPreviewPayload.TYPE, ReleaseLinkPreviewPayload.STREAM_CODEC, registrar.playToServer(ReleaseLinkPreviewPayload.TYPE, ReleaseLinkPreviewPayload.STREAM_CODEC,
(payload, context) -> releaseLinkPreview(context)); (payload, context) -> releaseLinkPreview(context));
registrar.playToClient(OpenDroppedBookScreenPayload.TYPE, OpenDroppedBookScreenPayload.STREAM_CODEC,
(payload, context) -> net.dnorberg.rivencraft.client.ClientDroppedBooks.open(payload, context));
registrar.playToServer(DroppedBookActionPayload.TYPE, DroppedBookActionPayload.STREAM_CODEC,
(payload, context) -> {
if (context.player() instanceof ServerPlayer player) droppedBookAction(player, payload);
});
registrar.playToClient(LinkPreviewPayload.TYPE, LinkPreviewPayload.STREAM_CODEC, registrar.playToClient(LinkPreviewPayload.TYPE, LinkPreviewPayload.STREAM_CODEC,
ClientLinkPreviewHandler::handle); ClientLinkPreviewHandler::handle);
registrar.playToClient(AgeCelestialAnglePayload.TYPE, AgeCelestialAnglePayload.STREAM_CODEC, registrar.playToClient(AgeCelestialAnglePayload.TYPE, AgeCelestialAnglePayload.STREAM_CODEC,
@@ -136,29 +142,36 @@ public final class ModNetworking {
if (access == null || WRITING_BOOKS.contains(access.stack())) { if (access == null || WRITING_BOOKS.contains(access.stack())) {
return; return;
} }
AgeReference reference = access.stack().get(ModDataComponents.AGE_REFERENCE.get()); var contents = describeBook(player, access.stack(), payload.fromStand(), payload.offhand(), payload.standPos());
access.sync().run();
PacketDistributor.sendToPlayer(player, contents);
}
private static OpenDescriptiveBookScreenPayload describeBook(ServerPlayer player, ItemStack stack,
boolean fromStand, boolean offhand, BlockPos standPos) {
AgeReference reference = stack.get(ModDataComponents.AGE_REFERENCE.get());
var definition = reference == null var definition = reference == null
? null ? null
: AgeRegistrySavedData.get(player.serverLevel()).find(reference.id()).orElse(null); : AgeRegistrySavedData.get(player.serverLevel()).find(reference.id()).orElse(null);
if (definition != null && !access.stack().has(ModDataComponents.AGE_GENERATION_PROFILE.get())) { if (definition != null && !stack.has(ModDataComponents.AGE_GENERATION_PROFILE.get())) {
access.stack().set(ModDataComponents.AGE_GENERATION_PROFILE.get(), definition.generationProfile()); stack.set(ModDataComponents.AGE_GENERATION_PROFILE.get(), definition.generationProfile());
access.sync().run();
} }
// Requests run on the same server thread as Age creation. A request queued // Requests run on the same server thread as Age creation. A request queued
// during generation can only open the finished book, never a stale client copy. // during generation can only open the finished book, never a stale client copy.
player.inventoryMenu.broadcastChanges(); player.inventoryMenu.broadcastChanges();
OrderedWriting writing = access.stack() OrderedWriting writing = stack
.getOrDefault(ModDataComponents.BOOK_WRITING.get(), OrderedWriting.EMPTY); .getOrDefault(ModDataComponents.BOOK_WRITING.get(), OrderedWriting.EMPTY);
List<SymbolDisplayMetadata> writingSymbols = writing.entries().stream() List<SymbolDisplayMetadata> writingSymbols = writing.entries().stream()
.filter(entry -> entry.kind() == WritingEntry.Kind.SYMBOL) .filter(entry -> entry.kind() == WritingEntry.Kind.SYMBOL)
.map(entry -> SymbolCatalog.display(entry.symbol().orElseThrow())) .map(entry -> SymbolCatalog.display(entry.symbol().orElseThrow()))
.toList(); .toList();
PacketDistributor.sendToPlayer(player, new OpenDescriptiveBookScreenPayload( return new OpenDescriptiveBookScreenPayload(
payload.fromStand(), payload.offhand(), fromStand, offhand,
GlobalPos.of(player.level().dimension(), payload.standPos()), access.stack().copy(), GlobalPos.of(player.level().dimension(), standPos), stack.copy(),
definition == null ? null : definition.plan() != null && definition.plan().biomeSelection() != null definition == null ? null : definition.plan() != null && definition.plan().biomeSelection() != null
? definition.traits().withBiomeDistribution(definition.plan().biomeSelection().distribution()) ? definition.traits().withBiomeDistribution(definition.plan().biomeSelection().distribution())
: definition.traits(), writingSymbols)); : definition.traits(), writingSymbols);
} }
private static void bindDescriptiveBook(BindDescriptiveBookPayload payload, IPayloadContext context) { private static void bindDescriptiveBook(BindDescriptiveBookPayload payload, IPayloadContext context) {
@@ -167,11 +180,15 @@ public final class ModNetworking {
} }
BookAccess access = descriptiveBookAccess(player, payload.fromStand(), payload.offhand(), payload.standPos()); BookAccess access = descriptiveBookAccess(player, payload.fromStand(), payload.offhand(), payload.standPos());
bindDescriptive(player, access, payload.title());
}
private static void bindDescriptive(ServerPlayer player, BookAccess access, String requestedTitle) {
if (access == null || WRITING_BOOKS.contains(access.stack()) if (access == null || WRITING_BOOKS.contains(access.stack())
|| access.stack().has(ModDataComponents.AGE_REFERENCE.get())) { || access.stack().has(ModDataComponents.AGE_REFERENCE.get())) {
return; return;
} }
String title = normalizeTitle(payload.title()); String title = normalizeTitle(requestedTitle);
if (title.isEmpty()) { if (title.isEmpty()) {
return; return;
} }
@@ -223,11 +240,15 @@ public final class ModNetworking {
} }
ItemStack stack = player.getItemInHand(hand(payload.offhand())); ItemStack stack = player.getItemInHand(hand(payload.offhand()));
bindLinking(player, stack, payload.title());
}
private static void bindLinking(ServerPlayer player, ItemStack stack, String requestedTitle) {
if (!stack.is(ModItems.LINKING_BOOK.get()) || stack.has(ModDataComponents.LINK_TARGET.get())) { if (!stack.is(ModItems.LINKING_BOOK.get()) || stack.has(ModDataComponents.LINK_TARGET.get())) {
return; return;
} }
String title = normalizeTitle(payload.title()); String title = normalizeTitle(requestedTitle);
if (title.isEmpty()) { if (title.isEmpty()) {
return; return;
} }
@@ -301,13 +322,18 @@ public final class ModNetworking {
stack = player.getItemInHand(hand(payload.offhand())); stack = player.getItemInHand(hand(payload.offhand()));
} }
requestPreview(player, stack, payload.descriptiveBook(), payload.immersivePortal());
}
private static void requestPreview(ServerPlayer player, ItemStack stack, boolean descriptiveBook,
boolean immersivePortal) {
LinkTarget target; LinkTarget target;
if (payload.descriptiveBook() && stack.is(ModItems.DESCRIPTIVE_BOOK.get())) { if (descriptiveBook && stack.is(ModItems.DESCRIPTIVE_BOOK.get())) {
AgeReference age = stack.get(ModDataComponents.AGE_REFERENCE.get()); AgeReference age = stack.get(ModDataComponents.AGE_REFERENCE.get());
target = age == null ? null : AgeDimensionService.resolve(player, age, OrderedWriting.EMPTY, target = age == null ? null : AgeDimensionService.resolve(player, age, OrderedWriting.EMPTY,
!stack.getOrDefault(ModDataComponents.LINK_PROPERTIES.get(), LinkProperties.NONE) !stack.getOrDefault(ModDataComponents.LINK_PROPERTIES.get(), LinkProperties.NONE)
.has(LinkProperties.DISABLE_PLATFORM)).orElse(null); .has(LinkProperties.DISABLE_PLATFORM)).orElse(null);
} else if (!payload.descriptiveBook() && stack.is(ModItems.LINKING_BOOK.get())) { } else if (!descriptiveBook && stack.is(ModItems.LINKING_BOOK.get())) {
target = stack.get(ModDataComponents.LINK_TARGET.get()); target = stack.get(ModDataComponents.LINK_TARGET.get());
} else { } else {
target = null; target = null;
@@ -327,7 +353,7 @@ public final class ModNetworking {
} }
BlockPos origin = LinkingService.resolveDestination( BlockPos origin = LinkingService.resolveDestination(
level, target.location().pos(), payload.descriptiveBook()) level, target.location().pos(), descriptiveBook)
.map(BlockPos::containing) .map(BlockPos::containing)
.orElse(target.location().pos()); .orElse(target.location().pos());
List<LinkPreviewPayload.SnapshotBlock> blocks = new ArrayList<>(); List<LinkPreviewPayload.SnapshotBlock> blocks = new ArrayList<>();
@@ -345,13 +371,41 @@ public final class ModNetworking {
} }
} }
int skyColor = previewSkyColor(level, origin); int skyColor = previewSkyColor(level, origin);
if (payload.immersivePortal() && ModList.get().isLoaded("immersive_portals_core")) { if (immersivePortal && ModList.get().isLoaded("immersive_portals_core")) {
ImmersivePortalsChunkLoaders.open(player, level, origin); ImmersivePortalsChunkLoaders.open(player, level, origin);
} }
PacketDistributor.sendToPlayer(player, new LinkPreviewPayload( PacketDistributor.sendToPlayer(player, new LinkPreviewPayload(
target.location().dimension(), origin, target.yaw(), target.pitch(), skyColor, List.copyOf(blocks))); target.location().dimension(), origin, target.yaw(), target.pitch(), skyColor, List.copyOf(blocks)));
} }
public static void openDroppedBook(ServerPlayer player, net.dnorberg.rivencraft.entity.DroppedBookEntity entity) {
var contents = describeBook(player, entity.getItem(), false, false, entity.blockPosition());
entity.setItem(entity.getItem().copy());
var source = new DroppedBookActionPayload(entity.getId(), entity.getUUID(), entity.getItem().copy(),
DroppedBookActionPayload.Action.USE, "", false);
PacketDistributor.sendToPlayer(player, new OpenDroppedBookScreenPayload(source, contents));
}
public static void droppedBookAction(ServerPlayer player, DroppedBookActionPayload payload) {
var entity = net.dnorberg.rivencraft.entity.DroppedBookEntity.validated(
player, payload.entityId(), payload.entityUuid(), payload.book());
if (entity == null) return;
var stack = entity.getItem();
switch (payload.action()) {
case USE -> {
if (stack.is(ModItems.LINKING_BOOK.get())) LinkingBookItem.useBoundBook(player, stack);
else if (stack.is(ModItems.DESCRIPTIVE_BOOK.get())) DescriptiveBookItem.useWrittenBook(player, stack);
}
case BIND -> {
if (stack.is(ModItems.LINKING_BOOK.get())) bindLinking(player, stack, payload.title());
else if (stack.is(ModItems.DESCRIPTIVE_BOOK.get()))
bindDescriptive(player, new BookAccess(stack, () -> entity.setItem(stack.copy())), payload.title());
entity.setItem(stack.copy());
}
case PREVIEW -> requestPreview(player, stack, stack.is(ModItems.DESCRIPTIVE_BOOK.get()), payload.immersive());
}
}
private static void releaseLinkPreview(IPayloadContext context) { private static void releaseLinkPreview(IPayloadContext context) {
if (context.player() instanceof ServerPlayer player && ModList.get().isLoaded("immersive_portals_core")) { if (context.player() instanceof ServerPlayer player && ModList.get().isLoaded("immersive_portals_core")) {
ImmersivePortalsChunkLoaders.close(player); ImmersivePortalsChunkLoaders.close(player);
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more