diff --git a/README.md b/README.md index 8d9d6c5..60a9dcb 100644 --- a/README.md +++ b/README.md @@ -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 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.0.12** and **26.3.0.15**, with separate Minecraft-specific JARs and saves. 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 @@ -20,9 +20,10 @@ 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) and [parity review](docs/MC263_PARITY_REVIEW.md). -These releases add [Native biome-family Pages](docs/NATIVE_BIOME_FAMILIES.md), -[desert vegetation](docs/DESERT_VEGETATION.md) and Number-controlled -[Static Sky resolution](docs/STATIC_SKY_RESOLUTION.md). +These releases add [Accelerated machine ticking](docs/ACCELERATED_MACHINES.md), +correct [Writing Desk displays](docs/WRITING_DESK_MODEL.md), restore +[Legacy-style dropped-book interaction](docs/DROPPED_BOOKS.md), and use +[default block baselines](docs/BLOCK_BASELINE.md) for void/skyblock Overworlds. 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. Install only one fork; built-in animations work without either. @@ -57,7 +58,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 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, -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 @@ -132,8 +135,7 @@ The JAR is written to `build/libs/`. Development runs need the required mods; see [GameTest guidance](docs/GAMETESTS.md) for focused archived suites. New versions prefix the Minecraft version, followed by the milestone/release 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 -numbers until that line's next code release. See the [release workflow](docs/DUAL_VERSION_RELEASE.md). +`rivencraft-26.3.0.1.jar`. Both supported tracks now use this scheme. See the [release workflow](docs/DUAL_VERSION_RELEASE.md). Rivencraft is licensed under LGPL-3.0-or-later. Legacy-derived material is credited in [NOTICE](NOTICE) and [asset provenance](docs/ASSET_PROVENANCE.md). diff --git a/RELEASE_NOTES_1.21.1.0.10.md b/RELEASE_NOTES_1.21.1.0.10.md new file mode 100644 index 0000000..10d1f22 --- /dev/null +++ b/RELEASE_NOTES_1.21.1.0.10.md @@ -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. diff --git a/RELEASE_NOTES_1.21.1.0.12.md b/RELEASE_NOTES_1.21.1.0.12.md new file mode 100644 index 0000000..eaad194 --- /dev/null +++ b/RELEASE_NOTES_1.21.1.0.12.md @@ -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. diff --git a/RELEASE_NOTES_1.21.1.0.7.md b/RELEASE_NOTES_1.21.1.0.7.md new file mode 100644 index 0000000..ca42adf --- /dev/null +++ b/RELEASE_NOTES_1.21.1.0.7.md @@ -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. diff --git a/RELEASE_NOTES_1.21.1.0.8.md b/RELEASE_NOTES_1.21.1.0.8.md new file mode 100644 index 0000000..f977a49 --- /dev/null +++ b/RELEASE_NOTES_1.21.1.0.8.md @@ -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. diff --git a/RELEASE_NOTES_1.21.1.0.9.md b/RELEASE_NOTES_1.21.1.0.9.md new file mode 100644 index 0000000..23d8a4a --- /dev/null +++ b/RELEASE_NOTES_1.21.1.0.9.md @@ -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. diff --git a/docs/ACCELERATED_MACHINES.md b/docs/ACCELERATED_MACHINES.md new file mode 100644 index 0000000..f92fae4 --- /dev/null +++ b/docs/ACCELERATED_MACHINES.md @@ -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. diff --git a/docs/BLOCK_BASELINE.md b/docs/BLOCK_BASELINE.md new file mode 100644 index 0000000..7b1f8c7 --- /dev/null +++ b/docs/BLOCK_BASELINE.md @@ -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. diff --git a/docs/DROPPED_BOOKS.md b/docs/DROPPED_BOOKS.md new file mode 100644 index 0000000..9c02937 --- /dev/null +++ b/docs/DROPPED_BOOKS.md @@ -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**. diff --git a/docs/README.md b/docs/README.md index 404967b..f75d035 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,3 +19,10 @@ former behavior or loader version. audits are intentionally retained for source attribution and migration history; these three entry points replace the former practice of treating 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) diff --git a/docs/WRITING_DESK_MODEL.md b/docs/WRITING_DESK_MODEL.md new file mode 100644 index 0000000..21bd756 --- /dev/null +++ b/docs/WRITING_DESK_MODEL.md @@ -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. diff --git a/gradle.properties b/gradle.properties index 06481bd..439e2c9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -36,7 +36,7 @@ mod_name=Rivencraft # The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. mod_license=LGPL-3.0-or-later # Minecraft.release-slice.iteration; independent of the 26.3 release track. -mod_version=1.21.1.0.6 +mod_version=1.21.1.0.12 immersive_portals_version=6.0.7 terrablender_version=4.1.0.8 serene_seasons_version_id=pHEgQQUE diff --git a/ports/mc263/README.md b/ports/mc263/README.md index e6a06b2..f601e64 100644 --- a/ports/mc263/README.md +++ b/ports/mc263/README.md @@ -1,6 +1,6 @@ # 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.0.15**, for NeoForge 26.3.0.99 and 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 features, weather/skies/celestials, libraries, crystal portals, live instability, @@ -29,7 +29,12 @@ The port feature and acceptance review is recorded in movement is disabled. The final dedicated-server restart/return check passed. 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. -See [release notes](RELEASE_NOTES_26.3.0.10.md). +See [release notes](RELEASE_NOTES_26.3.0.15.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, or the absolute base-25 Number Pages immediately before Flooded. Both-version diff --git a/ports/mc263/RELEASE_NOTES_26.3.0.11.md b/ports/mc263/RELEASE_NOTES_26.3.0.11.md new file mode 100644 index 0000000..793c3a6 --- /dev/null +++ b/ports/mc263/RELEASE_NOTES_26.3.0.11.md @@ -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. diff --git a/ports/mc263/RELEASE_NOTES_26.3.0.12.md b/ports/mc263/RELEASE_NOTES_26.3.0.12.md new file mode 100644 index 0000000..3a26304 --- /dev/null +++ b/ports/mc263/RELEASE_NOTES_26.3.0.12.md @@ -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. diff --git a/ports/mc263/RELEASE_NOTES_26.3.0.13.md b/ports/mc263/RELEASE_NOTES_26.3.0.13.md new file mode 100644 index 0000000..adff4ce --- /dev/null +++ b/ports/mc263/RELEASE_NOTES_26.3.0.13.md @@ -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. diff --git a/ports/mc263/RELEASE_NOTES_26.3.0.15.md b/ports/mc263/RELEASE_NOTES_26.3.0.15.md new file mode 100644 index 0000000..bc76f06 --- /dev/null +++ b/ports/mc263/RELEASE_NOTES_26.3.0.15.md @@ -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. diff --git a/ports/mc263/gradle.properties b/ports/mc263/gradle.properties index 254d275..7f57fb8 100644 --- a/ports/mc263/gradle.properties +++ b/ports/mc263/gradle.properties @@ -7,7 +7,7 @@ neo_version=26.3.0.99 mod_id=rivencraft mod_name=Rivencraft mod_license=LGPL-3.0-or-later -mod_version=26.3.0.10 +mod_version=26.3.0.15 jei_version=31.17.0.109 diff --git a/ports/mc263/port_en_us.json b/ports/mc263/port_en_us.json index 2b0bbf5..7d57543 100644 --- a/ports/mc263/port_en_us.json +++ b/ports/mc263/port_en_us.json @@ -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.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.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.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.", diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/PortConfig.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/PortConfig.java index 85846a1..8499f50 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/PortConfig.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/PortConfig.java @@ -20,6 +20,8 @@ public final class PortConfig { public static final ModConfigSpec.EnumValue RETURN_LINK_MODE; public static final ModConfigSpec.IntValue ACCELERATED_MAX_CHUNKS; 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 { var builder = new ModConfigSpec.Builder(); @@ -74,8 +76,12 @@ public final class PortConfig { builder.push("accelerated_age"); 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); - 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); + 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(); net.dnorberg.rivencraft.age.PortInstabilityConfig.define(builder); SPEC = builder.build(); diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortAcceleratedTicks.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortAcceleratedTicks.java index fb67191..9cae34b 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortAcceleratedTicks.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortAcceleratedTicks.java @@ -16,7 +16,7 @@ import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunkSection; 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 static final Identifier PAGE = Identifier.fromNamespaceAndPath("rivencraft", "environment/accelerated"); @@ -42,9 +42,10 @@ public final class PortAcceleratedTicks { static void tick(ServerLevel level) { int maximumAttempts = PortConfig.ACCELERATED_MAX_ATTEMPTS.get(); - if (maximumAttempts == 0) return; 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 chunks = loadedPlayerChunks(level); if (chunks.isEmpty()) return; diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortBlockInstability.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortBlockInstability.java index a16f7e0..6ea4ad8 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortBlockInstability.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortBlockInstability.java @@ -54,6 +54,32 @@ public final class 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 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. */ static boolean tracked(Identifier id) { if (VANILLA_WEIGHTS.containsKey(id)) return true; @@ -164,7 +190,7 @@ public final class PortBlockInstability { 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) { if (GENERATION_IN_FLIGHT.containsKey(server)) return; List targets = new ArrayList<>(); @@ -178,8 +204,8 @@ public final class PortBlockInstability { PortBlockProfileSavedData.MIN_AGE_SAMPLES)); } if (targets.isEmpty()) return; - ServerLevel overworld = server.overworld(); - targets.add(0, new SampleTarget(overworld, overworld.getRespawnData().pos(), + ServerLevel baseline = server.overworld(); + targets.add(0, new SampleTarget(baseline, baseline.getRespawnData().pos(), PortBlockProfileSavedData.MIN_BASELINE_SAMPLES)); int first = Math.floorMod(NEXT_TARGET.getOrDefault(server, 0), targets.size()); for (int offset = 0; offset < targets.size(); offset++) { @@ -261,7 +287,7 @@ public final class PortBlockInstability { double weight = weight(id); if (weight <= 0) continue; 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; } return (int) Math.min(100_000, Math.round(result)); diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortInstabilityCommands.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortInstabilityCommands.java index d710e1f..8a4cf50 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortInstabilityCommands.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortInstabilityCommands.java @@ -32,7 +32,8 @@ public final class PortInstabilityCommands { + "; effective score=" + PortInstabilityRuntime.effectiveScore(level) + "; difficulty=" + PortInstabilityConfig.instabilityDifficulty() + "; 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); for (var cost : age.contributions()) source.sendSuccess(() -> Component.literal( " " + cost.reason() + " page=" + cost.page() + " +" + cost.points()), false); diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortMachineTicks.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortMachineTicks.java new file mode 100644 index 0000000..c6b5df8 --- /dev/null +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/age/PortMachineTicks.java @@ -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 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); + } +} diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/AgeCatalogClient.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/AgeCatalogClient.java index ca372cd..02f60aa 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/AgeCatalogClient.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/AgeCatalogClient.java @@ -28,6 +28,7 @@ public final class AgeCatalogClient { @SubscribeEvent 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.WritingDeskCatalogPayload.TYPE, ClientWritingDeskCatalog::handle); event.register(net.dnorberg.rivencraft.network.SereneAgeWhitelistPayload.TYPE, (payload, context) -> diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/ClientDroppedBooks.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/ClientDroppedBooks.java new file mode 100644 index 0000000..81d23e2 --- /dev/null +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/ClientDroppedBooks.java @@ -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)); + }); + } +} diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortBookPreview.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortBookPreview.java index 96d3ed4..bf739ac 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortBookPreview.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortBookPreview.java @@ -30,10 +30,15 @@ public final class PortBookPreview { private net.minecraft.resources.Identifier destination; 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(); request = minecraft.level == null ? null : new RequestBookPreviewPayload(session, 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(); live = enabled ? new ImmersiveLiveBookPanel() : null; if (active != null) active.close(); diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortDescriptiveBookScreen.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortDescriptiveBookScreen.java index 9889b7e..28a92fd 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortDescriptiveBookScreen.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortDescriptiveBookScreen.java @@ -31,6 +31,7 @@ public final class PortDescriptiveBookScreen extends Screen { private final net.dnorberg.rivencraft.writing.DescriptiveBookPages pages; private int pageIndex; private net.dnorberg.rivencraft.network.UseBookStandPayload standSource; + private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource; private EditBox titleInput; public PortDescriptiveBookScreen(InteractionHand hand, ItemStack book) { @@ -47,11 +48,16 @@ public final class PortDescriptiveBookScreen extends Screen { standSource = source; } + public PortDescriptiveBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source) { + this(InteractionHand.MAIN_HAND, source.book()); + droppedSource = source; + } + @Override protected void init() { if (bound) { - linkPanel.open(hand, book, standSource); - exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null); + linkPanel.open(hand, book, standSource, droppedSource); + exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null || droppedSource != 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()); if (direction != 0) { turnPage(direction); return true; } 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)); onClose(); return true; @@ -187,6 +195,9 @@ public final class PortDescriptiveBookScreen extends Screen { } @Override public void tick() { + if (droppedSource != null && !ClientDroppedBooks.present(droppedSource)) { + onClose(); return; + } if (bound) linkPanel.tick(); exploration.tick(pageIndex == 0); } @@ -202,7 +213,9 @@ public final class PortDescriptiveBookScreen extends Screen { if (titleInput == null) return; String name = titleInput.getValue().strip(); 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(); } diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLegacyLinkPanel.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLegacyLinkPanel.java index 6b7780e..4ae7785 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLegacyLinkPanel.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLegacyLinkPanel.java @@ -17,7 +17,12 @@ final class PortLegacyLinkPanel { private PortBookPreview preview; void open(net.minecraft.world.InteractionHand hand, net.minecraft.world.item.ItemStack book, 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; } } boolean canExplore() { return preview != null && preview.canExplore(); } diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLinkingBookScreen.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLinkingBookScreen.java index 40b943b..1a28bb7 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLinkingBookScreen.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/PortLinkingBookScreen.java @@ -32,6 +32,7 @@ public final class PortLinkingBookScreen extends Screen { private final PortLegacyLinkPanel linkPanel = new PortLegacyLinkPanel(); private final PortBookExploration exploration = new PortBookExploration(linkPanel); private net.dnorberg.rivencraft.network.UseBookStandPayload standSource; + private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource; private EditBox titleInput; public PortLinkingBookScreen(InteractionHand hand, ItemStack book) { @@ -52,11 +53,16 @@ public final class PortLinkingBookScreen extends Screen { standSource = source; } + public PortLinkingBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source) { + this(InteractionHand.MAIN_HAND, source.book()); + droppedSource = source; + } + @Override protected void init() { if (bound) { - linkPanel.open(hand, book, standSource); - exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null); + linkPanel.open(hand, book, standSource, droppedSource); + exploration.attach(this, this::addRenderableWidget, (width - WIDTH) / 2, (height - HEIGHT) / 2, standSource != null || droppedSource != 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); if (direction != 0) { turnPage(direction); return true; } 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)); onClose(); return true; @@ -152,6 +160,9 @@ public final class PortLinkingBookScreen extends Screen { } @Override public void tick() { + if (droppedSource != null && !ClientDroppedBooks.present(droppedSource)) { + onClose(); return; + } if (bound) linkPanel.tick(); exploration.tick(pageIndex == 0); } @@ -167,7 +178,9 @@ public final class PortLinkingBookScreen extends Screen { if (titleInput == null) return; String name = titleInput.getValue().strip(); 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(); } diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java index d9ab4ee..94ca55b 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java @@ -14,18 +14,20 @@ import net.minecraft.client.renderer.item.ItemStackRenderState; import net.minecraft.client.renderer.state.level.CameraRenderState; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; +import net.dnorberg.rivencraft.shared.WritingDeskDisplayModel; +import net.minecraft.resources.Identifier; +import net.minecraft.client.renderer.rendertype.RenderTypes; import net.minecraft.world.phys.Vec3; /** The existing selected-page and white-paper display, extracted for 26.3. */ public final class WritingDeskRenderer implements BlockEntityRenderer { + private static final Identifier TEXTURE = Identifier.fromNamespaceAndPath( + "rivencraft", "textures/block/writing_desk.png"); private final ItemModelResolver resolver; public WritingDeskRenderer(BlockEntityRendererProvider.Context context) { resolver = context.itemModelResolver(); } public static final class State extends BlockEntityRenderState { - final ItemStackRenderState paper = new ItemStackRenderState(); final ItemStackRenderState page = new ItemStackRenderState(); - int layers; + int paperCount; float rotation; } @Override public State createRenderState() { return new State(); } @@ -33,18 +35,31 @@ public final class WritingDeskRenderer implements BlockEntityRenderer { + 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(); } private static void draw(ItemStackRenderState item, PoseStack pose, SubmitNodeCollector collector, diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/compat/ImmersivePreviewChunks.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/compat/ImmersivePreviewChunks.java index 5fb76ac..eb29b4b 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/compat/ImmersivePreviewChunks.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/compat/ImmersivePreviewChunks.java @@ -40,6 +40,7 @@ final class ImmersivePreviewChunks { if (previous != null && previous.session().equals(request.session()) && previous.source().offhand() == request.offhand() && previous.source().fromStand() == request.fromStand() + && java.util.Objects.equals(previous.source().droppedBook(), request.droppedBook()) && previous.source().sourceDimension().equals(request.sourceDimension()) && previous.source().standPos().equals(request.standPos()) && ItemStack.matches(previous.source().book(), request.book())) { @@ -80,6 +81,13 @@ final class ImmersivePreviewChunks { private static ItemStack validated(ServerPlayer player, RequestBookPreviewPayload request) { 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, new net.dnorberg.rivencraft.network.UseBookStandPayload(request.sourceDimension(), request.standPos(), request.book())); ItemStack held = player.getItemInHand(request.offhand() ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND); diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java index f7a4b8c..1a15957 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java @@ -37,6 +37,37 @@ public final class DroppedBookEntity extends ItemEntity { 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 public void tick() { super.tick(); diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/mixin/LevelBlockEntityTickersAccessor.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/mixin/LevelBlockEntityTickersAccessor.java new file mode 100644 index 0000000..cc49e02 --- /dev/null +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/mixin/LevelBlockEntityTickersAccessor.java @@ -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 rivencraft$blockEntityTickers(); +} diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/DroppedBookActionPayload.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/DroppedBookActionPayload.java new file mode 100644 index 0000000..9c98f2a --- /dev/null +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/DroppedBookActionPayload.java @@ -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 TYPE = new Type<>( + Identifier.fromNamespaceAndPath(Rivencraft.MOD_ID, "dropped_book_action")); + public static final StreamCodec 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 type() { return TYPE; } +} diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/OpenDroppedBookScreenPayload.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/OpenDroppedBookScreenPayload.java new file mode 100644 index 0000000..db34e3b --- /dev/null +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/OpenDroppedBookScreenPayload.java @@ -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 TYPE = new Type<>( + Identifier.fromNamespaceAndPath(Rivencraft.MOD_ID,"open_dropped_book")); + public static final StreamCodec STREAM_CODEC = + StreamCodec.of((buf,value)->{ DroppedBookActionPayload.STREAM_CODEC.encode(buf,value.source()); }, + buf->new OpenDroppedBookScreenPayload(DroppedBookActionPayload.STREAM_CODEC.decode(buf))); + @Override public Type type() { return TYPE; } +} diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/PortBookNetworking.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/PortBookNetworking.java index f1adbde..0618386 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/PortBookNetworking.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/PortBookNetworking.java @@ -32,7 +32,12 @@ public final class PortBookNetworking { } 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.playToServer(RequestBookPreviewPayload.TYPE, RequestBookPreviewPayload.STREAM_CODEC, (payload, context) -> { @@ -96,9 +101,12 @@ public final class PortBookNetworking { } 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; - String title = payload.title().strip(); + String title = requestedTitle.strip(); if (title.isEmpty() || title.length() > MAX_BOOK_TITLE_LENGTH) return; stack.set(Rivencraft.LINK_BOOK_TARGET.get(), LinkBookTarget.at(player)); 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) { - 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; - String title = payload.title().strip(); + String title = requestedTitle.strip(); if (title.isEmpty() || title.length() > MAX_BOOK_TITLE_LENGTH) return; Identifier id = createAge(player, title); 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) { return offhand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND; } diff --git a/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/RequestBookPreviewPayload.java b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/RequestBookPreviewPayload.java index 0b100ac..7866cb0 100644 --- a/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/RequestBookPreviewPayload.java +++ b/ports/mc263/src/main/java/net/dnorberg/rivencraft/network/RequestBookPreviewPayload.java @@ -9,16 +9,23 @@ import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.Identifier; 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, - 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 TYPE = new Type<>(Identifier.fromNamespaceAndPath(Rivencraft.MOD_ID, "request_book_preview")); public static final StreamCodec STREAM_CODEC = StreamCodec.of( (buf, value) -> { buf.writeUUID(value.session()); buf.writeBoolean(value.offhand()); buf.writeBoolean(value.fromStand()); Identifier.STREAM_CODEC.encode(buf, value.sourceDimension()); 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(), - 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 type() { return TYPE; } } diff --git a/ports/mc263/src/main/resources/assets/rivencraft/instability/default_block_baseline.json b/ports/mc263/src/main/resources/assets/rivencraft/instability/default_block_baseline.json new file mode 100644 index 0000000..299469f --- /dev/null +++ b/ports/mc263/src/main/resources/assets/rivencraft/instability/default_block_baseline.json @@ -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 + } +} diff --git a/ports/mc263/src/main/resources/rivencraft.mixins.json b/ports/mc263/src/main/resources/rivencraft.mixins.json index acb8219..08cc685 100644 --- a/ports/mc263/src/main/resources/rivencraft.mixins.json +++ b/ports/mc263/src/main/resources/rivencraft.mixins.json @@ -12,7 +12,8 @@ "AgeDayTimelineMixin", "RuinsDimensionMixin", "RuinsTemplateDimensionMixin", - "RuinsAttemptMixin" + "RuinsAttemptMixin", + "LevelBlockEntityTickersAccessor" ], "client": [ "StaticSkyStateMixin", diff --git a/scripts/fixtures/drop114/mc1211/net/dnorberg/rivencraft/regression/BookDropProbe.java b/scripts/fixtures/drop114/mc1211/net/dnorberg/rivencraft/regression/BookDropProbe.java new file mode 100644 index 0000000..6eb8910 --- /dev/null +++ b/scripts/fixtures/drop114/mc1211/net/dnorberg/rivencraft/regression/BookDropProbe.java @@ -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); + } +} diff --git a/scripts/fixtures/drop_interactions/mc1211/net/dnorberg/rivencraft/regression/DroppedInteractionProbe.java b/scripts/fixtures/drop_interactions/mc1211/net/dnorberg/rivencraft/regression/DroppedInteractionProbe.java new file mode 100644 index 0000000..bdc42c4 --- /dev/null +++ b/scripts/fixtures/drop_interactions/mc1211/net/dnorberg/rivencraft/regression/DroppedInteractionProbe.java @@ -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(); } + } +} diff --git a/scripts/fixtures/drop_interactions/mc263/net/dnorberg/rivencraft/regression/DroppedInteractionProbe.java b/scripts/fixtures/drop_interactions/mc263/net/dnorberg/rivencraft/regression/DroppedInteractionProbe.java new file mode 100644 index 0000000..d2d96f6 --- /dev/null +++ b/scripts/fixtures/drop_interactions/mc263/net/dnorberg/rivencraft/regression/DroppedInteractionProbe.java @@ -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 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(); } + } +} diff --git a/scripts/fixtures/machine112/mc1211/net/dnorberg/rivencraft/book/MachineProbe.java b/scripts/fixtures/machine112/mc1211/net/dnorberg/rivencraft/book/MachineProbe.java new file mode 100644 index 0000000..c3f387d --- /dev/null +++ b/scripts/fixtures/machine112/mc1211/net/dnorberg/rivencraft/book/MachineProbe.java @@ -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(); + 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(); + 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();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"); + } +} diff --git a/scripts/fixtures/machine112/mc263/net/dnorberg/rivencraft/age/MachineProbe.java b/scripts/fixtures/machine112/mc263/net/dnorberg/rivencraft/age/MachineProbe.java new file mode 100644 index 0000000..4b81d0e --- /dev/null +++ b/scripts/fixtures/machine112/mc263/net/dnorberg/rivencraft/age/MachineProbe.java @@ -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)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(); + 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();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"); + } +} diff --git a/scripts/generate_block_baseline.py b/scripts/generate_block_baseline.py new file mode 100644 index 0000000..4694f27 --- /dev/null +++ b/scripts/generate_block_baseline.py @@ -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") diff --git a/scripts/regression_baseline_defaults.py b/scripts/regression_baseline_defaults.py new file mode 100644 index 0000000..c56cd9b --- /dev/null +++ b/scripts/regression_baseline_defaults.py @@ -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) diff --git a/scripts/regression_drop114.py b/scripts/regression_drop114.py new file mode 100644 index 0000000..d8df448 --- /dev/null +++ b/scripts/regression_drop114.py @@ -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)) diff --git a/scripts/regression_dropped_interactions.py b/scripts/regression_dropped_interactions.py new file mode 100644 index 0000000..5d637f4 --- /dev/null +++ b/scripts/regression_dropped_interactions.py @@ -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)) diff --git a/scripts/regression_machine112.py b/scripts/regression_machine112.py new file mode 100644 index 0000000..9df410d --- /dev/null +++ b/scripts/regression_machine112.py @@ -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)) diff --git a/shared/src/main/java/net/dnorberg/rivencraft/shared/AcceleratedMachineWork.java b/shared/src/main/java/net/dnorberg/rivencraft/shared/AcceleratedMachineWork.java new file mode 100644 index 0000000..fd751de --- /dev/null +++ b/shared/src/main/java/net/dnorberg/rivencraft/shared/AcceleratedMachineWork.java @@ -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 int run(List registered, int pages, int maximumCandidates, int maximumTicks, + Predicate eligible, Consumer 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 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; + } +} diff --git a/shared/src/main/java/net/dnorberg/rivencraft/shared/MaterialBaselinePolicy.java b/shared/src/main/java/net/dnorberg/rivencraft/shared/MaterialBaselinePolicy.java new file mode 100644 index 0000000..dcc1891 --- /dev/null +++ b/shared/src/main/java/net/dnorberg/rivencraft/shared/MaterialBaselinePolicy.java @@ -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 defaults; + + public MaterialBaselinePolicy(Map 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 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); + } +} diff --git a/shared/src/main/java/net/dnorberg/rivencraft/shared/WritingDeskDisplayModel.java b/shared/src/main/java/net/dnorberg/rivencraft/shared/WritingDeskDisplayModel.java new file mode 100644 index 0000000..7b1c324 --- /dev/null +++ b/shared/src/main/java/net/dnorberg/rivencraft/shared/WritingDeskDisplayModel.java @@ -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> 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 paper(int count) { return STACKS.get(layers(count)); } + + private static List stack(int layers) { + List 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 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 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 vertices, float nx, float ny, float nz, int color) {} +} diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeAcceleratedTicks.java b/src/main/java/net/dnorberg/rivencraft/book/AgeAcceleratedTicks.java index 2470111..d7193cf 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeAcceleratedTicks.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeAcceleratedTicks.java @@ -15,17 +15,18 @@ import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunkSection; 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 { private AgeAcceleratedTicks() {} static void tick(ServerLevel level) { int maximumAttempts = RivencraftConfig.acceleratedMaxAttempts(); - if (maximumAttempts == 0) return; AgeDefinition age = AgeRegistrySavedData.get(level) .findByDimension(level.dimension().location()).orElse(null); 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 chunks = loadedPlayerChunks(level); if (chunks.isEmpty()) return; diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeBlockInstability.java b/src/main/java/net/dnorberg/rivencraft/book/AgeBlockInstability.java index ba91b63..f6c1bdf 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeBlockInstability.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeBlockInstability.java @@ -53,6 +53,32 @@ public final class 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 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. */ static boolean tracked(ResourceLocation id) { if (VANILLA_WEIGHTS.containsKey(id)) return true; @@ -144,7 +170,8 @@ public final class AgeBlockInstability { } if (pending == null) break; 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()); } if (event.getServer().getTickCount() % GENERATION_INTERVAL_TICKS == 0) { @@ -159,7 +186,7 @@ public final class AgeBlockInstability { 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) { if (GENERATION_IN_FLIGHT.containsKey(server)) return; List targets = new ArrayList<>(); @@ -174,8 +201,8 @@ public final class AgeBlockInstability { AgeBlockProfileSavedData.MIN_AGE_SAMPLES)); } if (targets.isEmpty()) return; - ServerLevel overworld = server.overworld(); - targets.add(0, new SampleTarget(overworld, overworld.getSharedSpawnPos(), + ServerLevel baseline = server.overworld(); + targets.add(0, new SampleTarget(baseline, baseline.getSharedSpawnPos(), AgeBlockProfileSavedData.MIN_BASELINE_SAMPLES)); int first = Math.floorMod(NEXT_TARGET.getOrDefault(server, 0), targets.size()); for (int offset = 0; offset < targets.size(); offset++) { @@ -208,14 +235,18 @@ public final class AgeBlockInstability { CompletableFuture.supplyAsync(() -> level.getChunkSource() .getChunkFuture(target.x, target.z, ChunkStatus.FULL, true)) .thenCompose(future -> future) - .whenComplete((result, error) -> server.execute(() -> { - GENERATION_IN_FLIGHT.remove(server); - if (error != null) { - Rivencraft.LOGGER.warn("Could not profile chunk {} in {}", target, dimension, error); - } else if (result.orElse(null) instanceof LevelChunk chunk) { - profile.sample(chunk); - } - })); + .whenComplete((result, error) -> { + if (server.isStopped()) return; + server.execute(() -> { + if (GENERATION_IN_FLIGHT.remove(server) == null) return; + if (error != null) { + 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 false; @@ -253,7 +284,7 @@ public final class AgeBlockInstability { double weight = weight(id); if (weight <= 0) continue; 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; } return (int) Math.min(100_000, Math.round(result)); @@ -263,8 +294,7 @@ public final class AgeBlockInstability { if (age.instability().version() < 2 || !AgeInstabilityRuntime.isAgeDimension(level.dimension().location()) || !age.dimensionId().equals(level.dimension().location())) return 0; - return score(AgeBlockProfileSavedData.get(level), - AgeBlockProfileSavedData.get(level.getServer().overworld())); + return score(AgeBlockProfileSavedData.get(level), AgeBlockProfileSavedData.get(level.getServer().overworld())); } public static int sampledChunks(ServerLevel level) { diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeInstabilityRuntime.java b/src/main/java/net/dnorberg/rivencraft/book/AgeInstabilityRuntime.java index 31fb42b..8465dad 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeInstabilityRuntime.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeInstabilityRuntime.java @@ -39,9 +39,10 @@ public final class AgeInstabilityRuntime { public static void onLevelTickPost(LevelTickEvent.Post event) { 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. AgeAcceleratedTicks.tick(level); + if (level.players().isEmpty()) return; if (!RivencraftConfig.instabilityEnabled()) return; MinecraftServer server = level.getServer(); long tick = server.getTickCount(); diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeMachineTicks.java b/src/main/java/net/dnorberg/rivencraft/book/AgeMachineTicks.java new file mode 100644 index 0000000..6b5c744 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeMachineTicks.java @@ -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 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); + } +} diff --git a/src/main/java/net/dnorberg/rivencraft/client/ClientDroppedBooks.java b/src/main/java/net/dnorberg/rivencraft/client/ClientDroppedBooks.java new file mode 100644 index 0000000..1b988f3 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/client/ClientDroppedBooks.java @@ -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())); + }); + } +} diff --git a/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java b/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java index 0eb0761..c4d3555 100644 --- a/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java +++ b/src/main/java/net/dnorberg/rivencraft/client/WritingDeskRenderer.java @@ -10,10 +10,15 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.world.item.ItemDisplayContext; 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. */ public final class WritingDeskRenderer implements BlockEntityRenderer { + private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath( + "rivencraft", "textures/block/writing_desk.png"); + public WritingDeskRenderer(BlockEntityRendererProvider.Context context) {} @Override public void render(WritingDeskBlockEntity desk, float partialTick, PoseStack pose, @@ -25,22 +30,26 @@ public final class WritingDeskRenderer implements BlockEntityRenderer 0) { - ItemStack sheet = new ItemStack(Items.PAPER); - int layers = Math.min(4, 1 + paper / 16); - for (int i = 0; i < layers; i++) { - drawFlat(desk, sheet, pose, buffers, light, overlay, 1.22, 0.27 + i * 0.008, -0.14, 0.55F); + var vertices = buffers.getBuffer(RenderType.entitySolid(TEXTURE)); + for (var face : WritingDeskDisplayModel.paper(paper)) { + for (var vertex : face.vertices()) { + vertices.addVertex(pose.last(), vertex.x(), vertex.y(), vertex.z()) + .setColor(face.color()).setUv(vertex.u(), vertex.v()) + .setOverlay(overlay).setLight(light) + .setNormal(pose.last(), face.nx(), face.ny(), face.nz()); } } 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(); } - private static void drawFlat(WritingDeskBlockEntity desk, ItemStack stack, PoseStack pose, + private static void drawFlat(ItemStack stack, PoseStack pose, 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.translate(x, y, z); pose.mulPose(Axis.XP.rotationDegrees(90)); diff --git a/src/main/java/net/dnorberg/rivencraft/client/screen/DescriptiveBookScreen.java b/src/main/java/net/dnorberg/rivencraft/client/screen/DescriptiveBookScreen.java index 3c8836a..738dd9a 100644 --- a/src/main/java/net/dnorberg/rivencraft/client/screen/DescriptiveBookScreen.java +++ b/src/main/java/net/dnorberg/rivencraft/client/screen/DescriptiveBookScreen.java @@ -58,6 +58,7 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo private final String author; private final InteractionHand hand; private final BlockPos bookStandPos; + private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource; private DestinationPreviewRenderer preview; private EditBox titleInput; private Button exploreButton; @@ -96,6 +97,12 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo this.bookStandPos = bookStandPos.immutable(); } + public DescriptiveBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source, + @Nullable AgeTraits traits, List symbols) { + this(InteractionHand.MAIN_HAND, source.book(), traits, symbols); + droppedSource = source; + } + @Override protected void init() { int left = (width - BOOK_WIDTH) / 2; @@ -127,23 +134,33 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo EXPLORE_ICON, button -> enterExploreOverlay()) .bounds(left + 229, top + 145, 20, 20) .tooltip(Tooltip.create(Component.translatable("screen.rivencraft.book.explore"))).build()); - exploreButton.active = bookStandPos == null; + exploreButton.active = bookStandPos == null && droppedSource == null; exploreButton.visible = pageIndex == 0; } 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, bookStandPos != null, bookStandPos == null && hand == InteractionHand.OFF_HAND, bookStandPos == null ? BlockPos.ZERO : bookStandPos, preview.supportsExploration() )); + } } } } @Override public void tick() { + if (droppedSource != null && !net.dnorberg.rivencraft.client.ClientDroppedBooks.present(droppedSource)) { + onClose(); + return; + } if (preview != null) { preview.tick(); } @@ -386,7 +403,7 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo } private void enterExploreOverlay() { - if (bookStandPos != null) { + if (bookStandPos != null || droppedSource != null) { return; } preview.setExploring(true); @@ -444,6 +461,12 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo } 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( bookStandPos != null, bookStandPos == null && hand == InteractionHand.OFF_HAND, @@ -457,12 +480,17 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo if (name.isEmpty()) { 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 && hand == InteractionHand.OFF_HAND, bookStandPos == null ? BlockPos.ZERO : bookStandPos, name )); + } onClose(); } diff --git a/src/main/java/net/dnorberg/rivencraft/client/screen/LinkingBookScreen.java b/src/main/java/net/dnorberg/rivencraft/client/screen/LinkingBookScreen.java index 6c49f76..5568b66 100644 --- a/src/main/java/net/dnorberg/rivencraft/client/screen/LinkingBookScreen.java +++ b/src/main/java/net/dnorberg/rivencraft/client/screen/LinkingBookScreen.java @@ -44,6 +44,7 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr private final ItemStack book; private final LinkTarget target; private final BlockPos bookStandPos; + private net.dnorberg.rivencraft.network.DroppedBookActionPayload droppedSource; private DestinationPreviewRenderer preview; private EditBox titleInput; private Button exploreButton; @@ -68,6 +69,11 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr this.bookStandPos = bookStandPos.immutable(); } + public LinkingBookScreen(net.dnorberg.rivencraft.network.DroppedBookActionPayload source) { + this(InteractionHand.MAIN_HAND, source.book()); + droppedSource = source; + } + @Override protected void init() { int left = (width - BOOK_WIDTH) / 2; @@ -99,23 +105,33 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr EXPLORE_ICON, button -> enterExploreOverlay()) .bounds(left + 229, top + 145, 20, 20) .tooltip(Tooltip.create(Component.translatable("screen.rivencraft.book.explore"))).build()); - exploreButton.active = bookStandPos == null; + exploreButton.active = bookStandPos == null && droppedSource == null; exploreButton.visible = pageIndex == 0; } 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, bookStandPos != null, bookStandPos == null && hand == InteractionHand.OFF_HAND, bookStandPos == null ? BlockPos.ZERO : bookStandPos, preview.supportsExploration() )); + } } } } @Override public void tick() { + if (droppedSource != null && !net.dnorberg.rivencraft.client.ClientDroppedBooks.present(droppedSource)) { + onClose(); + return; + } if (preview != null) { preview.tick(); } @@ -263,7 +279,7 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr } private void enterExploreOverlay() { - if (bookStandPos != null) { + if (bookStandPos != null || droppedSource != null) { return; } preview.setExploring(true); @@ -329,12 +345,23 @@ public final class LinkingBookScreen extends Screen implements ExplorableBookScr private void bind() { String name = titleInput.getValue().strip(); 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(); } } 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) { PacketDistributor.sendToServer(new UseLinkingBookPayload(hand == InteractionHand.OFF_HAND)); } else { diff --git a/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java b/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java index 0fe2cf8..0a924a1 100644 --- a/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java +++ b/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java @@ -183,10 +183,10 @@ public final class RivencraftCommands { if (age.instability().version() >= 2) { int ageSamples = ageLevel == null ? 0 : net.dnorberg.rivencraft.book.AgeBlockInstability.sampledChunks(ageLevel); - int baselineSamples = net.dnorberg.rivencraft.book.AgeBlockInstability.sampledChunks( - source.getServer().overworld()); + int baselineSamples = net.dnorberg.rivencraft.book.AgeBlockInstability.baselineSamples(source.getServer()); 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); source.sendSuccess(() -> Component.literal("Modded materials: automatic when installed, " + RivencraftConfig.moddedMaterialOverrides().size() + " exact block override(s)"), false); diff --git a/src/main/java/net/dnorberg/rivencraft/config/RivencraftConfig.java b/src/main/java/net/dnorberg/rivencraft/config/RivencraftConfig.java index 6268d81..eaa4a15 100644 --- a/src/main/java/net/dnorberg/rivencraft/config/RivencraftConfig.java +++ b/src/main/java/net/dnorberg/rivencraft/config/RivencraftConfig.java @@ -37,6 +37,8 @@ public final class RivencraftConfig { private static final ModConfigSpec.IntValue INSTABILITY_MAX_CHUNKS; private static final ModConfigSpec.IntValue ACCELERATED_MAX_CHUNKS; 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> MODDED_MATERIAL_OVERRIDES; private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_ENABLED; private static final ModConfigSpec.BooleanValue STATUS_EFFECTS_PLAYERS; @@ -135,8 +137,12 @@ public final class RivencraftConfig { builder.push("accelerated_age"); ACCELERATED_MAX_CHUNKS = builder.comment("Maximum already-loaded chunks given extra random ticks per Age tick.") .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); + 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.push("instability_modded_materials"); 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 instabilityMaxChunks() { return INSTABILITY_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 List moddedMaterialOverrides() { return MODDED_MATERIAL_OVERRIDES.get(); } diff --git a/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java b/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java index fc987a0..b9c964a 100644 --- a/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java +++ b/src/main/java/net/dnorberg/rivencraft/entity/DroppedBookEntity.java @@ -8,7 +8,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; 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 { private static final String DECAY_TICKS_TAG = "BookDecayTicks"; private static final int SLOW_DECAY_INTERVAL = 10_000; @@ -27,6 +27,20 @@ public final class DroppedBookEntity extends ItemEntity { 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. */ @Override public DroppedBookEntity copy() { @@ -37,6 +51,37 @@ public final class DroppedBookEntity extends ItemEntity { 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 public void tick() { super.tick(); diff --git a/src/main/java/net/dnorberg/rivencraft/event/DroppedBookConversionHandler.java b/src/main/java/net/dnorberg/rivencraft/event/DroppedBookConversionHandler.java new file mode 100644 index 0000000..28e9ffb --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/event/DroppedBookConversionHandler.java @@ -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()); + } +} diff --git a/src/main/java/net/dnorberg/rivencraft/mixin/LevelBlockEntityTickersAccessor.java b/src/main/java/net/dnorberg/rivencraft/mixin/LevelBlockEntityTickersAccessor.java new file mode 100644 index 0000000..cc49e02 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/mixin/LevelBlockEntityTickersAccessor.java @@ -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 rivencraft$blockEntityTickers(); +} diff --git a/src/main/java/net/dnorberg/rivencraft/network/DroppedBookActionPayload.java b/src/main/java/net/dnorberg/rivencraft/network/DroppedBookActionPayload.java new file mode 100644 index 0000000..bae4ef6 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/network/DroppedBookActionPayload.java @@ -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 TYPE = new Type<>( + ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, "dropped_book_action")); + public static final StreamCodec 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 type() { return TYPE; } +} diff --git a/src/main/java/net/dnorberg/rivencraft/network/ModNetworking.java b/src/main/java/net/dnorberg/rivencraft/network/ModNetworking.java index d5fc3d7..e9349ab 100644 --- a/src/main/java/net/dnorberg/rivencraft/network/ModNetworking.java +++ b/src/main/java/net/dnorberg/rivencraft/network/ModNetworking.java @@ -61,7 +61,7 @@ public final class ModNetworking { } public static void register(RegisterPayloadHandlersEvent event) { - PayloadRegistrar registrar = event.registrar("19"); + PayloadRegistrar registrar = event.registrar("20"); registrar.playToServer(RequestDescriptiveBookScreenPayload.TYPE, RequestDescriptiveBookScreenPayload.STREAM_CODEC, ModNetworking::requestDescriptiveBookScreen); registrar.playToClient(OpenDescriptiveBookScreenPayload.TYPE, OpenDescriptiveBookScreenPayload.STREAM_CODEC, @@ -77,6 +77,12 @@ public final class ModNetworking { ModNetworking::requestLinkPreview); registrar.playToServer(ReleaseLinkPreviewPayload.TYPE, ReleaseLinkPreviewPayload.STREAM_CODEC, (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, ClientLinkPreviewHandler::handle); registrar.playToClient(AgeCelestialAnglePayload.TYPE, AgeCelestialAnglePayload.STREAM_CODEC, @@ -136,29 +142,36 @@ public final class ModNetworking { if (access == null || WRITING_BOOKS.contains(access.stack())) { 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 ? null : AgeRegistrySavedData.get(player.serverLevel()).find(reference.id()).orElse(null); - if (definition != null && !access.stack().has(ModDataComponents.AGE_GENERATION_PROFILE.get())) { - access.stack().set(ModDataComponents.AGE_GENERATION_PROFILE.get(), definition.generationProfile()); - access.sync().run(); + if (definition != null && !stack.has(ModDataComponents.AGE_GENERATION_PROFILE.get())) { + stack.set(ModDataComponents.AGE_GENERATION_PROFILE.get(), definition.generationProfile()); + } // 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. player.inventoryMenu.broadcastChanges(); - OrderedWriting writing = access.stack() + OrderedWriting writing = stack .getOrDefault(ModDataComponents.BOOK_WRITING.get(), OrderedWriting.EMPTY); List writingSymbols = writing.entries().stream() .filter(entry -> entry.kind() == WritingEntry.Kind.SYMBOL) .map(entry -> SymbolCatalog.display(entry.symbol().orElseThrow())) .toList(); - PacketDistributor.sendToPlayer(player, new OpenDescriptiveBookScreenPayload( - payload.fromStand(), payload.offhand(), - GlobalPos.of(player.level().dimension(), payload.standPos()), access.stack().copy(), + return new OpenDescriptiveBookScreenPayload( + fromStand, offhand, + GlobalPos.of(player.level().dimension(), standPos), stack.copy(), definition == null ? null : definition.plan() != null && definition.plan().biomeSelection() != null ? definition.traits().withBiomeDistribution(definition.plan().biomeSelection().distribution()) - : definition.traits(), writingSymbols)); + : definition.traits(), writingSymbols); } 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()); + bindDescriptive(player, access, payload.title()); + } + + private static void bindDescriptive(ServerPlayer player, BookAccess access, String requestedTitle) { if (access == null || WRITING_BOOKS.contains(access.stack()) || access.stack().has(ModDataComponents.AGE_REFERENCE.get())) { return; } - String title = normalizeTitle(payload.title()); + String title = normalizeTitle(requestedTitle); if (title.isEmpty()) { return; } @@ -223,11 +240,15 @@ public final class ModNetworking { } 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())) { return; } - String title = normalizeTitle(payload.title()); + String title = normalizeTitle(requestedTitle); if (title.isEmpty()) { return; } @@ -301,13 +322,18 @@ public final class ModNetworking { 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; - 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()); target = age == null ? null : AgeDimensionService.resolve(player, age, OrderedWriting.EMPTY, !stack.getOrDefault(ModDataComponents.LINK_PROPERTIES.get(), LinkProperties.NONE) .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()); } else { target = null; @@ -327,7 +353,7 @@ public final class ModNetworking { } BlockPos origin = LinkingService.resolveDestination( - level, target.location().pos(), payload.descriptiveBook()) + level, target.location().pos(), descriptiveBook) .map(BlockPos::containing) .orElse(target.location().pos()); List blocks = new ArrayList<>(); @@ -345,13 +371,41 @@ public final class ModNetworking { } } 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); } PacketDistributor.sendToPlayer(player, new LinkPreviewPayload( 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) { if (context.player() instanceof ServerPlayer player && ModList.get().isLoaded("immersive_portals_core")) { ImmersivePortalsChunkLoaders.close(player); diff --git a/src/main/java/net/dnorberg/rivencraft/network/OpenDroppedBookScreenPayload.java b/src/main/java/net/dnorberg/rivencraft/network/OpenDroppedBookScreenPayload.java new file mode 100644 index 0000000..16f44c7 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/network/OpenDroppedBookScreenPayload.java @@ -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.ResourceLocation; + +public record OpenDroppedBookScreenPayload(DroppedBookActionPayload source, OpenDescriptiveBookScreenPayload contents) implements CustomPacketPayload { + public static final Type TYPE = new Type<>( + ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID,"open_dropped_book")); + public static final StreamCodec STREAM_CODEC = + StreamCodec.of((buf,value)->{ DroppedBookActionPayload.STREAM_CODEC.encode(buf,value.source()); OpenDescriptiveBookScreenPayload.STREAM_CODEC.encode(buf,value.contents()); }, + buf->new OpenDroppedBookScreenPayload(DroppedBookActionPayload.STREAM_CODEC.decode(buf),OpenDescriptiveBookScreenPayload.STREAM_CODEC.decode(buf))); + @Override public Type type() { return TYPE; } +} diff --git a/src/main/resources/assets/rivencraft/instability/default_block_baseline.json b/src/main/resources/assets/rivencraft/instability/default_block_baseline.json new file mode 100644 index 0000000..dcee796 --- /dev/null +++ b/src/main/resources/assets/rivencraft/instability/default_block_baseline.json @@ -0,0 +1,23 @@ +{ + "minecraft_version": "1.21.1", + "source_sample_count": 987, + "source_sha256": "5fbe706718bc983d89230fd72bd1dbe46cc352322ad33ab006142af1fe99c778", + "blocks_per_chunk": { + "create:deepslate_zinc_ore": 39.61600810536981, + "create:zinc_ore": 36.10536980749747, + "minecraft:coal_ore": 170.09625126646404, + "minecraft:deepslate_coal_ore": 0.7396149949341438, + "minecraft:deepslate_diamond_ore": 23.569402228976696, + "minecraft:deepslate_gold_ore": 21.41033434650456, + "minecraft:deepslate_iron_ore": 30.374873353596758, + "minecraft:deepslate_lapis_ore": 13.732522796352583, + "minecraft:deepslate_redstone_ore": 32.217831813576495, + "minecraft:diamond_ore": 0.3850050658561297, + "minecraft:emerald_ore": 0.47619047619047616, + "minecraft:gold_ore": 7.293819655521784, + "minecraft:iron_ore": 59.591691995947315, + "minecraft:lapis_ore": 10.065856129685917, + "minecraft:raw_iron_block": 0.14893617021276595, + "minecraft:redstone_ore": 2.812563323201621 + } +} diff --git a/src/main/resources/assets/rivencraft/lang/en_us.json b/src/main/resources/assets/rivencraft/lang/en_us.json index 58497a3..7bffc52 100644 --- a/src/main/resources/assets/rivencraft/lang/en_us.json +++ b/src/main/resources/assets/rivencraft/lang/en_us.json @@ -451,7 +451,7 @@ "itemGroup.rivencraft.pages.corrupted": "Rivencraft Corrupted Pages", "itemGroup.rivencraft.pages.environment": "Rivencraft Environment Pages", "symbol.rivencraft.environment.accelerated": "Accelerated", - "symbol.rivencraft.environment.accelerated.description": "Causes blocks in this Age to receive extra random ticks.", + "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.corrupted.large": "Corrupted Page", "symbol.rivencraft.corrupted.large.description": "The writing shifts beyond comprehension.", "symbol.rivencraft.corrupted.medium": "Corrupted Page", diff --git a/src/main/resources/rivencraft.mixins.json b/src/main/resources/rivencraft.mixins.json index e48cfcf..678b665 100644 --- a/src/main/resources/rivencraft.mixins.json +++ b/src/main/resources/rivencraft.mixins.json @@ -12,7 +12,8 @@ "RuinsDimensionMixin", "RuinsAttemptMixin", "RuinsTemplateDimensionMixin", - "StructurePlacementAccessor" + "StructurePlacementAccessor", + "LevelBlockEntityTickersAccessor" ], "client": [ "client.ClientLevelSkyColorMixin",