Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9828590009 | ||
|
|
c85b5e91cc | ||
|
|
bda7419b8b | ||
|
|
6ac4c4bfde | ||
|
|
6f42082383 | ||
|
|
9ddc139544 | ||
|
|
58d5ea82f1 | ||
|
|
40e41d6b7a | ||
|
|
b493cfe192 | ||
|
|
3d045ff99b | ||
|
|
f7d01381ec | ||
|
|
db87505142 |
No files matched your search
@@ -1,14 +1,15 @@
|
||||
# Fantasy Stick
|
||||
|
||||
**Development in progress. Manual character crafting is registered; fantasy sessions and the full RPG are not ready for deployment.**
|
||||
**Transferable characters and standalone names (US-001), equipment restoration (US-002), inventory safety (US-003), paginated character inspection (US-005), native session health/defeat (US-006), book parties/native damage protection (US-012), and switch delay (US-023) have automated implementation coverage. The full RPG remains in development and is not deployment-ready.**
|
||||
|
||||
Fantasy Stick is the proposed transferable-character RPG plugin for Social Minecraft. Its approved design uses Paper character sheets, native equipment storage and a book/basic-stick/seven-ability hotbar. Crafting is now assembled; fantasy-mode activation and most gameplay integrations remain planned. The server-independent progression core now tests initial stats/points, stat purchases, CON's equal maximum/current-health gain, capped XP and `MAX` presentation. YAML persistence, backend death/revival transitions and a native signed-book factory are also present. Saved-sheet crafting is wired; anvil-name persistence now observes native accepted takes; health, session and spell interactions remain incomplete.
|
||||
Fantasy Stick is the proposed transferable-character RPG plugin for Social Minecraft. Its approved design uses Paper character sheets, native equipment storage and a book/basic-stick/seven-ability hotbar. Crafting, native-health offhand sessions, read-only character books and book-managed parties with native damage protection are assembled; active food overrides, stat/ability book actions, combat progression and spells remain incomplete. The server-independent progression core now tests initial stats/points, stat purchases, CON's equal maximum/current-health gain, capped XP and `MAX` presentation. YAML persistence, backend death/revival transitions and a native signed-book factory are also present. Saved-sheet crafting and accepted anvil-name persistence are wired. Stat purchases and spell execution remain incomplete.
|
||||
|
||||
## Build and verify
|
||||
|
||||
- Java 25 toolchain (Gradle can resolve it), Gradle wrapper 9.6.1.
|
||||
- Purpur API/runtime `26.2.build.2618-stable`; `plugin.yml` declares API `26.2`.
|
||||
- Node.js 20 or later and npm for the TypeScript release-tool tests.
|
||||
- ProtocolLib **5.4.0** is required at runtime and declared as a compile-only dependency; it is not bundled. Install the official [server distribution](https://github.com/dmulloy2/ProtocolLib/releases/tag/5.4.0), not the Maven library JAR (which lacks bundled runtime dependencies).
|
||||
|
||||
```sh
|
||||
./gradlew clean check jar
|
||||
@@ -17,7 +18,7 @@ Fantasy Stick is the proposed transferable-character RPG plugin for Social Minec
|
||||
|
||||
`check` runs Java packaging tests, TypeScript release-client/credential-helper tests, and a native compatibility test against the checksum-verified Purpur runtime. Native preparation downloads and patches the declared runtime and loads vanilla registries/components **without starting a listening server or creating a gameplay world**. The item tests decode signed written books with Minecraft's real codec, without a plugin instance or YAML lookup. A clean build repeats that preparation. Dependencies and runtime downloads require network access.
|
||||
|
||||
Build output is `build/libs/purpur-fantasy-stick-<version>.jar`. Server APIs, tests, credentials, and Node tooling are not bundled in the plugin. Runtime identity is `FantasyStick`, entrypoint `games.dmg.fantasystick.FantasyStickPlugin`, data folder `FantasyStick`, namespace `fantasystick`. Startup registers the manual crafting controller and automated-Crafter guard before the character-sheet recipe. Commands, permissions, fantasy sessions and spells remain absent.
|
||||
Build output is `build/libs/purpur-fantasy-stick-<version>.jar`. Server APIs, tests, credentials, and Node tooling are not bundled in the plugin. Runtime identity is `FantasyStick`, entrypoint `games.dmg.fantasystick.FantasyStickPlugin`, data folder `FantasyStick`, namespace `fantasystick`. Startup registers the manual crafting controller and automated-Crafter guard before the character-sheet recipe. Equipment sessions and permission-gated administration are registered; spell execution remains absent.
|
||||
|
||||
## Character storage and keepsakes
|
||||
|
||||
@@ -27,9 +28,9 @@ The file adapter uses safe YAML construction, duplicate-key rejection, bounded r
|
||||
|
||||
`CharacterStorage` queues disk operations on its persistence worker and acknowledges successful writes only after commit. Its backend restoration checks the saved dead flag, matching current death ID and death age strictly under 24 hours at the request/selection time. It preserves progress/cooldowns and restores full character health; old books do not become eligible after a later death. This method is **not** a complete Revive spell: the engine must still validate the caster and native dialog, spend its cooldown, recheck item possession and perform physical conversion safely.
|
||||
|
||||
`TailBooks` creates vanilla `WRITTEN_BOOK` items with static pages. The full character name remains in display/pages; the native title is bounded to vanilla's 32 UTF-16 units without splitting a surrogate pair. `fantasystick:tail_version`, `character_id` and `death_id` identify the saved record. Pages/title are never read as authoritative stats or revival eligibility. Plugin absence does not remove the vanilla written-book contents. The factory does not yet deliver books from a death event.
|
||||
`TailBooks` creates vanilla `WRITTEN_BOOK` items with static pages. The full character name remains in display/pages; the native title is bounded to vanilla's 32 UTF-16 units without splitting a surrogate pair. `fantasystick:tail_version`, `character_id` and `death_id` identify the saved record. Pages/title are never read as authoritative stats or revival eligibility. Plugin absence does not remove the vanilla written-book contents. The equipment coordinator now intercepts active-session native death, restores gear and normal health, attempts the entry-location return, and saves authoritative death before guarded one-book conversion. Stale/offline/uncertain delivery is reported without reissue; this is not the complete Revive spell. Native health/session integration is described below.
|
||||
|
||||
File-level atomic replacement is **not** atomicity with Minecraft inventory/player saves. This checkpoint does not implement cross-save reconciliation, an administrator lock, automatic overflow drops or player/session persistence.
|
||||
File-level atomic replacement is **not** atomicity with Minecraft inventory/player saves. Player/session receipts and proof-based equipment reconciliation are implemented below, not an administrator lock, automatic overflow drops or guaranteed cross-save recovery.
|
||||
|
||||
## Craft preparation and conservative cleanup
|
||||
|
||||
@@ -43,7 +44,7 @@ Thirteen craft-persistence tests cover these backend boundaries, including worke
|
||||
|
||||
## Paper sheet and recipe definition
|
||||
|
||||
`CharacterSheets` renders one Paper sheet from a saved live record, with its current name and the exact offhand instruction. `fantasystick:sheet_version` (integer 1) and `character_id` (UUID string) identify the character, with no owner lock or duplicated progress snapshot. Identification is only a reference: it does not authorize entry or replace saved-state/session validation. Rendering from a dead record is refused.
|
||||
`CharacterSheets` renders one Paper sheet from a saved live record, with its current name and three separate lore lines: `Character sheet:`, `Place in off hand`, `to enter fantasy world.` Recipe previews and acknowledged crafted sheets use the same layout; existing items are not bulk-rewritten. `fantasystick:sheet_version` (integer 1) and `character_id` (UUID string) identify the character, with no owner lock or duplicated progress snapshot. Identification is only a reference: it does not authorize entry or replace saved-state/session validation. Rendering from a dead record is refused.
|
||||
|
||||
`CharacterFactory` allocates a fresh UUID and randomized two-part character name when explicitly called. It reuses the progression initializer for zero stats, level 1/zero XP, configured unspent points and full base health, with empty abilities/loadout/cooldowns and no prior death. Name collisions are allowed; identity is independent. Construction and recipe previews do not invoke allocation. Unit tests check fresh defaults/configured arbitrary-precision points, request-time allocation, seeded name variation and same-name/different-ID characters. A native composition test prepares a planned batch through YAML and verifies individually named sheets/IDs after native serialization without consuming or delivering inventory items. The assembled craft-event controller now invokes this allocator only for accepted current attempts.
|
||||
|
||||
@@ -91,7 +92,7 @@ starting-points: 40
|
||||
|
||||
The default is 40; nonnegative arbitrary-precision integers are supported. Invalid values fail before gameplay registration. Existing saved characters are not rewritten. Configuration is read on enable; no reload command or automatic data migration is supplied.
|
||||
|
||||
Nine native lifecycle tests load the actual packaged entrypoint through a test configured classloader and native `JavaPlugin.setEnabled`, then register/dispatch through Paper. They cover registration ordering, configured points, all craft routes, distinct persisted sheets, installed Crafter cancellation, failed startup and shutdown/queued-callback cleanup. Server registry/scheduler/player/world insertion are explicit test ports; this is not a listening world/client test. The assembled checkpoint passes clean/incremental packaging, all 162 tests, audit and static analysis; remote publication is tracked separately. Fantasy-mode entry and the remaining RPG are not implemented.
|
||||
Nine native lifecycle tests load the actual packaged entrypoint through a test configured classloader and native `JavaPlugin.setEnabled`, then register/dispatch through Paper. They cover registration ordering, configured points, all craft routes, distinct persisted sheets, installed Crafter cancellation, failed startup and shutdown/queued-callback cleanup. Server registry/scheduler/player/world insertion are explicit test ports; this is not a listening world/client test. The assembled checkpoint passes clean/incremental packaging, all 162 tests, audit and static analysis; remote publication is tracked separately. This historical crafting checkpoint predates the equipment-session integration below; the remaining RPG is not complete.
|
||||
|
||||
## Accepted anvil names
|
||||
|
||||
@@ -99,13 +100,21 @@ Nine native lifecycle tests load the actual packaged entrypoint through a test c
|
||||
|
||||
Vanilla retains responsibility for item movement, XP charging and anvil damage. The inspected event fires at the start of native accepted-take processing, before that continuation; the observer does not make native completion contingent on YAML acknowledgment. Failure/crash may leave item presentation ahead of the saved name. The original saved progress is retained and captured IDs are logged; there is no automatic item/XP rollback, reissue or guaranteed retry.
|
||||
|
||||
Six backend tests, seven native observer tests and an added packaged-entrypoint registration test cover preservation, sequencing, failures, shutdown, preview/take separation, name fallbacks and later serialized sheet/Tail rendering. Native XP/damage execution and live clients are not exercised by these fixtures. Active overhead/chat/tab presentation and fantasy sessions remain incomplete. This slice passes 176 tests, clean/incremental packaging, three additional native-suite repeats, audit and static analysis. A controller test's leftover retry was explicitly drained before fixture reuse (12 focused stress runs pass); production shutdown remains nonblocking. Remote publication is tracked separately.
|
||||
Six backend tests, seven native observer tests and an added packaged-entrypoint registration test cover preservation, sequencing, failures, shutdown, preview/take separation, name fallbacks and later serialized sheet/Tail rendering. Native XP/damage execution and live clients are not exercised by these fixtures. Active overhead/chat/tab presentation now refreshes after acknowledged saves, including renaming a copied reference held by someone else; stale session/revision callbacks cannot rename a replacement holder. This slice passes 176 tests, clean/incremental packaging, three additional native-suite repeats, audit and static analysis. A controller test's leftover retry was explicitly drained before fixture reuse (12 focused stress runs pass); production shutdown remains nonblocking. Remote publication is tracked separately.
|
||||
|
||||
## Session claims (not wired to activation)
|
||||
## Native health ceiling (historical core checkpoint)
|
||||
|
||||
`CharacterProgress` now limits base maximum health to `min(10 + CON, supplied native limit)` without limiting CON purchases. A purchase adds only the actual maximum-health gain to current health: fractional gain when crossing the ceiling, zero gain once capped. Injury and revision/idempotency protections remain intact. The two-argument initializer uses the pinned runtime's default 1,024 HP; runtime adapters must pass their actual ceiling explicitly.
|
||||
|
||||
`NativeHealthLimit.read()` reads the current native ranged attribute through the pinned runtime's public Craft/native accessors, without setting attributes or changing configuration. It must run on the server thread after registry initialization. Incompatible accessors or nonpositive/nonfinite/unrepresentable native ranges fail explicitly instead of guessing. This is not a refusal based on CON. Tests cover core purchases and actual native attribute compatibility at 10.5, 1,024 and 2,048 HP; native tests restore their temporary in-process range changes in `finally`.
|
||||
|
||||
At this historical checkpoint, no virtual health, global configuration change, stored-data migration or active-player health adapter was introduced. The persisted schema's raw `10 + CON` validation envelope remains unchanged for compatibility. The later native session integration is described below; a complete Revive spell remains unfinished. Current-health gain is calculated against the core instance's fixed supplied limit; callers must obtain/revalidate the applicable limit at their native operation boundary. This slice passes 186 tests, clean/incremental packaging, audit and static analysis. Remote publication is tracked separately.
|
||||
|
||||
## Session claims
|
||||
|
||||
`SessionClaims` supplies process-local exclusion for pending/active character sessions. A single shared registry atomically prevents simultaneous claims for either the same character identity or the same player's active mode. This does not limit how many sheets a player may own or permanently bind a character to a holder. Released characters can transfer; a stale token cannot release a replacement claim. Private claim objects carry distinct session UUIDs for future equipment/callback correlation. Dead/zero-health DTOs refuse unchanged; shutdown invalidates all claims and refuses new ones.
|
||||
|
||||
Six unit tests cover exclusion, transfer/switch release, stale callbacks, invalid input, shutdown/restart boundaries, same-name identities, uncapped values and 24 rounds of 16 competing callbacks. The registry does no persistence or native work and does not impose a native-health cap. It must be shared across entry routes; separate processes do not coordinate. Callers still must load current authoritative state, validate sheet possession/context/deadlines, preflight native equipment/health, retain/release claims across their lifecycle and reconcile interrupted state. `isCurrent()` is a lifetime check, not saved-state or effect authorization. No fantasy activation is registered yet. The foundation passes 182 tests, clean/incremental packaging, audit and static analysis; remote publication is tracked separately.
|
||||
Six unit tests cover exclusion, transfer/switch release, stale callbacks, invalid input, shutdown/restart boundaries, same-name identities, uncapped values and 24 rounds of 16 competing callbacks. The registry does no persistence or native work and does not impose a native-health cap. It must be shared across entry routes; separate processes do not coordinate. Callers still must load current authoritative state, validate sheet possession/context/deadlines, preflight native equipment/health, retain/release claims across their lifecycle and reconcile interrupted state. `isCurrent()` is a lifetime check, not saved-state or effect authorization. The equipment coordinator now uses one shared registry for its entry/exit routes. The historical foundation passed 182 tests, clean/incremental packaging, audit and static analysis; remote publication is tracked separately.
|
||||
|
||||
## Native equipment adapter
|
||||
|
||||
@@ -113,7 +122,81 @@ Six unit tests cover exclusion, transfer/switch release, stale callbacks, invali
|
||||
|
||||
Version-1 box metadata uses `fantasystick:storage_version`, `storage_owner_id`, `storage_session_id` and `storage_slots`. Box positions 0–8 contain original hotbar slots 0–8; positions 9–12 contain boots, leggings, chest and head from player slots 36–39. These metadata fields are for identity/restoration, not the only copy of the items. Restoration searches main slots 9–35, so sorting relocation does not lose the box. Repeated requests, wrong identity, duplicate/malformed boxes, unexpected extra contents or occupied restoration slots do not overwrite/delete items. These are adapter error results, not a persistent administrator lock or completed recovery policy.
|
||||
|
||||
The caller must remove authenticated fantasy controls before restoration. One new head stack uses the slot freed by removing the box, even with a full main inventory; there is no drop fallback. The adapter does not yet route sheet/cursor events, emit entry warnings, manage character/player snapshots or register a playable session. Native tests use real player-slot storage with only the absent network recipient stubbed; client packets and live gameplay remain unverified.
|
||||
The coordinator supplies authenticated control ownership to the adapter, which validates all destinations before replacing controls. One new head stack uses the slot freed by removing the box, even with a full main inventory; there is no drop fallback. The equipment coordinator/event bridge now routes sheet/cursor events, emits entry warnings and registers sessions. Native health/vitals integration is described below; active nutrition overrides remain unfinished. Standalone display projection is implemented below. Native tests use real player-slot storage with only the absent network recipient stubbed; client packets and live gameplay remain unverified.
|
||||
|
||||
## Equipment sessions and safe box movement
|
||||
|
||||
The historical US-002 completion checkpoint passed all acceptance criteria and **359 automated tests** (315 Java/native and 44 release-tool tests), clean/incremental packaging, dependency audit and static analysis. The new equipment path loads authoritative characters, claims player/character identity, and acknowledges `<plugin data>/sessions/<player UUID>.yml` before packing. Preparation failure leaves gear unchanged. Nine typed bound controls occupy the hotbar; book/ability actions were not yet implemented at that checkpoint. Current inspection and party actions are described below; basic/learned attacks remain unfinished.
|
||||
|
||||
The genuine **Fantasy Storage Box** contains actual original items. Picking it up for a move leaves it in main storage and issues a harmless bound cursor move-control. Confirming a valid main-storage destination exchanges the real box and that destination's contents; closing the inventory cancels the move. Sorting, stale callbacks and lifecycle changes cannot confer movement authority on a copied control. Full storage needs no extra space or overflow drops. Ordinary sheet movements, including Q/Ctrl-Q, remain supported.
|
||||
|
||||
Exit removes controls and restores original slots once, locating the genuine box by owner/session rather than original index. A new head uses the freed box slot. Native player phase markers and the persisted receipt must agree for recovery; ambiguous state is preserved/reported, never guessed into replacement gear. Shutdown is best-effort and nonblocking; accepted cleanup drains before its receipt worker closes. Equipment stays vanilla-readable without this plugin.
|
||||
|
||||
Optional `character-swap-cooldown-seconds` defaults to `900`; zero bypasses the player-bound restriction. Existing absolute deadlines survive configuration changes; only a new actual exit starts a new deadline, and repeated cleanup does not extend it. The switch-delay setting is read on enable; there is no general reload command or deployed configuration change.
|
||||
|
||||
Administration (permission `fantasystick.admin`, default operators):
|
||||
|
||||
- `/fantasystick inspect <player-uuid>` — asynchronous receipt/native-session inspection.
|
||||
- `/fantasystick recover <player-uuid>` — validated online equipment/game-mode restoration only; no forced overwrite, progression grant or ambiguous replay.
|
||||
- `/fantasystick config adventure-mode [true|false]` — show or persist the policy for new sessions; no change to active sessions.
|
||||
|
||||
Tests use actual native items, inventories, serialization, Paper event dispatch and menu-close behavior, with explicit scheduler/player/world ports. Drag continuation ordering includes a model based on pinned bytecode. The packaged lifecycle fixture isolates the entrypoint but delegates helpers parent-first. Live clients, production PluginClassLoader execution and arbitrary-plugin/crash atomicity are not claimed verified. No deployment or existing-data migration is authorized by story completion.
|
||||
|
||||
## Standalone character presentation
|
||||
|
||||
Saved character identity/progress transfers between holders; ordinary equipment, vitals, return location and switch deadline do not. Native reference/session tests cover live/dead/invalid/copied identities, concurrent exclusion, orderly switches and legitimate backend revival. The complete Revive spell remains unfinished.
|
||||
|
||||
ProtocolLib-backed presentation shows the full literal saved name above the player, in chat and in the player list, without changing the server account name/UUID/profile, scoreboard membership, ordinary display/list fields or authoritative name-tag-distance attribute. A detached client-only TextDisplay replaces the native overhead label; display-name-only player-info packets and the chat renderer's sender-name argument cover the other surfaces. No signed message-body or recipient rewrite is introduced.
|
||||
|
||||
Output resources belong to a player connection/session, not the sheet. Exit/defeat/lifecycle cleanup withdraws them independently of successful gear restoration, using current ordinary server state rather than replaying stale fantasy names. Renames refresh only after authoritative file acknowledgment; future sessions also reload saved names. Reconnect/restart discards client-only labels, not ordinary identity data.
|
||||
|
||||
**Cross-plugin display compatibility is unsupported**, as explicitly requested. There is no Stealth/Leaf/Ignis bridge or nickname/concealment guarantee. Native/platform visibility and ordinary cancellations are covered; supplemental presentation-owned packets bypass ProtocolLib filters to avoid recursive projection. Names can therefore conflict with other plugins' presentation or packet-only concealment. This does not disable ordinary protection or inventory safeguards.
|
||||
|
||||
Tests exercise actual native codecs, renderer inputs and ProtocolLib dispatch with explicit transport/server/player ports. They do not prove live-client appearance or client delivery acknowledgments. Unknown transport outcomes are reported without speculative spawn replay; cleanup remains best-effort. Label reconciliation is tick-driven; live-client/network-load observation remains a follow-up. Optional Adventure mode is described below; its verification does not complete the remaining fantasy health, nutrition or combat features.
|
||||
|
||||
## Optional Adventure mode
|
||||
|
||||
`adventure-mode: true` is the default. A new entry captures this policy; enabled entries save the holder's original game mode in the player/session receipt before changing it to Adventure. Disabled entries leave the mode untouched, as do holders already in Adventure. This state never transfers with the character.
|
||||
|
||||
The admin command saves on a worker, preserving unrelated configuration values, before publishing its effective value. Invalid values and failed writes leave that value unchanged. Already active sessions keep their captured policy. Accepted writes drain without blocking shutdown; immediate re-enable defers startup asynchronously until those writes finish, then reads the saved policy.
|
||||
|
||||
Exit, defeat and best-effort lifecycle/recovery cleanup restore only an owned Adventure change. Observed later admin changes relinquish ownership, including an observed change away and back. Native cancellation refuses entry without packing; a cancelled restoration retains its receipt for inspection/retry. Interrupted or mismatched player markers are not replay permission. Mode cleanup is independent of uncertain equipment cleanup.
|
||||
|
||||
A same-process retry can acknowledge gear already verified restored for that exact player while retrying a vetoed mode restoration; a serialized `RESTORED` marker alone cannot establish this after restart. Missing game-mode proof leaves the mode and receipt retained even when independently verified gear can be restored and synchronized. Player-data and YAML saves are not one transaction; unobserved out-of-band state edits are not detectable history. No forced player save, blanket Survival reset or deployment is introduced.
|
||||
|
||||
## Native fantasy health, exit and defeat
|
||||
|
||||
Offhand entry applies actual native maximum health `min(10 + CON, native health limit)`, resumes saved remaining character health, and shows public blue particles. A fresh character's saved health starts full. CON has no gameplay cap; high values do not reject entry. Native damage/healing rules remain in effect, with the existing party/mixed-mode protection. The book reports current native health rather than waiting for an exit save.
|
||||
|
||||
`NativeMaximumHealth` owns only the effective-value cache/dirty callback of that player's existing native maximum-health instance. Base values, modifiers and native potion expiry remain owned by their original sources; nothing is copied back from an old modifier snapshot. The native player health methods and client attribute snapshot are tested. This adapter uses **pinned Purpur 2618 internals**, including private fields; a detached startup probe exercises installation, recalculation and removal before gameplay is registered. Runtime upgrades require renewed native compatibility verification, not a guessed fallback or global attribute-limit changes. Matching native health scaling displays the real fantasy maximum, not a separate virtual health pool; a later unrelated display-scale change is preserved on exit.
|
||||
|
||||
Ordinary health, food, saturation, exhaustion and health-display state belong to the holder/session, not the character sheet. The session receipt acknowledges this snapshot before native mutation; versioned player PDC records its application/restoration phase. Voluntary exit restores ordinary gear/vitals at the current location, with ordinary health capped by the current legitimate maximum. Character damage is saved on the worker, and the character claim/receipt cannot complete ahead of that acknowledgment. Quit and disable perform the same best-effort cleanup. Failed or uncertain saves retain the receipt and acknowledged character record instead of permitting a stale-health reentry. Missing/ambiguous native proof never authorizes a snapshot heal; process-owned maximum overrides are still retired independently of equipment/client-write failures.
|
||||
|
||||
An intercepted fantasy defeat records authoritative death once, removes session state, restores ordinary health to its current maximum and attempts return to the entry location. Ordinary health is restored before health-scale setters can send or queue client health packets: cancelled defeat must not deliver zero health and strand an otherwise alive player on a death screen. Refused/failed return leaves the player at the current location with a warning, not an alternate destination or invulnerability. A public red burst marks the defeat location. After the death acknowledgment, guarded conversion replaces the unchanged sheet stack with one signed Tail book. New Tails group ordinary-sized name/level/XP/points/stats on a summary page, then give each learned ability its own section with saved ID, assigned ability slots and cooldown deadline. Unknown IDs, saved unlearned cooldowns, empty abilities and death time stay explicit; long content continues onto additional pages without truncation. No ability descriptions are invented and existing books are not rewritten. Static Unicode-safe Tail pagination survives native serialization without a plugin; signed books use a different codec from the 100-page writable-book format. Stale or ambiguous conversion never overwrites another item or automatically reissues a book.
|
||||
|
||||
Interrupted recovery requires matching player/session receipt and native proof. It preserves current native modifier ownership and does not resurrect expired effects. Repeated/stale recovery cannot replay ordinary health or recreate an already released claim. This is **not crash-atomic** across player, inventory and plugin files; unresolved native setter phases and unacknowledged progress may require inspection. Legacy equipment-only receipts remain readable but do not grant health-restoration authority. Older binaries do not understand the new optional ordinary-vitals receipt field; do not downgrade across unresolved newer receipts.
|
||||
|
||||
Active hunger/exhaustion suppression and food-regeneration discrimination remain US-026 work. Book stat purchases, XP delivery, basic/learned attacks and Revive remain separate unfinished stories. The preceding equipment/progression checkpoint sections are historical evidence, not the current health scope.
|
||||
|
||||
## Character inspection and inventory safety
|
||||
|
||||
The first-hotbar-slot book reads the active character's authoritative name, six stats, health, level, XP/MAX, points and learned identities. Inspection does not change character data or inventory. Plain-text pages wrap conservatively for the vanilla font without splitting Unicode code points. Large supported records use volumes of at most 80 inspection pages, leaving room for navigation and party controls while bounding each opened view's payload. This is a plugin presentation bound, not Minecraft's 100-page writable-book cap; signed books use a different codec. `[Next pages]` / `[Previous pages]` reread current data; unknown ability IDs and arbitrarily large saved numbers are not silently discarded.
|
||||
|
||||
Deferred reads and single-use navigation validate the player, session, character and held control. Superseded requests, ended sessions, quit/disable and invalid client tokens cannot open a stale view. Read failures preserve data and allow reopening. Native tests cover overflow, multiple volumes, rename, transfer, reload and unchanged inventory/data; actual client rendering and custom resource-pack fonts are not claimed as tested.
|
||||
|
||||
All nine hotbar controls remain bound, with seven selectable placeholders on a new character. Native containment tests cover export/consumption, hidden swaps, recipe autofill, armor/cosmetics, cursor custody and sorting relocation. The packaged inventory journey proves that these guards still permit the real book action and that removing the transferable offhand sheet restores ordinary equipment. Future attack/ability consumers must retain these same safeguards.
|
||||
|
||||
## Character-book parties and combat protection
|
||||
|
||||
Use the slot-1 book to create a party, invite online players, accept invitations, leave, kick members or disband. Parties hold up to six consenting players. Only the creator/leader may invite, kick or disband; a leader leaving disbands rather than transferring leadership. Invitations last 60 real seconds and reserve no capacity. Book actions are single-use and bound to the current player/session/view, with authority and capacity rechecked on execution. Membership belongs to the player, not a traded character sheet, and grants no XP by itself.
|
||||
|
||||
A disconnected leader remains leader while another member is online. All-offline parties, invitations and book views are discarded on shutdown/restart. This does not persist or restore party rosters.
|
||||
|
||||
Native damage protection blocks friendly fire between active fantasy party members and player-attributable mixed-mode damage in both directions. Ordinary-versus-ordinary and environmental/mob combat retain their native rules and prior cancellations. Projectiles, TNT, fangs, clouds, fireworks and pet attacks retain player attribution; delayed fantasy sources cannot borrow a new session after exit, transfer or reconnect. Valid native healing is unchanged; stale projectile impacts are rejected before execution. Full RPG attacks and support/XP abilities remain separate unfinished work.
|
||||
|
||||
Attributable poison, wither and burning retain bounded source/recipient provenance in native entity/player PDC (`combat_origin_v1`, `combat_dot_*_v1`). Each damage tick checks current membership, source/recipient session identity and native effect state. Poison/wither hidden layers keep their own source rather than inheriting a covering effect's origin. Removal, expiry and unrelated replacement clear only the matching provenance; cleanup does not remove native effects or change health, equipment, character YAML or XP. A tick-driven cleanup checks only the three relevant player metadata keys and stops on disable. Native PDC serialization retains source proofs across reload; ended fantasy sessions remain invalid, while parties themselves never survive restart. These are native save guarantees, not cross-save atomicity or dedicated cross-plugin integration.
|
||||
|
||||
Automated party tests exercise actual packaged listeners, native book custom-click payloads, native event dispatch, effect-merging semantics and PDC serialization. Player/network/world execution remains represented by explicit test ports; live multiplayer testing and deployment are separate.
|
||||
|
||||
## CI and publication
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ tasks.withType<JavaCompile>().configureEach {
|
||||
|
||||
dependencies {
|
||||
compileOnly("org.purpurmc.purpur:purpur-api:26.2.build.2618-stable")
|
||||
compileOnly("net.dmulloy2:ProtocolLib:5.4.0")
|
||||
testImplementation("net.dmulloy2:ProtocolLib:5.4.0")
|
||||
testImplementation("org.purpurmc.purpur:purpur-api:26.2.build.2618-stable")
|
||||
testImplementation(platform("org.junit:junit-bom:5.13.4"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||
@@ -71,6 +73,8 @@ val nativeTest = sourceSets.create("nativeTest")
|
||||
dependencies {
|
||||
add(nativeTest.implementationConfigurationName, platform("org.junit:junit-bom:5.13.4"))
|
||||
add(nativeTest.implementationConfigurationName, "org.junit.jupiter:junit-jupiter")
|
||||
add(nativeTest.implementationConfigurationName, "net.dmulloy2:ProtocolLib:5.4.0")
|
||||
add(nativeTest.implementationConfigurationName, "org.mockito:mockito-core:5.18.0")
|
||||
add(nativeTest.compileOnlyConfigurationName, "org.jetbrains:annotations:26.0.2")
|
||||
add(nativeTest.compileOnlyConfigurationName, "org.checkerframework:checker-qual:3.49.2")
|
||||
add(nativeTest.runtimeOnlyConfigurationName, "org.junit.platform:junit-platform-launcher")
|
||||
@@ -78,6 +82,8 @@ dependencies {
|
||||
val nativeRuntimeJars = files(fileTree(nativeRuntime) {
|
||||
include("versions/**/*.jar", "libraries/**/*.jar")
|
||||
}).builtBy(prepareNativeRuntime)
|
||||
// Pinned output-only packet codec; native classes remain provided by the server, never bundled.
|
||||
sourceSets.main.get().compileClasspath += nativeRuntimeJars
|
||||
nativeTest.compileClasspath += sourceSets.main.get().output + nativeRuntimeJars
|
||||
nativeTest.runtimeClasspath += sourceSets.main.get().output + nativeRuntimeJars
|
||||
val nativeCompatibilityTest = tasks.register<Test>("nativeCompatibilityTest") {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import com.comphenix.protocol.ProtocolLibrary;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation;
|
||||
import games.dmg.fantasystick.presentation.CharacterChatNames;
|
||||
import games.dmg.fantasystick.presentation.ProtocolPresentation;
|
||||
import games.dmg.fantasystick.crafting.CharacterFactory;
|
||||
import games.dmg.fantasystick.crafting.CharacterAnvilNames;
|
||||
import games.dmg.fantasystick.crafting.ManualCraftingController;
|
||||
@@ -7,22 +11,62 @@ import games.dmg.fantasystick.crafting.ManualCraftingGuard;
|
||||
import games.dmg.fantasystick.crafting.PlayerSheetDrops;
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.EquipmentSessionStore;
|
||||
import games.dmg.fantasystick.session.EquipmentAdminCommand;
|
||||
import games.dmg.fantasystick.session.EquipmentSessionEvents;
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import games.dmg.fantasystick.persistence.YamlCharacterRepository;
|
||||
import games.dmg.fantasystick.progression.ProgressionRules;
|
||||
import java.time.Clock;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/** Manual character crafting and anvil names; fantasy sessions and remaining gameplay are not registered yet. */
|
||||
/** Crafting, native fantasy sessions, books, parties and names; progression actions and spells remain separate. */
|
||||
public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private CharacterStorage characters;
|
||||
private ManualCraftingController crafting;
|
||||
private ManualCraftingGuard guard;
|
||||
private CharacterAnvilNames anvilNames;
|
||||
private boolean recipeRegistered;
|
||||
private EquipmentSessionStore receipts;
|
||||
private EquipmentSessions sessions;
|
||||
private EquipmentSessionEvents sessionEvents;
|
||||
private games.dmg.fantasystick.book.CharacterBookController books;
|
||||
private games.dmg.fantasystick.party.PartyRoster parties;
|
||||
private games.dmg.fantasystick.party.PartyEvents partyEvents;
|
||||
private games.dmg.fantasystick.party.PartyCombat partyCombat;
|
||||
private EquipmentAdminCommand admin;
|
||||
private volatile Object lifetime;
|
||||
private CharacterPresentation presentation;
|
||||
private ProtocolPresentation protocolPresentation;
|
||||
private CharacterChatNames chatNames;
|
||||
private games.dmg.fantasystick.persistence.AdventureSettings adventureSettings;
|
||||
private games.dmg.fantasystick.session.AdventureModeLease gameModes;
|
||||
private games.dmg.fantasystick.session.SessionVitals vitals;
|
||||
private games.dmg.fantasystick.session.SessionVisuals sessionVisuals;
|
||||
private java.util.concurrent.CompletionStage<Void> configurationDrain = java.util.concurrent.CompletableFuture.completedStage(null);
|
||||
|
||||
@Override public void onEnable() {
|
||||
try {
|
||||
Object generation = new Object();
|
||||
lifetime = generation;
|
||||
if (!configurationDrain.toCompletableFuture().isDone()) {
|
||||
configurationDrain.whenComplete((ignored, failure) -> {
|
||||
if (lifetime != generation) return;
|
||||
try {
|
||||
getServer().getScheduler().runTask(this, () -> {
|
||||
if (lifetime == generation && isEnabled()) onEnable();
|
||||
});
|
||||
} catch (RuntimeException rejected) {
|
||||
getLogger().log(Level.WARNING, "Configuration startup continuation unavailable", rejected);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
reloadConfig();
|
||||
var adventure = games.dmg.fantasystick.persistence.AdventureSettings.validate(getConfig().get("adventure-mode"));
|
||||
adventureSettings = new games.dmg.fantasystick.persistence.AdventureSettings(getDataFolder().toPath(), adventure);
|
||||
var switchDelay = switchDelay();
|
||||
var defaults = ProgressionRules.defaults();
|
||||
var rules = new ProgressionRules(new java.math.BigInteger(getConfig().getString("starting-points", "40")),
|
||||
defaults.xpPerLevel(), defaults.maximumLevel());
|
||||
@@ -33,47 +77,188 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
player -> new PlayerSheetDrops(player, event -> getServer().getPluginManager().callEvent(event)),
|
||||
problem -> getLogger().log(Level.WARNING, "Character craft " + problem.operation() + " for player "
|
||||
+ problem.player() + "; character records " + problem.characters(), problem.cause()));
|
||||
java.util.function.Consumer<Runnable> nextTick = task -> getServer().getScheduler().runTask(this, task);
|
||||
java.util.function.Consumer<Throwable> presentationFailures = problem ->
|
||||
getLogger().log(Level.WARNING, "Character presentation failed", problem);
|
||||
// This supplier belongs to one enable, never the mutable plugin field after re-enable.
|
||||
var localPresentation = new java.util.concurrent.atomic.AtomicReference<CharacterPresentation>();
|
||||
var installationFailure = new java.util.concurrent.atomic.AtomicReference<Throwable>();
|
||||
protocolPresentation = new ProtocolPresentation(this, ProtocolLibrary.getProtocolManager(),
|
||||
() -> localPresentation.get().snapshot(), problem -> {
|
||||
installationFailure.compareAndSet(null, problem);
|
||||
presentationFailures.accept(problem);
|
||||
});
|
||||
presentation = new CharacterPresentation(protocolPresentation, nextTick,
|
||||
() -> getServer().isPrimaryThread(), presentationFailures, characters::find);
|
||||
localPresentation.set(presentation);
|
||||
chatNames = new CharacterChatNames(presentation::name);
|
||||
protocolPresentation.install();
|
||||
if (installationFailure.get() != null) {
|
||||
throw new IllegalStateException("Could not install character presentation", installationFailure.get());
|
||||
}
|
||||
guard = new ManualCraftingGuard();
|
||||
anvilNames = new CharacterAnvilNames(characters,
|
||||
problem -> getLogger().log(Level.WARNING, "Character name update was refused or failed for player "
|
||||
+ problem.player() + "; character " + problem.character(), problem.cause()), getServer().getItemFactory());
|
||||
+ problem.player() + "; character " + problem.character(), problem.cause()), getServer().getItemFactory(),
|
||||
presentation::acknowledged);
|
||||
receipts = new EquipmentSessionStore(getDataFolder().toPath(), Clock.systemUTC());
|
||||
java.util.function.Consumer<EquipmentSessions.Failure> diagnostics = problem ->
|
||||
getLogger().log(Level.WARNING, "Equipment transition/recovery for player " + problem.player()
|
||||
+ "; session " + problem.session(), problem.cause());
|
||||
gameModes = new games.dmg.fantasystick.session.AdventureModeLease();
|
||||
sessions = new EquipmentSessions(characters, receipts, switchDelay, Clock.systemUTC(), nextTick,
|
||||
notice -> notifyPlayer(generation, notice), diagnostics, presentation, adventureSettings::enabled, gameModes);
|
||||
vitals = new games.dmg.fantasystick.session.SessionVitals();
|
||||
sessions.attachVitals(vitals);
|
||||
parties = new games.dmg.fantasystick.party.PartyRoster(Clock.systemUTC(), id -> {
|
||||
var player = getServer().getPlayer(id);
|
||||
return player != null && player.isOnline();
|
||||
});
|
||||
partyEvents = new games.dmg.fantasystick.party.PartyEvents(parties);
|
||||
partyCombat = new games.dmg.fantasystick.party.PartyCombat(parties, sessions);
|
||||
books = new games.dmg.fantasystick.book.CharacterBookController(characters, rules, nextTick,
|
||||
problem -> getLogger().log(Level.WARNING, "Character book failed for player " + problem.player()
|
||||
+ "; character " + problem.character(), problem.cause()), parties, getServer(), id -> {
|
||||
String name = localPresentation.get().name(id);
|
||||
var player = getServer().getPlayer(id);
|
||||
return net.kyori.adventure.text.Component.text(name != null ? name : player == null ? id.toString() : player.getName());
|
||||
});
|
||||
sessionEvents = new EquipmentSessionEvents(sessions, nextTick, diagnostics, books);
|
||||
admin = new EquipmentAdminCommand(receipts, sessions, getServer(), nextTick,
|
||||
problem -> getLogger().log(Level.WARNING, "Equipment admin " + problem.operation()
|
||||
+ " for player " + problem.player(), problem.cause()), adventureSettings);
|
||||
var command = java.util.Objects.requireNonNull(getCommand("fantasystick"), "Missing packaged fantasystick command");
|
||||
command.setExecutor(admin);
|
||||
command.setTabCompleter(admin);
|
||||
getServer().getPluginManager().registerEvents(crafting, this);
|
||||
getServer().getPluginManager().registerEvents(guard, this);
|
||||
getServer().getPluginManager().registerEvents(anvilNames, this);
|
||||
getServer().getPluginManager().registerEvents(sessionEvents, this);
|
||||
getServer().getPluginManager().registerEvents(chatNames, this);
|
||||
getServer().getPluginManager().registerEvents(partyEvents, this);
|
||||
getServer().getPluginManager().registerEvents(partyCombat, this);
|
||||
partyCombat.install(this);
|
||||
getServer().getPluginManager().registerEvents(books, this);
|
||||
getServer().getPluginManager().registerEvents(gameModes, this);
|
||||
sessionVisuals = new games.dmg.fantasystick.session.SessionVisuals(sessions,
|
||||
failure -> getLogger().log(Level.WARNING, "Fantasy session particle delivery failed", failure));
|
||||
sessionVisuals.install(this);
|
||||
recipeRegistered = getServer().addRecipe(new CharacterSheets().recipe());
|
||||
if (!recipeRegistered) throw new IllegalStateException("Character-sheet recipe key is already registered");
|
||||
} catch (RuntimeException failure) {
|
||||
for (var player : getServer().getOnlinePlayers()) sessions.arrive(player);
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
try { onDisable(); }
|
||||
catch (RuntimeException cleanupFailure) { failure.addSuppressed(cleanupFailure); }
|
||||
catch (RuntimeException | LinkageError cleanupFailure) { failure.addSuppressed(cleanupFailure); }
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onDisable() {
|
||||
if (crafting != null) crafting.close();
|
||||
if (recipeRegistered) {
|
||||
try {
|
||||
getServer().removeRecipe(CharacterSheets.RECIPE);
|
||||
recipeRegistered = false;
|
||||
} catch (RuntimeException failure) {
|
||||
getLogger().log(Level.WARNING, "Could not remove the character-sheet recipe; continuing shutdown cleanup", failure);
|
||||
}
|
||||
lifetime = null;
|
||||
// Detach this enable's resources before any native callback can reenter disable.
|
||||
var closingPresentation = presentation; presentation = null;
|
||||
var closingProtocol = protocolPresentation; protocolPresentation = null;
|
||||
var closingChat = chatNames; chatNames = null;
|
||||
var closingAdmin = admin; admin = null;
|
||||
var closingEvents = sessionEvents; sessionEvents = null;
|
||||
var closingBooks = books; books = null;
|
||||
var closingPartyEvents = partyEvents; partyEvents = null;
|
||||
var closingPartyCombat = partyCombat; partyCombat = null;
|
||||
var closingParties = parties; parties = null;
|
||||
var closingCrafting = crafting; crafting = null;
|
||||
var closingGuard = guard; guard = null;
|
||||
var closingAnvil = anvilNames; anvilNames = null;
|
||||
var closingSessions = sessions; sessions = null;
|
||||
var closingReceipts = receipts; receipts = null;
|
||||
var closingCharacters = characters; characters = null;
|
||||
var closingSettings = adventureSettings; adventureSettings = null;
|
||||
var closingModes = gameModes; gameModes = null;
|
||||
var closingVitals = vitals; vitals = null;
|
||||
var closingVisuals = sessionVisuals; sessionVisuals = null;
|
||||
// Retire client resources independently of successful ordinary-equipment restoration.
|
||||
if (closingPresentation != null) cleanup("presentation", closingPresentation::close);
|
||||
if (closingProtocol != null) cleanup("protocol presentation", closingProtocol::close);
|
||||
if (closingAdmin != null) cleanup("admin command", closingAdmin::close);
|
||||
if (closingSettings != null) {
|
||||
configurationDrain = closingSettings.drained();
|
||||
cleanup("configuration", closingSettings::close);
|
||||
}
|
||||
if (crafting != null) {
|
||||
org.bukkit.event.HandlerList.unregisterAll(crafting);
|
||||
crafting = null;
|
||||
}
|
||||
if (guard != null) {
|
||||
org.bukkit.event.HandlerList.unregisterAll(guard);
|
||||
guard = null;
|
||||
}
|
||||
if (anvilNames != null) {
|
||||
org.bukkit.event.HandlerList.unregisterAll(anvilNames);
|
||||
anvilNames = null;
|
||||
}
|
||||
if (characters != null) {
|
||||
characters.close();
|
||||
characters = null;
|
||||
if (closingBooks != null) cleanup("character book", closingBooks::close);
|
||||
if (closingVisuals != null) cleanup("session particles", closingVisuals::close);
|
||||
if (closingParties != null) cleanup("parties", closingParties::close);
|
||||
if (closingPartyCombat != null) cleanup("party combat", closingPartyCombat::close);
|
||||
if (closingEvents != null) cleanup("session events", closingEvents::close);
|
||||
if (closingCrafting != null) cleanup("craft attempts", closingCrafting::close);
|
||||
if (closingSessions != null) cleanup("equipment sessions", closingSessions::close);
|
||||
if (closingVitals != null) cleanup("native health hooks", closingVitals::close);
|
||||
unregister(closingModes);
|
||||
unregister(closingChat);
|
||||
unregister(closingPartyEvents);
|
||||
unregister(closingPartyCombat);
|
||||
unregister(closingBooks);
|
||||
unregister(closingEvents);
|
||||
unregister(closingCrafting);
|
||||
unregister(closingGuard);
|
||||
unregister(closingAnvil);
|
||||
if (recipeRegistered) cleanup("character-sheet recipe", () -> {
|
||||
getServer().removeRecipe(CharacterSheets.RECIPE);
|
||||
recipeRegistered = false; // Retain ownership for a later retry if removal failed.
|
||||
});
|
||||
if (closingCharacters != null) cleanup("character storage", closingCharacters::close);
|
||||
// Never await IO on the server thread or close receipts ahead of accepted preparations.
|
||||
if (closingReceipts != null) cleanup("equipment receipt drain", () -> {
|
||||
if (closingSessions == null) closingReceipts.close();
|
||||
else closingSessions.drained().whenComplete((ignored, failure) -> closingReceipts.close());
|
||||
});
|
||||
}
|
||||
|
||||
private void unregister(org.bukkit.event.Listener listener) {
|
||||
if (listener != null) cleanup("listener " + listener.getClass().getSimpleName(),
|
||||
() -> org.bukkit.event.HandlerList.unregisterAll(listener));
|
||||
}
|
||||
|
||||
private void cleanup(String resource, Runnable action) {
|
||||
try { action.run(); }
|
||||
catch (RuntimeException | LinkageError failure) {
|
||||
try { getLogger().log(Level.WARNING, "Could not close " + resource + "; continuing shutdown cleanup", failure); }
|
||||
catch (RuntimeException | LinkageError ignored) { /* Diagnostics must not prevent remaining cleanup. */ }
|
||||
}
|
||||
}
|
||||
|
||||
private java.time.Duration switchDelay() {
|
||||
Object configured = getConfig().get("character-swap-cooldown-seconds", 900);
|
||||
String value = String.valueOf(configured);
|
||||
if (!value.matches("[0-9]+")) {
|
||||
throw new IllegalArgumentException("character-swap-cooldown-seconds must be a nonnegative integer");
|
||||
}
|
||||
try {
|
||||
var delay = java.time.Duration.ofSeconds(new java.math.BigInteger(value).longValueExact());
|
||||
var deadline = java.time.Instant.now().plus(delay);
|
||||
if (deadline.atOffset(java.time.ZoneOffset.UTC).getYear() > 9999) {
|
||||
throw new IllegalArgumentException("character-swap-cooldown-seconds exceeds the persisted UTC timestamp range");
|
||||
}
|
||||
return delay;
|
||||
} catch (ArithmeticException | java.time.DateTimeException invalid) {
|
||||
throw new IllegalArgumentException("character-swap-cooldown-seconds exceeds the supported duration range", invalid);
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyPlayer(Object generation, EquipmentSessions.Notice notice) {
|
||||
Runnable delivery = () -> {
|
||||
if (lifetime != generation) return;
|
||||
var player = getServer().getPlayer(notice.player());
|
||||
if (player == null || !player.isOnline()) return;
|
||||
String message = switch (notice.code()) {
|
||||
case "NO_SPACE" -> "Equipment entry refused: free one slot in your main inventory for the Fantasy Storage Box.";
|
||||
case "INELIGIBLE_EQUIPMENT" -> "Equipment entry refused: a hotbar or armor item cannot fit in a vanilla shulker box. Move it before retrying.";
|
||||
default -> notice.message();
|
||||
};
|
||||
player.sendMessage(message);
|
||||
if (notice.code().equals("DEFEAT")) games.dmg.fantasystick.session.SessionVisuals.burst(player, org.bukkit.Color.RED, 12);
|
||||
else player.spawnParticle(org.bukkit.Particle.ANGRY_VILLAGER, player.getLocation().add(0, 1, 0), 8, 0.3, 0.4, 0.3, 0);
|
||||
};
|
||||
if (lifetime != generation) return;
|
||||
if (getServer().isPrimaryThread()) delivery.run();
|
||||
else getServer().getScheduler().runTask(this, delivery);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package games.dmg.fantasystick.book;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.kyori.adventure.text.Component;
|
||||
|
||||
/** Plain native book pages, conservatively bounded for the vanilla font (no styled/bold text). */
|
||||
public final class BookPagination {
|
||||
private BookPagination() { }
|
||||
|
||||
public static List<Component> pages(String text) {
|
||||
var lines = new ArrayList<String>();
|
||||
var line = new StringBuilder();
|
||||
int width = 0;
|
||||
for (int offset = 0; offset < text.length();) {
|
||||
int codePoint = text.codePointAt(offset);
|
||||
offset += Character.charCount(codePoint);
|
||||
if (codePoint == '\n') {
|
||||
lines.add(line.toString()); line.setLength(0); width = 0;
|
||||
continue;
|
||||
}
|
||||
// ASCII is at most six pixels; vanilla's Unicode fallback is at most nine.
|
||||
// Leave six pixels of horizontal slack and one line of vertical slack.
|
||||
int advance = codePoint < 128 ? 6 : 9;
|
||||
if (width + advance > 108) {
|
||||
lines.add(line.toString()); line.setLength(0); width = 0;
|
||||
}
|
||||
line.appendCodePoint(codePoint); width += advance;
|
||||
}
|
||||
lines.add(line.toString());
|
||||
var pages = new ArrayList<Component>();
|
||||
for (int start = 0; start < lines.size(); start += 13) {
|
||||
pages.add(Component.text(String.join("\n", lines.subList(start, Math.min(start + 13, lines.size())))));
|
||||
}
|
||||
return List.copyOf(pages);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package games.dmg.fantasystick.book;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.progression.ProgressionRules;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import games.dmg.fantasystick.session.ControlInput;
|
||||
import games.dmg.fantasystick.session.NativeHealthLimit;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.BookMeta;
|
||||
|
||||
/** Authoritative inspection and validated party controls; character mutation actions remain unfinished. */
|
||||
public final class CharacterBookController implements Consumer<ControlInput>, AutoCloseable, org.bukkit.event.Listener {
|
||||
public record Failure(UUID player, UUID character, Throwable cause) { }
|
||||
private final CharacterStorage characters;
|
||||
private final ProgressionRules rules;
|
||||
private final PartyBookControls partyControls;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<Failure> failures;
|
||||
private final Map<UUID, Object> pending = new ConcurrentHashMap<>();
|
||||
private volatile boolean closed;
|
||||
private static final int VOLUME_SIZE = 80; // Leave room for navigation and the bounded party pages.
|
||||
private static final net.kyori.adventure.key.Key PAGES = net.kyori.adventure.key.Key.key("fantasystick", "character_pages");
|
||||
private static final java.util.regex.Pattern PAGE_PAYLOAD = java.util.regex.Pattern.compile("\"([a-f0-9-]{36}):([01])\"");
|
||||
private record View(String nonce, ControlInput input, int previous, int next) { }
|
||||
private final Map<UUID, View> views = new ConcurrentHashMap<>();
|
||||
|
||||
/** Scheduler must always defer to the server thread. Diagnostics must not access players or throw. */
|
||||
public CharacterBookController(CharacterStorage characters, ProgressionRules rules,
|
||||
Consumer<Runnable> nextTick, Consumer<Failure> failures, games.dmg.fantasystick.party.PartyRoster parties,
|
||||
org.bukkit.Server server, java.util.function.Function<UUID, Component> names) {
|
||||
this.characters = Objects.requireNonNull(characters);
|
||||
this.rules = Objects.requireNonNull(rules);
|
||||
this.nextTick = Objects.requireNonNull(nextTick);
|
||||
this.failures = Objects.requireNonNull(failures);
|
||||
this.partyControls = new PartyBookControls(parties, server, names, this::accept, this::report);
|
||||
}
|
||||
|
||||
@Override public void accept(ControlInput input) { load(input, 0); }
|
||||
|
||||
private void load(ControlInput input, int offset) {
|
||||
if (closed || input.kind() != ControlInput.Kind.BOOK || input.gesture() != ControlInput.Gesture.USE
|
||||
|| !input.stillCurrent()) return;
|
||||
var owner = input.session().player();
|
||||
partyControls.forget(owner);
|
||||
views.remove(owner);
|
||||
Object ticket = new Object();
|
||||
pending.put(owner, ticket);
|
||||
characters.find(input.session().character()).whenComplete((record, failure) -> {
|
||||
if (closed || pending.get(owner) != ticket) return;
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (closed || !pending.remove(owner, ticket) || !input.stillCurrent()) return;
|
||||
if (failure != null) {
|
||||
report(input, failure);
|
||||
input.player().sendMessage("Character book could not be loaded; no character state was changed.");
|
||||
return;
|
||||
}
|
||||
if (record.isEmpty() || record.orElseThrow().dead()) {
|
||||
input.player().sendMessage("This character is no longer available.");
|
||||
return;
|
||||
}
|
||||
try { input.player().openBook(render(record.orElseThrow(), input, offset)); }
|
||||
catch (RuntimeException error) { partyControls.forget(owner); views.remove(owner); report(input, error); }
|
||||
});
|
||||
} catch (RuntimeException rejected) {
|
||||
pending.remove(owner, ticket);
|
||||
report(input, rejected);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ItemStack render(CharacterRecord record, ControlInput input, int offset) {
|
||||
var first = new StringBuilder(record.name()).append("\n\n");
|
||||
for (var stat : Stat.values()) first.append(stat).append(": ").append(record.stats().get(stat)).append('\n');
|
||||
var maximum = record.maximumHealth().min(NativeHealthLimit.read());
|
||||
String xp = record.level() >= rules.maximumLevel() ? "MAX"
|
||||
: record.experience().remainder(rules.xpPerLevel()) + "/" + rules.xpPerLevel();
|
||||
String learned = record.learned().isEmpty() ? "none" : String.join(", ", record.learned().stream().sorted().toList());
|
||||
String second = "Level: " + record.level() + "\nXP: " + xp + "\nUnspent points: " + record.unspentPoints()
|
||||
+ "\nHealth: " + java.math.BigDecimal.valueOf(input.player().getHealth()).min(maximum).stripTrailingZeros().toPlainString()
|
||||
+ "/" + maximum.stripTrailingZeros().toPlainString()
|
||||
+ "\n\nAbilities: " + learned;
|
||||
var item = new ItemStack(Material.WRITTEN_BOOK);
|
||||
var meta = (BookMeta) item.getItemMeta();
|
||||
meta.setTitle("Character");
|
||||
meta.setAuthor("Fantasy Stick");
|
||||
var all = BookPagination.pages(first + "\n" + second);
|
||||
int start = Math.min(offset, (all.size() - 1) / VOLUME_SIZE * VOLUME_SIZE);
|
||||
int end = Math.min(start + VOLUME_SIZE, all.size());
|
||||
var pages = new java.util.ArrayList<Component>(all.subList(start, end));
|
||||
if (all.size() > VOLUME_SIZE) {
|
||||
var view = new View(UUID.randomUUID().toString(), input, start > 0 ? start - VOLUME_SIZE : -1,
|
||||
end < all.size() ? end : -1);
|
||||
views.put(input.session().player(), view);
|
||||
Component navigation = Component.text("Character pages\n\n" + (start + 1) + "–" + end + "/" + all.size());
|
||||
if (view.previous() >= 0) navigation = navigation.append(Component.newline()).append(pageButton("Previous pages", view, 0));
|
||||
if (view.next() >= 0) navigation = navigation.append(Component.newline()).append(pageButton("Next pages", view, 1));
|
||||
pages.add(navigation);
|
||||
}
|
||||
pages.addAll(partyControls.pages(input));
|
||||
meta.pages(pages);
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
private static Component pageButton(String label, View view, int direction) {
|
||||
return Component.text("[" + label + "]", net.kyori.adventure.text.format.NamedTextColor.DARK_BLUE)
|
||||
.clickEvent(net.kyori.adventure.text.event.ClickEvent.custom(PAGES,
|
||||
net.kyori.adventure.nbt.api.BinaryTagHolder.binaryTagHolder("\"" + view.nonce() + ":" + direction + "\"")));
|
||||
}
|
||||
|
||||
@org.bukkit.event.EventHandler
|
||||
public void pageAction(io.papermc.paper.event.player.PlayerCustomClickEvent event) {
|
||||
if (closed || !PAGES.equals(event.getIdentifier())
|
||||
|| !(event.getCommonConnection() instanceof io.papermc.paper.connection.PlayerGameConnection connection)) return;
|
||||
var player = connection.getPlayer();
|
||||
var view = views.get(player.getUniqueId());
|
||||
if (view == null || view.input().player() != player || event.getTag() == null) return;
|
||||
String raw = event.getTag().string();
|
||||
if (raw.length() > 64) return;
|
||||
var match = PAGE_PAYLOAD.matcher(raw);
|
||||
if (!match.matches() || !view.nonce().equals(match.group(1))) return;
|
||||
int offset = match.group(2).equals("0") ? view.previous() : view.next();
|
||||
if (offset < 0 || !views.remove(player.getUniqueId(), view) || !view.input().stillCurrent()) return;
|
||||
// Reread authoritative data, rather than retaining a stale giant character snapshot.
|
||||
load(view.input(), offset);
|
||||
}
|
||||
|
||||
private void report(ControlInput input, Throwable failure) {
|
||||
try { failures.accept(new Failure(input.session().player(), input.session().character(), failure)); }
|
||||
catch (RuntimeException ignored) { /* A diagnostic failure must not replay a book request. */ }
|
||||
}
|
||||
|
||||
@org.bukkit.event.EventHandler
|
||||
public void partyAction(io.papermc.paper.event.player.PlayerCustomClickEvent event) { partyControls.click(event); }
|
||||
|
||||
@org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.MONITOR)
|
||||
public void quit(org.bukkit.event.player.PlayerQuitEvent event) {
|
||||
var owner = event.getPlayer().getUniqueId();
|
||||
pending.remove(owner);
|
||||
views.remove(owner);
|
||||
partyControls.forget(owner);
|
||||
}
|
||||
|
||||
@Override public void close() { closed = true; pending.clear(); views.clear(); partyControls.close(); }
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package games.dmg.fantasystick.book;
|
||||
|
||||
import games.dmg.fantasystick.party.PartyRoster;
|
||||
import games.dmg.fantasystick.session.ControlInput;
|
||||
import io.papermc.paper.connection.PlayerGameConnection;
|
||||
import io.papermc.paper.event.player.PlayerCustomClickEvent;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.nbt.api.BinaryTagHolder;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.BookMeta;
|
||||
|
||||
/** One single-use view per player; client payloads select server-owned actions, never arbitrary UUIDs/commands. */
|
||||
public final class PartyBookControls implements AutoCloseable {
|
||||
private static final Key ACTION = Key.key("fantasystick", "party_book");
|
||||
private static final Pattern PAYLOAD = Pattern.compile("\"([a-f0-9-]{36}):([0-9]{1,3})\"");
|
||||
private static final int PAGE_SIZE = 8;
|
||||
private enum Menu { ROOT, PLAYERS, INVITATIONS }
|
||||
private record View(String nonce, ControlInput input, List<Runnable> actions) {
|
||||
private View { actions = List.copyOf(actions); }
|
||||
}
|
||||
private final Map<UUID, View> views = new HashMap<>();
|
||||
private final PartyRoster parties;
|
||||
private final Server server;
|
||||
private final Function<UUID, Component> names;
|
||||
private final Consumer<ControlInput> refresh;
|
||||
private final BiConsumer<ControlInput, Throwable> failures;
|
||||
private boolean closed;
|
||||
|
||||
public PartyBookControls(PartyRoster parties, Server server, Function<UUID, Component> names,
|
||||
Consumer<ControlInput> refresh, BiConsumer<ControlInput, Throwable> failures) {
|
||||
this.parties = Objects.requireNonNull(parties);
|
||||
this.server = Objects.requireNonNull(server);
|
||||
this.names = Objects.requireNonNull(names);
|
||||
this.refresh = Objects.requireNonNull(refresh);
|
||||
this.failures = Objects.requireNonNull(failures);
|
||||
}
|
||||
|
||||
public List<Component> pages(ControlInput input) { return render(input, Menu.ROOT, 0); }
|
||||
|
||||
private List<Component> render(ControlInput input, Menu menu, int offset) {
|
||||
if (closed || !input.stillCurrent()) return List.of();
|
||||
var build = new Pages(input);
|
||||
var owner = input.session().player();
|
||||
var party = parties.partyOf(owner);
|
||||
if (menu == Menu.PLAYERS && (party.isEmpty() || !party.orElseThrow().leader().equals(owner))) menu = Menu.ROOT;
|
||||
if (menu == Menu.ROOT) {
|
||||
Component summary = Component.text("Party\n\n");
|
||||
if (party.isEmpty()) {
|
||||
summary = summary.append(build.button("Create party", () -> mutate(input, () -> parties.create(owner).isPresent())))
|
||||
.append(Component.newline()).append(build.button("Invitations", () -> show(input, Menu.INVITATIONS, 0)));
|
||||
build.pages.add(summary);
|
||||
} else {
|
||||
var group = party.orElseThrow();
|
||||
boolean leader = group.leader().equals(owner);
|
||||
summary = summary.append(Component.text(group.members().size() + "/6 members\n\n"))
|
||||
.append(build.button("Leave party", () -> mutate(input, () -> parties.leave(owner, group.id()))));
|
||||
if (leader) {
|
||||
summary = summary.append(Component.newline())
|
||||
.append(build.button("Disband party", () -> mutate(input, () -> parties.disband(owner, group.id()))));
|
||||
if (group.members().size() < 6) summary = summary.append(Component.newline())
|
||||
.append(build.button("Invite players", () -> show(input, Menu.PLAYERS, 0)));
|
||||
}
|
||||
build.pages.add(summary);
|
||||
for (var member : group.members()) {
|
||||
Component row = Component.text(member.equals(group.leader()) ? "Leader\n\n" : "Member\n\n").append(names.apply(member));
|
||||
if (leader && !member.equals(owner)) row = row.append(Component.text("\n\n"))
|
||||
.append(build.button("Kick", () -> mutate(input, () -> parties.kick(owner, group.id(), member))));
|
||||
build.pages.add(row);
|
||||
}
|
||||
}
|
||||
} else if (menu == Menu.PLAYERS) {
|
||||
var group = party.orElseThrow();
|
||||
var candidates = server.getOnlinePlayers().stream().filter(player -> player.isOnline())
|
||||
.map(player -> player.getUniqueId()).filter(id -> parties.partyOf(id).isEmpty())
|
||||
.sorted(Comparator.comparing(UUID::toString)).toList();
|
||||
int start = start(offset, candidates.size());
|
||||
build.navigation("Invite players", Menu.PLAYERS, start, candidates.size());
|
||||
for (int i = start; i < Math.min(candidates.size(), start + PAGE_SIZE); i++) {
|
||||
UUID target = candidates.get(i);
|
||||
build.pages.add(Component.text("Invite\n\n").append(names.apply(target)).append(Component.text("\n\n"))
|
||||
.append(build.button("Invite", () -> mutate(input, () -> {
|
||||
boolean invited = parties.invite(owner, group.id(), target).isPresent();
|
||||
if (invited) {
|
||||
var recipient = server.getPlayer(target);
|
||||
if (recipient != null && recipient.isOnline()) recipient.sendMessage(
|
||||
"Party invitation received. Open your character book to accept within 60 seconds.");
|
||||
}
|
||||
return invited;
|
||||
}))));
|
||||
}
|
||||
} else {
|
||||
var invitations = parties.invitationsFor(owner);
|
||||
int start = start(offset, invitations.size());
|
||||
build.navigation("Invitations", Menu.INVITATIONS, start, invitations.size());
|
||||
for (int i = start; i < Math.min(invitations.size(), start + PAGE_SIZE); i++) {
|
||||
var invitation = invitations.get(i);
|
||||
build.pages.add(Component.text("Invitation from\n\n").append(names.apply(invitation.leader()))
|
||||
.append(Component.text("\n\n")).append(build.button("Accept",
|
||||
() -> mutate(input, () -> parties.accept(owner, invitation.id())))));
|
||||
}
|
||||
}
|
||||
views.put(owner, new View(build.nonce, input, build.actions));
|
||||
return List.copyOf(build.pages);
|
||||
}
|
||||
|
||||
private static int start(int requested, int size) {
|
||||
return Math.min(Math.max(0, requested), Math.max(0, (size - 1) / PAGE_SIZE * PAGE_SIZE));
|
||||
}
|
||||
|
||||
private final class Pages {
|
||||
final ControlInput input;
|
||||
final String nonce = UUID.randomUUID().toString();
|
||||
final List<Component> pages = new ArrayList<>();
|
||||
final List<Runnable> actions = new ArrayList<>();
|
||||
Pages(ControlInput input) { this.input = input; }
|
||||
Component button(String label, Runnable action) {
|
||||
int index = actions.size();
|
||||
actions.add(action);
|
||||
return Component.text("[" + label + "]", NamedTextColor.DARK_BLUE).clickEvent(ClickEvent.custom(ACTION,
|
||||
BinaryTagHolder.binaryTagHolder("\"" + nonce + ":" + index + "\"")));
|
||||
}
|
||||
void navigation(String title, Menu menu, int start, int count) {
|
||||
Component page = Component.text(title + "\n\n" + (count == 0 ? "None available\n\n" : ""))
|
||||
.append(button("Character book", () -> refresh.accept(input)));
|
||||
if (start > 0) page = page.append(Component.newline()).append(button("Previous", () -> show(input, menu, start - PAGE_SIZE)));
|
||||
if (start + PAGE_SIZE < count) page = page.append(Component.newline()).append(button("Next", () -> show(input, menu, start + PAGE_SIZE)));
|
||||
pages.add(page);
|
||||
}
|
||||
}
|
||||
|
||||
private void show(ControlInput input, Menu menu, int offset) {
|
||||
var item = new ItemStack(Material.WRITTEN_BOOK);
|
||||
var meta = (BookMeta) item.getItemMeta();
|
||||
meta.setTitle("Party"); meta.setAuthor("Fantasy Stick");
|
||||
meta.pages(render(input, menu, offset));
|
||||
item.setItemMeta(meta);
|
||||
input.player().openBook(item);
|
||||
}
|
||||
|
||||
public void click(PlayerCustomClickEvent event) {
|
||||
if (closed || !ACTION.equals(event.getIdentifier()) || !(event.getCommonConnection() instanceof PlayerGameConnection connection)) return;
|
||||
var player = connection.getPlayer();
|
||||
var view = views.get(player.getUniqueId());
|
||||
if (view == null || view.input().player() != player) return;
|
||||
var tag = event.getTag();
|
||||
if (tag == null) return;
|
||||
String raw = tag.string();
|
||||
if (raw.length() > 64) return;
|
||||
var match = PAYLOAD.matcher(raw);
|
||||
if (!match.matches() || !view.nonce().equals(match.group(1))) return;
|
||||
int index = Integer.parseInt(match.group(2));
|
||||
if (index >= view.actions().size()) return;
|
||||
views.remove(player.getUniqueId());
|
||||
if (!view.input().stillCurrent()) return;
|
||||
try { view.actions().get(index).run(); }
|
||||
catch (RuntimeException failure) { forget(player.getUniqueId()); failures.accept(view.input(), failure); }
|
||||
}
|
||||
|
||||
private void mutate(ControlInput input, BooleanSupplier operation) {
|
||||
if (!operation.getAsBoolean()) input.player().sendMessage("Party action unavailable: membership, authority or invitation changed.");
|
||||
refresh.accept(input);
|
||||
}
|
||||
public void forget(UUID player) { views.remove(player); }
|
||||
@Override public void close() { closed = true; views.clear(); }
|
||||
}
|
||||
@@ -16,12 +16,20 @@ public final class CharacterAnvilNames implements Listener {
|
||||
private final CharacterStorage storage;
|
||||
private final Consumer<Failure> failures;
|
||||
private final org.bukkit.inventory.ItemFactory items;
|
||||
private final Consumer<games.dmg.fantasystick.persistence.CharacterRecord> acknowledged;
|
||||
|
||||
/** Diagnostics may run on the persistence worker and must not access native player state. */
|
||||
public CharacterAnvilNames(CharacterStorage storage, Consumer<Failure> failures, org.bukkit.inventory.ItemFactory items) {
|
||||
this(storage, failures, items, ignored -> { });
|
||||
}
|
||||
|
||||
/** Acknowledgments run after file commit, possibly on the worker; never access Bukkit in that callback. */
|
||||
public CharacterAnvilNames(CharacterStorage storage, Consumer<Failure> failures, org.bukkit.inventory.ItemFactory items,
|
||||
Consumer<games.dmg.fantasystick.persistence.CharacterRecord> acknowledged) {
|
||||
this.items = java.util.Objects.requireNonNull(items);
|
||||
this.storage = java.util.Objects.requireNonNull(storage);
|
||||
this.failures = java.util.Objects.requireNonNull(failures);
|
||||
this.acknowledged = java.util.Objects.requireNonNull(acknowledged);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
@@ -37,7 +45,9 @@ public final class CharacterAnvilNames implements Listener {
|
||||
var player = event.getPlayer().getUniqueId();
|
||||
var character = id.orElseThrow();
|
||||
storage.renameCharacter(character, name).whenComplete((renamed, failure) -> {
|
||||
if (failure != null || renamed.isEmpty()) failures.accept(new Failure(player, character, failure));
|
||||
if (failure != null || renamed.isEmpty()) { failures.accept(new Failure(player, character, failure)); return; }
|
||||
try { acknowledged.accept(renamed.orElseThrow()); }
|
||||
catch (RuntimeException | LinkageError error) { failures.accept(new Failure(player, character, error)); }
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/**
|
||||
* World boundary for saved sheets; no inventory-source drop or cancellation return-to-inventory fallback.
|
||||
* Invoke on the server thread only after the batch claim, since listeners receive a playable identity.
|
||||
* Invoke on the server thread with an existing reference, or after the craft batch claim,
|
||||
* since listeners receive a playable identity.
|
||||
* Native spawnAt supplies ItemSpawnEvent; do not dispatch that event separately or infer success from a wrapper.
|
||||
*/
|
||||
public final class PlayerSheetDrops implements ManualDropDelivery.DropTarget {
|
||||
@@ -30,6 +31,19 @@ public final class PlayerSheetDrops implements ManualDropDelivery.DropTarget {
|
||||
if (sheet == null || sheet.getAmount() != 1 || new CharacterSheets().identify(sheet).isEmpty()) {
|
||||
throw new IllegalArgumentException("Exactly one identified character sheet is required");
|
||||
}
|
||||
return dropReferences(sheet, current);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop an existing stack of references to the same character, not a batch of newly crafted characters.
|
||||
* COMPLETE confirms this quantity in one entity; the caller must recheck context before source debit.
|
||||
* No character allocation, inventory-source fallback or retry of uncertain exposure is performed.
|
||||
*/
|
||||
public ManualDropDelivery.Status dropReferences(ItemStack sheet, BooleanSupplier current) {
|
||||
if (sheet == null || sheet.getAmount() <= 0 || sheet.getAmount() > sheet.getMaxStackSize()
|
||||
|| new CharacterSheets().identify(sheet).isEmpty()) {
|
||||
throw new IllegalArgumentException("A positive, native-sized stack of identified character references is required");
|
||||
}
|
||||
if (!current.getAsBoolean()) return ManualDropDelivery.Status.STALE;
|
||||
var location = player.getEyeLocation().subtract(0, .3, 0);
|
||||
var item = location.getWorld().createEntity(location, Item.class);
|
||||
|
||||
@@ -16,7 +16,8 @@ public final class CharacterSheets {
|
||||
public static final NamespacedKey RECIPE = new NamespacedKey("fantasystick", "character_sheet");
|
||||
private static final NamespacedKey VERSION = new NamespacedKey("fantasystick", "sheet_version");
|
||||
private static final NamespacedKey CHARACTER = new NamespacedKey("fantasystick", "character_id");
|
||||
private static final String INSTRUCTION = "Character sheet: place in off hand to enter fantasy world.";
|
||||
private static final List<Component> INSTRUCTION = List.of(Component.text("Character sheet:"),
|
||||
Component.text("Place in off hand"), Component.text("to enter fantasy world."));
|
||||
|
||||
public ItemStack create(CharacterRecord character) {
|
||||
if (character.dead()) throw new IllegalArgumentException("Dead characters require authoritative revival before sheet creation");
|
||||
@@ -40,7 +41,7 @@ public final class CharacterSheets {
|
||||
var item = new ItemStack(Material.PAPER);
|
||||
var meta = item.getItemMeta();
|
||||
meta.displayName(Component.text(name));
|
||||
meta.lore(List.of(Component.text(INSTRUCTION)));
|
||||
meta.lore(INSTRUCTION);
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -22,21 +22,39 @@ public final class EquipmentStorage {
|
||||
private static final NamespacedKey SESSION = key("storage_session_id");
|
||||
private static final NamespacedKey SLOTS = key("storage_slots");
|
||||
|
||||
private record PackPlan(PackResult result, ItemStack box, int destination) { }
|
||||
|
||||
/** Full read-only preflight; no contents are removed and no box is installed. */
|
||||
public java.util.Optional<PackResult> refusal(PlayerInventory inventory, UUID owner, UUID session) {
|
||||
var plan = inspect(inventory, owner, session);
|
||||
return plan.result() == PackResult.PACKED ? java.util.Optional.empty() : java.util.Optional.of(plan.result());
|
||||
}
|
||||
|
||||
public PackResult pack(PlayerInventory inventory, UUID owner, UUID session) {
|
||||
var plan = inspect(inventory, owner, session);
|
||||
if (plan.result() != PackResult.PACKED) return plan.result();
|
||||
// Install the genuine, fully constructed recovery copy before removing any original.
|
||||
// Setter exceptions may retain duplicates; the caller must report uncertainty, not roll back.
|
||||
inventory.setItem(plan.destination(), plan.box());
|
||||
for (int slot : EQUIPMENT_SLOTS) inventory.setItem(slot, null);
|
||||
return PackResult.PACKED;
|
||||
}
|
||||
|
||||
private PackPlan inspect(PlayerInventory inventory, UUID owner, UUID session) {
|
||||
Objects.requireNonNull(owner);
|
||||
Objects.requireNonNull(session);
|
||||
for (int slot = 9; slot < 36; slot++) {
|
||||
if (matches(inventory.getItem(slot), owner, session)) return PackResult.ALREADY_PACKED;
|
||||
if (matches(inventory.getItem(slot), owner, session)) return new PackPlan(PackResult.ALREADY_PACKED, null, -1);
|
||||
}
|
||||
for (int slot : EQUIPMENT_SLOTS) {
|
||||
var item = inventory.getItem(slot);
|
||||
if (!empty(item) && item.getType().name().endsWith("SHULKER_BOX")) return PackResult.INELIGIBLE_EQUIPMENT;
|
||||
if (!empty(item) && item.getType().name().endsWith("SHULKER_BOX")) return new PackPlan(PackResult.INELIGIBLE_EQUIPMENT, null, -1);
|
||||
}
|
||||
int available = -1;
|
||||
for (int slot = 9; slot < 36; slot++) {
|
||||
if (empty(inventory.getItem(slot))) { available = slot; break; }
|
||||
}
|
||||
if (available == -1) return PackResult.NO_SPACE;
|
||||
if (available == -1) return new PackPlan(PackResult.NO_SPACE, null, -1);
|
||||
var item = new ItemStack(Material.SHULKER_BOX);
|
||||
var meta = (BlockStateMeta) item.getItemMeta();
|
||||
var box = (ShulkerBox) meta.getBlockState();
|
||||
@@ -44,7 +62,7 @@ public final class EquipmentStorage {
|
||||
for (int i = 0; i < EQUIPMENT_SLOTS.length; i++) {
|
||||
var equipment = inventory.getItem(EQUIPMENT_SLOTS[i]);
|
||||
if (!empty(equipment) && equipment.getAmount() > Math.min(equipment.getMaxStackSize(), contents.getMaxStackSize())) {
|
||||
return PackResult.INELIGIBLE_EQUIPMENT;
|
||||
return new PackPlan(PackResult.INELIGIBLE_EQUIPMENT, null, -1);
|
||||
}
|
||||
contents.setItem(i, equipment);
|
||||
}
|
||||
@@ -56,26 +74,48 @@ public final class EquipmentStorage {
|
||||
data.set(SESSION, PersistentDataType.STRING, session.toString());
|
||||
data.set(SLOTS, PersistentDataType.INTEGER_ARRAY, EQUIPMENT_SLOTS.clone());
|
||||
item.setItemMeta(meta);
|
||||
for (int slot : EQUIPMENT_SLOTS) inventory.setItem(slot, null);
|
||||
inventory.setItem(available, item);
|
||||
return PackResult.PACKED;
|
||||
return new PackPlan(PackResult.PACKED, item, available);
|
||||
}
|
||||
|
||||
public enum RestoreResult { RESTORED, NOT_FOUND, AMBIGUOUS, INVALID_BOX, OCCUPIED_SLOT }
|
||||
|
||||
/** Caller removes validated fantasy controls first. Unexpected slot occupants are never overwritten. */
|
||||
public RestoreResult restore(PlayerInventory inventory, UUID owner, UUID session) {
|
||||
return restore(inventory, owner, session, item -> false);
|
||||
}
|
||||
|
||||
/** Validates the entire restore before replacing only the current session's owned hotbar controls. */
|
||||
public RestoreResult restore(PlayerInventory inventory, UUID owner, UUID session,
|
||||
java.util.function.Predicate<ItemStack> ownedControl) {
|
||||
return restore(inventory, owner, session, ownedControl, null, ignored -> { });
|
||||
}
|
||||
|
||||
/** Cursor-aware restore; the setter is invoked only when the matching box is on the cursor. */
|
||||
public RestoreResult restore(PlayerInventory inventory, UUID owner, UUID session,
|
||||
ItemStack cursor, java.util.function.Consumer<ItemStack> setCursor) {
|
||||
return restore(inventory, owner, session, item -> false, cursor, setCursor);
|
||||
}
|
||||
|
||||
/** All candidates and destinations are validated before any write; setter failures are uncertain. */
|
||||
public RestoreResult restore(PlayerInventory inventory, UUID owner, UUID session,
|
||||
java.util.function.Predicate<ItemStack> ownedControl,
|
||||
ItemStack cursor, java.util.function.Consumer<ItemStack> setCursor) {
|
||||
Objects.requireNonNull(inventory);
|
||||
Objects.requireNonNull(ownedControl);
|
||||
Objects.requireNonNull(setCursor);
|
||||
Objects.requireNonNull(owner);
|
||||
Objects.requireNonNull(session);
|
||||
int found = -1;
|
||||
for (int slot = 9; slot < 36; slot++) {
|
||||
if (matches(inventory.getItem(slot), owner, session)) {
|
||||
// 9..35 main, 40 offhand, 41 cursor (not an inventory index).
|
||||
for (int slot = 9; slot <= 41; slot++) {
|
||||
if (slot >= 36 && slot < 40) continue;
|
||||
if (matches(slot == 41 ? cursor : inventory.getItem(slot), owner, session)) {
|
||||
if (found != -1) return RestoreResult.AMBIGUOUS;
|
||||
found = slot;
|
||||
}
|
||||
}
|
||||
if (found == -1) return RestoreResult.NOT_FOUND;
|
||||
var item = inventory.getItem(found);
|
||||
var item = found == 41 ? cursor : inventory.getItem(found);
|
||||
if (item.getAmount() != 1 || !(item.getItemMeta() instanceof BlockStateMeta meta)
|
||||
|| !(meta.getBlockState() instanceof ShulkerBox box)) return RestoreResult.INVALID_BOX;
|
||||
var data = meta.getPersistentDataContainer();
|
||||
@@ -89,12 +129,15 @@ public final class EquipmentStorage {
|
||||
if (!empty(contents.getItem(slot))) return RestoreResult.INVALID_BOX;
|
||||
}
|
||||
for (int slot : EQUIPMENT_SLOTS) {
|
||||
if (slot != 39 && !empty(inventory.getItem(slot))) return RestoreResult.OCCUPIED_SLOT;
|
||||
if (slot == 39) continue;
|
||||
var current = inventory.getItem(slot);
|
||||
if (!empty(current) && !(slot < 9 && ownedControl.test(current.clone()))) return RestoreResult.OCCUPIED_SLOT;
|
||||
}
|
||||
var currentHead = inventory.getItem(39);
|
||||
var displacedHead = empty(currentHead) ? null : currentHead.clone();
|
||||
for (int i = 0; i < EQUIPMENT_SLOTS.length; i++) inventory.setItem(EQUIPMENT_SLOTS[i], contents.getItem(i));
|
||||
inventory.setItem(found, displacedHead);
|
||||
if (found == 41) setCursor.accept(displacedHead);
|
||||
else inventory.setItem(found, displacedHead);
|
||||
return RestoreResult.RESTORED;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package games.dmg.fantasystick.items;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/**
|
||||
* Detached, server-thread control presentation/identity, never session or casting authorization.
|
||||
* The caller must enforce session custody and suppress vanilla item uses; this class registers no events.
|
||||
*/
|
||||
public final class SessionControls {
|
||||
private static final NamespacedKey VERSION = key("control_version");
|
||||
private static final NamespacedKey OWNER = key("control_owner_id");
|
||||
private static final NamespacedKey SESSION = key("control_session_id");
|
||||
private static final NamespacedKey SLOT = key("control_slot");
|
||||
private static final NamespacedKey KIND = key("control_kind");
|
||||
private static final NamespacedKey ABILITY = key("control_ability_id");
|
||||
|
||||
/** Presentation catalogue only: no unlock requirements, effects or casting authorization. */
|
||||
private record Icon(Material material, String name) { }
|
||||
private static final Map<String, Icon> ABILITIES = Map.ofEntries(
|
||||
Map.entry("fireball", new Icon(Material.SNOWBALL, "Fireball")),
|
||||
Map.entry("great_sword", new Icon(Material.WOODEN_SWORD, "Great Sword")),
|
||||
Map.entry("frost_shard", new Icon(Material.PRISMARINE_SHARD, "Frost Shard")),
|
||||
Map.entry("longbow", new Icon(Material.BOW, "Longbow")),
|
||||
Map.entry("quickstep", new Icon(Material.RABBIT_FOOT, "Quickstep")),
|
||||
Map.entry("second_wind", new Icon(Material.GHAST_TEAR, "Second Wind")),
|
||||
Map.entry("stone_skin", new Icon(Material.BRICK, "Stone Skin")),
|
||||
Map.entry("shield_bash", new Icon(Material.SHIELD, "Shield Bash")),
|
||||
Map.entry("hex", new Icon(Material.SPIDER_EYE, "Hex")),
|
||||
Map.entry("inspire", new Icon(Material.AMETHYST_SHARD, "Inspire")),
|
||||
Map.entry("mending_light", new Icon(Material.GHAST_TEAR, "Mending Light")),
|
||||
Map.entry("purify", new Icon(Material.HONEY_BOTTLE, "Purify")),
|
||||
Map.entry("guardian_bond", new Icon(Material.IRON_CHESTPLATE, "Guardian Bond")),
|
||||
Map.entry("rallying_cry", new Icon(Material.GOAT_HORN, "Rallying Cry")),
|
||||
Map.entry("frost_nova", new Icon(Material.SNOWBALL, "Frost Nova")),
|
||||
Map.entry("chain_lightning", new Icon(Material.LIGHTNING_ROD, "Chain Lightning")),
|
||||
Map.entry("sanctuary", new Icon(Material.SEA_LANTERN, "Sanctuary")),
|
||||
Map.entry("war_banner", new Icon(Material.RED_BANNER, "War Banner")),
|
||||
Map.entry("meteor", new Icon(Material.FIRE_CHARGE, "Meteor")),
|
||||
Map.entry("revive", new Icon(Material.ECHO_SHARD, "Revive"))
|
||||
);
|
||||
|
||||
public record Identity(UUID owner, UUID session, int slot) { }
|
||||
|
||||
/**
|
||||
* Builds the entire detached hotbar before a caller may start packing equipment.
|
||||
* Slot zero is a plain book control, not the pending character-book UI.
|
||||
*/
|
||||
public ItemStack[] create(CharacterRecord character, UUID owner, UUID session) {
|
||||
Objects.requireNonNull(character);
|
||||
Objects.requireNonNull(owner);
|
||||
Objects.requireNonNull(session);
|
||||
var items = new ItemStack[9];
|
||||
for (int slot = 0; slot < items.length; slot++) {
|
||||
String ability = slot < 2 ? "" : character.loadout().get(slot - 2);
|
||||
Icon icon = slot == 0 ? new Icon(Material.BOOK, "Character book")
|
||||
: slot == 1 ? new Icon(Material.STICK, "Basic attack")
|
||||
: ability.isEmpty() ? new Icon(Material.GRAY_DYE, "No Ability")
|
||||
: ABILITIES.getOrDefault(ability, new Icon(Material.PAPER, "Unavailable ability: " + ability));
|
||||
var item = new ItemStack(icon.material());
|
||||
var meta = item.getItemMeta();
|
||||
meta.displayName(Component.text(icon.name()));
|
||||
meta.setMaxStackSize(1);
|
||||
var data = meta.getPersistentDataContainer();
|
||||
data.set(VERSION, PersistentDataType.INTEGER, 1);
|
||||
data.set(OWNER, PersistentDataType.STRING, owner.toString());
|
||||
data.set(SESSION, PersistentDataType.STRING, session.toString());
|
||||
data.set(SLOT, PersistentDataType.INTEGER, slot);
|
||||
data.set(KIND, PersistentDataType.STRING, slot == 0 ? "book" : slot == 1 ? "basic_attack"
|
||||
: ability.isEmpty() ? "empty" : ABILITIES.containsKey(ability) ? "ability" : "unavailable");
|
||||
if (!ability.isEmpty()) data.set(ABILITY, PersistentDataType.STRING, ability);
|
||||
item.setItemMeta(meta);
|
||||
items[slot] = item;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** Structural identity only, not proof of an active session or permission to cast. */
|
||||
public Optional<Identity> identify(ItemStack item) {
|
||||
if (item == null || item.getAmount() != 1 || !item.hasItemMeta()) return Optional.empty();
|
||||
var meta = item.getItemMeta();
|
||||
// The native codec can omit redundant overrides on naturally unstackable icons.
|
||||
if (item.getMaxStackSize() != 1) return Optional.empty();
|
||||
var data = meta.getPersistentDataContainer();
|
||||
if (!data.has(VERSION, PersistentDataType.INTEGER)
|
||||
|| !Integer.valueOf(1).equals(data.get(VERSION, PersistentDataType.INTEGER))
|
||||
|| !data.has(OWNER, PersistentDataType.STRING)
|
||||
|| !data.has(SESSION, PersistentDataType.STRING)
|
||||
|| !data.has(SLOT, PersistentDataType.INTEGER)
|
||||
|| !data.has(KIND, PersistentDataType.STRING)) return Optional.empty();
|
||||
int slot = data.get(SLOT, PersistentDataType.INTEGER);
|
||||
if (slot < 0 || slot > 8 || !validKind(item.getType(), slot, data)) return Optional.empty();
|
||||
try {
|
||||
return Optional.of(new Identity(canonicalUuid(data.get(OWNER, PersistentDataType.STRING)),
|
||||
canonicalUuid(data.get(SESSION, PersistentDataType.STRING)), slot));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** A structurally recognized selectable ability; still not session/cast authorization. */
|
||||
public Optional<String> ability(ItemStack item) {
|
||||
if (identify(item).isEmpty()) return Optional.empty();
|
||||
var data = item.getPersistentDataContainer();
|
||||
return "ability".equals(data.get(KIND, PersistentDataType.STRING))
|
||||
? Optional.of(data.get(ABILITY, PersistentDataType.STRING)) : Optional.empty();
|
||||
}
|
||||
|
||||
private static boolean validKind(Material material, int slot, PersistentDataContainer data) {
|
||||
String kind = data.get(KIND, PersistentDataType.STRING);
|
||||
if (slot == 0) return kind.equals("book") && material == Material.BOOK && !data.has(ABILITY);
|
||||
if (slot == 1) return kind.equals("basic_attack") && material == Material.STICK && !data.has(ABILITY);
|
||||
if (kind.equals("empty")) return material == Material.GRAY_DYE && !data.has(ABILITY);
|
||||
if (!data.has(ABILITY, PersistentDataType.STRING)) return false;
|
||||
String ability = data.get(ABILITY, PersistentDataType.STRING);
|
||||
if (ability.isBlank()) return false;
|
||||
Icon icon = ABILITIES.get(ability);
|
||||
return kind.equals("ability") ? icon != null && icon.material() == material
|
||||
: kind.equals("unavailable") && icon == null && material == Material.PAPER;
|
||||
}
|
||||
|
||||
private static UUID canonicalUuid(String value) {
|
||||
UUID parsed = UUID.fromString(value);
|
||||
if (!parsed.toString().equals(value)) throw new IllegalArgumentException("Noncanonical UUID");
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private static NamespacedKey key(String name) { return new NamespacedKey("fantasystick", name); }
|
||||
|
||||
public boolean owned(ItemStack item, UUID owner, UUID session) {
|
||||
return identify(item).filter(identity -> identity.owner().equals(owner)
|
||||
&& identity.session().equals(session)).isPresent();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package games.dmg.fantasystick.items;
|
||||
|
||||
import games.dmg.fantasystick.book.BookPagination;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import java.util.ArrayList;
|
||||
@@ -35,14 +36,26 @@ public final class TailBooks {
|
||||
meta.setGeneration(BookMeta.Generation.ORIGINAL);
|
||||
meta.displayName(Component.text(fullTitle));
|
||||
List<Component> pages = new ArrayList<>();
|
||||
pages.add(Component.text(fullTitle));
|
||||
pages.add(Component.text("Level: " + character.level()));
|
||||
pages.add(Component.text("XP: " + character.experience()));
|
||||
pages.add(Component.text("Unspent points: " + character.unspentPoints()));
|
||||
for (Stat stat : Stat.values()) pages.add(Component.text(stat + ": " + character.stats().get(stat)));
|
||||
pages.add(Component.text("Abilities: " + (character.learned().isEmpty() ? "None" : "")));
|
||||
character.learned().stream().sorted().forEach(ability -> pages.add(Component.text(ability)));
|
||||
pages.add(Component.text("Fell: " + character.diedAt()));
|
||||
var summary = new StringBuilder(fullTitle).append("\nLevel: ").append(character.level())
|
||||
.append("\nXP: ").append(character.experience()).append("\nUnspent points: ").append(character.unspentPoints());
|
||||
for (Stat stat : Stat.values()) summary.append('\n').append(stat).append(": ").append(character.stats().get(stat));
|
||||
pages.addAll(BookPagination.pages(summary.toString()));
|
||||
if (character.learned().isEmpty()) pages.addAll(BookPagination.pages("Abilities: None"));
|
||||
character.learned().stream().sorted().forEach(ability -> {
|
||||
var slots = new ArrayList<String>();
|
||||
for (int slot = 0; slot < character.loadout().size(); slot++) {
|
||||
if (character.loadout().get(slot).equals(ability)) slots.add(Integer.toString(slot + 1));
|
||||
}
|
||||
var section = new StringBuilder("Ability: ").append(ability)
|
||||
.append("\nSlots: ").append(slots.isEmpty() ? "none" : String.join(", ", slots));
|
||||
var deadline = character.cooldowns().get(ability);
|
||||
section.append(deadline == null ? "\nCooldown: none" : "\nCooldown until:\n" + deadline);
|
||||
pages.addAll(BookPagination.pages(section.toString()));
|
||||
});
|
||||
// Unlearned/unknown saved cooldowns remain readable without pretending they are learned abilities.
|
||||
character.cooldowns().keySet().stream().filter(id -> !character.learned().contains(id)).sorted().forEach(id ->
|
||||
pages.addAll(BookPagination.pages("Saved cooldown\n" + id + "\nUntil:\n" + character.cooldowns().get(id))));
|
||||
pages.addAll(BookPagination.pages("Fell:\n" + character.diedAt()));
|
||||
meta.pages(pages);
|
||||
var data = meta.getPersistentDataContainer();
|
||||
data.set(VERSION, PersistentDataType.INTEGER, 1);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package games.dmg.fantasystick.party;
|
||||
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.entity.Projectile;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/** Source identity travels with delayed native entities, never with a replacement sheet or shooter. */
|
||||
final class CombatSources {
|
||||
static final NamespacedKey ORIGIN = new NamespacedKey("fantasystick", "combat_origin_v1");
|
||||
record Origin(UUID player, UUID session, UUID character) {
|
||||
String encode() { return player + "/" + (session == null ? "-/-" : session + "/" + character); }
|
||||
static Origin decode(String value) {
|
||||
if (value == null || value.length() > 110) return null;
|
||||
var parts = value.split("/", -1);
|
||||
if (parts.length != 3) return null;
|
||||
try {
|
||||
var origin = new Origin(UUID.fromString(parts[0]), parts[1].equals("-") ? null : UUID.fromString(parts[1]),
|
||||
parts[2].equals("-") ? null : UUID.fromString(parts[2]));
|
||||
return (origin.session == null) == (origin.character == null) && value.equals(origin.encode()) ? origin : null;
|
||||
} catch (IllegalArgumentException malformed) { return null; }
|
||||
}
|
||||
}
|
||||
private final EquipmentSessions sessions;
|
||||
CombatSources(EquipmentSessions sessions) { this.sessions = Objects.requireNonNull(sessions); }
|
||||
Origin player(UUID player) {
|
||||
return sessions.active(player).map(active -> new Origin(player, active.session(), active.character()))
|
||||
.orElseGet(() -> new Origin(player, null, null));
|
||||
}
|
||||
boolean current(Origin origin) {
|
||||
return origin.equals(player(origin.player())) && (origin.session() == null
|
||||
|| sessions.current(new EquipmentSessions.Active(origin.player(), origin.session(), origin.character())));
|
||||
}
|
||||
Origin read(Entity entity) { return read(entity, 0); }
|
||||
private Origin read(Entity entity, int depth) {
|
||||
if (entity == null || depth >= 8) return null;
|
||||
if (entity instanceof Player player) return player(player.getUniqueId());
|
||||
var saved = Origin.decode(entity.getPersistentDataContainer().get(ORIGIN, PersistentDataType.STRING));
|
||||
if (saved != null) return saved;
|
||||
if (entity instanceof org.bukkit.entity.Tameable pet && pet.getOwnerUniqueId() != null) {
|
||||
return player(pet.getOwnerUniqueId()); // A pet's new attack, not its old taming session.
|
||||
}
|
||||
var owner = owner(entity, depth + 1);
|
||||
// No launch proof (e.g. predating plugin startup): never assign a current fantasy session.
|
||||
return owner == null ? null : new Origin(owner.player(), null, null);
|
||||
}
|
||||
private Origin owner(Entity entity, int depth) {
|
||||
if (entity instanceof Projectile projectile && projectile.getShooter() instanceof Entity shooter) return read(shooter, depth);
|
||||
if (entity instanceof org.bukkit.entity.Firework firework && firework.getSpawningEntity() != null) return player(firework.getSpawningEntity());
|
||||
if (entity instanceof org.bukkit.entity.TNTPrimed tnt) return read(tnt.getSource(), depth);
|
||||
if (entity instanceof org.bukkit.entity.EvokerFangs fangs) return read(fangs.getOwner(), depth);
|
||||
if (entity instanceof org.bukkit.entity.AreaEffectCloud cloud && cloud.getSource() instanceof Entity source) return read(source, depth);
|
||||
return null;
|
||||
}
|
||||
void launch(Entity entity) {
|
||||
if (entity.getPersistentDataContainer().has(ORIGIN)) return;
|
||||
store(entity, owner(entity, 0));
|
||||
}
|
||||
void store(Entity entity, Origin origin) {
|
||||
if (origin != null) entity.getPersistentDataContainer().set(ORIGIN, PersistentDataType.STRING, origin.encode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package games.dmg.fantasystick.party;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
/** Bounded provenance for native damage layers, not copied effects or character/XP state.
|
||||
* Native effects remain authoritative. Durations reconcile in native ticks (also across offline saves),
|
||||
* so a hidden effect regaining the foreground keeps its own source, not a covering effect's source.
|
||||
*/
|
||||
final class OngoingDamage {
|
||||
record Application(CombatSources.Origin source, CombatSources.Origin target) { }
|
||||
private record Layer(int amplifier, int duration, Application application) { }
|
||||
private static final List<DamageCause> CAUSES = List.of(DamageCause.POISON, DamageCause.WITHER, DamageCause.FIRE_TICK);
|
||||
private static NamespacedKey key(DamageCause cause) {
|
||||
return new NamespacedKey("fantasystick", "combat_dot_" + cause.name().toLowerCase(java.util.Locale.ROOT) + "_v1");
|
||||
}
|
||||
static DamageCause cause(PotionEffectType type) {
|
||||
if (type.equals(PotionEffectType.POISON)) return DamageCause.POISON;
|
||||
if (type.equals(PotionEffectType.WITHER)) return DamageCause.WITHER;
|
||||
return null;
|
||||
}
|
||||
static void clear(Player player, DamageCause cause) { player.getPersistentDataContainer().remove(key(cause)); }
|
||||
static void potion(Player player, PotionEffect old, PotionEffect incoming, boolean override, Application application) {
|
||||
var cause = cause(incoming.getType());
|
||||
var layers = old == null ? new ArrayList<Layer>() : reconcile(load(player, cause), old.getAmplifier(), old.getDuration());
|
||||
var next = new Layer(incoming.getAmplifier(), incoming.getDuration(), application);
|
||||
// Purpur also stores a longer weaker effect behind the active one when override=false.
|
||||
if (layers.isEmpty() || override || next.amplifier() < layers.getFirst().amplifier()
|
||||
&& longer(next.duration(), layers.getFirst().duration())) merge(layers, 0, next);
|
||||
save(player, cause, layers);
|
||||
}
|
||||
private static boolean longer(int a, int b) { return a == -1 ? b != -1 : b != -1 && a > b; }
|
||||
private static void merge(List<Layer> layers, int index, Layer next) {
|
||||
if (index == layers.size()) { layers.add(next); return; }
|
||||
var old = layers.get(index);
|
||||
if (next.amplifier() > old.amplifier()) {
|
||||
if (longer(old.duration(), next.duration())) layers.add(index, next);
|
||||
else layers.set(index, next);
|
||||
} else if (next.amplifier() == old.amplifier()) {
|
||||
if (longer(next.duration(), old.duration())) layers.set(index, next);
|
||||
} else if (longer(next.duration(), old.duration())) merge(layers, index + 1, next);
|
||||
}
|
||||
static void fire(Player player, int duration, Application application) {
|
||||
save(player, DamageCause.FIRE_TICK, List.of(new Layer(0, duration, application)));
|
||||
}
|
||||
static Application read(Player player, DamageCause cause) {
|
||||
if (!CAUSES.contains(cause) || !player.getPersistentDataContainer().has(key(cause))) return null;
|
||||
List<Layer> layers = load(player, cause);
|
||||
if (cause == DamageCause.FIRE_TICK) {
|
||||
int fire = player.getFireTicks();
|
||||
layers = fire > 0 && !layers.isEmpty() && fire <= layers.getFirst().duration()
|
||||
? List.of(new Layer(0, fire, layers.getFirst().application())) : List.of();
|
||||
} else {
|
||||
var effect = player.getPotionEffect(cause == DamageCause.POISON ? PotionEffectType.POISON : PotionEffectType.WITHER);
|
||||
layers = effect == null ? List.of() : reconcile(layers, effect.getAmplifier(), effect.getDuration());
|
||||
}
|
||||
save(player, cause, layers);
|
||||
return layers.isEmpty() ? null : layers.getFirst().application();
|
||||
}
|
||||
static void sweep(Player player) { for (var cause : CAUSES) read(player, cause); }
|
||||
|
||||
private static ArrayList<Layer> reconcile(List<Layer> saved, int amplifier, int duration) {
|
||||
var result = new ArrayList<Layer>();
|
||||
for (int i = 0; i < saved.size(); i++) {
|
||||
var layer = saved.get(i);
|
||||
if (layer.amplifier() != amplifier || longer(duration, layer.duration())) continue;
|
||||
int elapsed = layer.duration() == -1 ? 0 : layer.duration() - duration;
|
||||
for (int j = i; j < saved.size(); j++) {
|
||||
var remaining = saved.get(j);
|
||||
int ticks = remaining.duration() == -1 ? -1 : Math.max(0, remaining.duration() - elapsed);
|
||||
if (ticks != 0) result.add(new Layer(remaining.amplifier(), ticks, remaining.application()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// Unknown/out-of-band replacement never borrows old attribution or gains party immunity.
|
||||
if (duration != 0) result.add(new Layer(amplifier, duration, null));
|
||||
return result;
|
||||
}
|
||||
private static List<Layer> load(Player player, DamageCause cause) {
|
||||
String value = player.getPersistentDataContainer().get(key(cause), PersistentDataType.STRING);
|
||||
if (value == null || value.length() > 65536) return List.of();
|
||||
var result = new ArrayList<Layer>();
|
||||
try {
|
||||
for (var row : value.split("\n", -1)) {
|
||||
var cells = row.split(",", -1);
|
||||
if (cells.length != 4 || result.size() >= 256) return List.of();
|
||||
int amplifier = Integer.parseInt(cells[0]), duration = Integer.parseInt(cells[1]);
|
||||
if (amplifier < 0 || amplifier > 255 || duration < -1 || duration == 0
|
||||
|| !result.isEmpty() && amplifier >= result.getLast().amplifier()) return List.of();
|
||||
Application application = null;
|
||||
if (!cells[2].equals("-") || !cells[3].equals("-")) {
|
||||
var source = CombatSources.Origin.decode(cells[2]);
|
||||
var target = CombatSources.Origin.decode(cells[3]);
|
||||
if (source == null || target == null || !target.player().equals(player.getUniqueId())) return List.of();
|
||||
application = new Application(source, target);
|
||||
}
|
||||
result.add(new Layer(amplifier, duration, application));
|
||||
}
|
||||
} catch (IllegalArgumentException malformed) { return List.of(); }
|
||||
return result;
|
||||
}
|
||||
private static void save(Player player, DamageCause cause, List<Layer> layers) {
|
||||
if (layers.stream().noneMatch(layer -> layer.application() != null)) { clear(player, cause); return; }
|
||||
var value = new StringBuilder();
|
||||
for (var layer : layers) {
|
||||
if (!value.isEmpty()) value.append('\n');
|
||||
value.append(layer.amplifier()).append(',').append(layer.duration()).append(',');
|
||||
var application = layer.application();
|
||||
value.append(application == null ? "-,-" : application.source().encode() + "," + application.target().encode());
|
||||
}
|
||||
player.getPersistentDataContainer().set(key(cause), PersistentDataType.STRING, value.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package games.dmg.fantasystick.party;
|
||||
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
import org.bukkit.event.entity.EntitySpawnEvent;
|
||||
import org.bukkit.event.entity.LingeringPotionSplashEvent;
|
||||
|
||||
/** Server-thread native damage protection; never uncancels another protection's decision. */
|
||||
public final class PartyCombat implements Listener, AutoCloseable {
|
||||
private org.bukkit.scheduler.BukkitTask cleanup;
|
||||
private boolean closed;
|
||||
private final PartyRoster parties;
|
||||
private final CombatSources sources;
|
||||
|
||||
public PartyCombat(PartyRoster parties, EquipmentSessions sessions) {
|
||||
this.parties = Objects.requireNonNull(parties);
|
||||
this.sources = new CombatSources(sessions);
|
||||
}
|
||||
|
||||
public void install(org.bukkit.plugin.Plugin plugin) {
|
||||
cleanup = plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
|
||||
if (!closed) for (var player : plugin.getServer().getOnlinePlayers()) OngoingDamage.sweep(player);
|
||||
}, 1, 1);
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
closed = true;
|
||||
if (cleanup != null) cleanup.cancel();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void launch(EntitySpawnEvent event) { sources.launch(event.getEntity()); }
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void impact(org.bukkit.event.entity.ProjectileHitEvent event) {
|
||||
var origin = sources.read(event.getEntity());
|
||||
if (origin != null && (!sources.current(origin) || !(event.getEntity() instanceof org.bukkit.entity.ThrownPotion)
|
||||
&& event.getHitEntity() instanceof Player target && blocked(origin, target))) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void splash(org.bukkit.event.entity.PotionSplashEvent event) {
|
||||
// Native splash passes only its owner to addEffect, losing the projectile's session.
|
||||
// Revoke stale continuation here. Valid healing and unrelated recipients are untouched;
|
||||
// actual harmful applications and instantaneous damage have their own guards below.
|
||||
var origin = sources.read(event.getEntity());
|
||||
if (origin != null && !sources.current(origin)) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void staleLingering(LingeringPotionSplashEvent event) {
|
||||
var origin = sources.read(event.getEntity());
|
||||
if (origin != null && !sources.current(origin)) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void lingering(LingeringPotionSplashEvent event) {
|
||||
sources.store(event.getAreaEffectCloud(), sources.read(event.getEntity()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void damage(EntityDamageEvent event) {
|
||||
if (event.getEntity() instanceof Player target) {
|
||||
var ongoing = OngoingDamage.read(target, event.getCause());
|
||||
if (ongoing != null && (!sources.current(ongoing.target()) || blocked(ongoing.source(), target))) {
|
||||
event.setCancelled(true); return;
|
||||
}
|
||||
}
|
||||
var origin = sources.read(event.getDamageSource().getDirectEntity());
|
||||
if (origin == null && event instanceof EntityDamageByEntityEvent entity) origin = sources.read(entity.getDamager());
|
||||
if (origin == null) origin = sources.read(event.getDamageSource().getCausingEntity());
|
||||
if (origin != null && (!sources.current(origin)
|
||||
|| event.getEntity() instanceof Player target && blocked(origin, target))) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void potion(org.bukkit.event.entity.EntityPotionEffectEvent event) {
|
||||
if (!(event.getEntity() instanceof Player target) || event.getNewEffect() == null
|
||||
|| OngoingDamage.cause(event.getModifiedType()) == null) return;
|
||||
var origin = sources.read(event.getSource());
|
||||
if (origin != null && blocked(origin, target)) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void acceptedPotion(org.bukkit.event.entity.EntityPotionEffectEvent event) {
|
||||
if (!(event.getEntity() instanceof Player target)) return;
|
||||
var cause = OngoingDamage.cause(event.getModifiedType());
|
||||
if (cause == null) return;
|
||||
if (event.getNewEffect() == null) OngoingDamage.clear(target, cause);
|
||||
else {
|
||||
var origin = sources.read(event.getSource());
|
||||
OngoingDamage.potion(target, event.getOldEffect(), event.getNewEffect(), event.isOverride(), origin == null ? null
|
||||
: new OngoingDamage.Application(origin, sources.player(target.getUniqueId())));
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void combust(org.bukkit.event.entity.EntityCombustByEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player target)) return;
|
||||
var origin = sources.read(event.getCombuster());
|
||||
if (origin != null && blocked(origin, target)) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void acceptedCombust(org.bukkit.event.entity.EntityCombustEvent event) {
|
||||
if (!(event.getEntity() instanceof Player target)) return;
|
||||
var origin = event instanceof org.bukkit.event.entity.EntityCombustByEntityEvent entity
|
||||
? sources.read(entity.getCombuster()) : null;
|
||||
int duration = Math.max(target.getFireTicks(), (int) Math.ceil(event.getDuration() * 20));
|
||||
OngoingDamage.fire(target, duration, origin == null ? null
|
||||
: new OngoingDamage.Application(origin, sources.player(target.getUniqueId())));
|
||||
}
|
||||
|
||||
private boolean blocked(CombatSources.Origin origin, Player target) {
|
||||
var recipient = sources.player(target.getUniqueId());
|
||||
boolean fantasy = origin.session() != null;
|
||||
return !sources.current(origin) || fantasy != (recipient.session() != null) || fantasy
|
||||
&& !origin.player().equals(recipient.player())
|
||||
&& parties.partyOf(origin.player()).filter(group -> group.members().contains(recipient.player())).isPresent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package games.dmg.fantasystick.party;
|
||||
|
||||
import java.util.Objects;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
/** Quit is authoritative even before Bukkit's online flag changes. */
|
||||
public final class PartyEvents implements Listener {
|
||||
private final PartyRoster parties;
|
||||
public PartyEvents(PartyRoster parties) { this.parties = Objects.requireNonNull(parties); }
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void join(org.bukkit.event.player.PlayerJoinEvent event) { parties.arrive(event.getPlayer().getUniqueId()); }
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void quit(PlayerQuitEvent event) { parties.disconnect(event.getPlayer().getUniqueId()); }
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package games.dmg.fantasystick.party;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/** Server-thread-confined, player-owned parties. No state survives a plugin/server restart. */
|
||||
public final class PartyRoster implements AutoCloseable {
|
||||
public record Party(UUID id, UUID leader, List<UUID> members) {
|
||||
public Party { members = List.copyOf(members); }
|
||||
}
|
||||
public record Invitation(UUID id, UUID party, UUID leader, UUID invitee, Instant expires) { }
|
||||
private final Map<UUID, Party> membership = new HashMap<>();
|
||||
private final Map<UUID, Invitation> invitations = new HashMap<>();
|
||||
private final Set<UUID> departed = new HashSet<>();
|
||||
private boolean closed;
|
||||
private final Clock clock;
|
||||
private final Predicate<UUID> online;
|
||||
|
||||
public PartyRoster(Clock clock, Predicate<UUID> online) {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.online = Objects.requireNonNull(online);
|
||||
}
|
||||
public Optional<Party> create(UUID player) {
|
||||
if (closed || !connected(player) || membership.containsKey(player)) return Optional.empty();
|
||||
var party = new Party(UUID.randomUUID(), player, List.of(player));
|
||||
membership.put(player, party);
|
||||
return Optional.of(party);
|
||||
}
|
||||
public Optional<Party> partyOf(UUID player) { return Optional.ofNullable(membership.get(player)); }
|
||||
public List<Invitation> invitationsFor(UUID player) {
|
||||
expire();
|
||||
return invitations.values().stream().filter(i -> i.invitee().equals(player))
|
||||
.sorted(java.util.Comparator.comparing(Invitation::expires).thenComparing(Invitation::id)).toList();
|
||||
}
|
||||
public Optional<Invitation> invite(UUID leader, UUID party, UUID invitee) {
|
||||
expire();
|
||||
var group = managedBy(leader, party);
|
||||
if (group == null || group.members().size() >= 6 || !connected(invitee) || membership.containsKey(invitee)) return Optional.empty();
|
||||
var existing = invitations.values().stream().filter(i -> i.party().equals(party) && i.invitee().equals(invitee)).findFirst();
|
||||
if (existing.isPresent()) return existing;
|
||||
var invitation = new Invitation(UUID.randomUUID(), party, leader, invitee, clock.instant().plusSeconds(60));
|
||||
invitations.put(invitation.id(), invitation);
|
||||
return Optional.of(invitation);
|
||||
}
|
||||
public boolean accept(UUID player, UUID invitation) {
|
||||
expire();
|
||||
var offer = invitations.get(invitation);
|
||||
if (offer == null || !offer.invitee().equals(player) || !connected(player) || membership.containsKey(player)) return false;
|
||||
var group = membership.get(offer.leader());
|
||||
if (group == null || group.members().size() >= 6 || !group.id().equals(offer.party())) return false;
|
||||
var members = new ArrayList<>(group.members());
|
||||
members.add(player);
|
||||
var updated = new Party(group.id(), group.leader(), members);
|
||||
for (var member : members) membership.put(member, updated);
|
||||
invitations.values().removeIf(i -> i.invitee().equals(player));
|
||||
return true;
|
||||
}
|
||||
public boolean kick(UUID leader, UUID party, UUID member) {
|
||||
var group = managedBy(leader, party);
|
||||
if (group == null || !group.members().contains(member) || member.equals(leader)) return false;
|
||||
removeMember(group, member);
|
||||
return true;
|
||||
}
|
||||
public boolean disband(UUID leader, UUID party) {
|
||||
var group = managedBy(leader, party);
|
||||
if (group == null) return false;
|
||||
remove(group);
|
||||
return true;
|
||||
}
|
||||
private Party managedBy(UUID leader, UUID party) {
|
||||
var group = membership.get(leader);
|
||||
return group != null && group.id().equals(party) && group.leader().equals(leader) && connected(leader) ? group : null;
|
||||
}
|
||||
public boolean leave(UUID player, UUID party) {
|
||||
var group = membership.get(player);
|
||||
if (group == null || !group.id().equals(party) || !connected(player)) return false;
|
||||
if (group.leader().equals(player)) remove(group);
|
||||
else removeMember(group, player);
|
||||
return true;
|
||||
}
|
||||
private void removeMember(Party group, UUID player) {
|
||||
var remaining = group.members().stream().filter(member -> !member.equals(player)).toList();
|
||||
if (remaining.stream().noneMatch(this::connected)) { remove(group); return; }
|
||||
membership.remove(player);
|
||||
departed.remove(player);
|
||||
var updated = new Party(group.id(), group.leader(), remaining);
|
||||
for (var member : remaining) membership.put(member, updated);
|
||||
}
|
||||
public void arrive(UUID player) { departed.remove(player); }
|
||||
public void disconnect(UUID player) {
|
||||
var group = membership.get(player);
|
||||
if (group == null) return;
|
||||
departed.add(player);
|
||||
if (group.members().stream().noneMatch(this::connected)) remove(group);
|
||||
}
|
||||
private boolean connected(UUID player) { return !departed.contains(player) && online.test(player); }
|
||||
private void expire() {
|
||||
var now = clock.instant();
|
||||
invitations.values().removeIf(i -> !now.isBefore(i.expires()));
|
||||
}
|
||||
private void remove(Party group) {
|
||||
for (var member : group.members()) membership.remove(member);
|
||||
departed.removeAll(group.members());
|
||||
invitations.values().removeIf(i -> i.party().equals(group.id()));
|
||||
}
|
||||
@Override public void close() {
|
||||
closed = true;
|
||||
membership.clear();
|
||||
invitations.clear();
|
||||
departed.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/** Worker-owned config writes; publish a new-session policy only after durable file acknowledgment. */
|
||||
public final class AdventureSettings implements AutoCloseable {
|
||||
private static final int MAX_BYTES = 1_048_576;
|
||||
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
|
||||
private final Path directory;
|
||||
private final Replacement replacement;
|
||||
private final java.util.concurrent.ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
task -> new Thread(task, "fantasy-configuration-persistence"));
|
||||
private volatile boolean enabled;
|
||||
private boolean closed;
|
||||
private int pending;
|
||||
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
||||
|
||||
public AdventureSettings(Path directory, boolean initial) {
|
||||
this(directory, initial, (from, to) -> Files.move(from, to,
|
||||
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
|
||||
}
|
||||
|
||||
AdventureSettings(Path directory, boolean initial, Replacement replacement) {
|
||||
this.directory = Objects.requireNonNull(directory).toAbsolutePath();
|
||||
this.replacement = Objects.requireNonNull(replacement);
|
||||
enabled = initial;
|
||||
}
|
||||
|
||||
public static boolean validate(Object configured) {
|
||||
if (configured == null) return true;
|
||||
if (configured instanceof Boolean value) return value;
|
||||
throw new IllegalArgumentException("adventure-mode must be true or false");
|
||||
}
|
||||
|
||||
public boolean enabled() { return enabled; }
|
||||
|
||||
public synchronized CompletionStage<Boolean> set(boolean value) {
|
||||
if (closed) return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
|
||||
pending++;
|
||||
try {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try { save(value); enabled = value; return value; }
|
||||
catch (IOException | RuntimeException failure) {
|
||||
// No parser contents, filesystem paths or configuration values in diagnostics.
|
||||
throw new java.util.concurrent.CompletionException(new IOException(
|
||||
"Adventure configuration save refused or failed; effective setting unchanged"));
|
||||
} finally { finished(); }
|
||||
}, worker).minimalCompletionStage();
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
finished();
|
||||
return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
|
||||
}
|
||||
}
|
||||
|
||||
private void save(boolean value) throws IOException {
|
||||
Files.createDirectories(directory);
|
||||
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe directory");
|
||||
var file = directory.resolve("config.yml");
|
||||
var lockFile = directory.resolve(".config.lock");
|
||||
if (Files.exists(lockFile, LinkOption.NOFOLLOW_LINKS)
|
||||
&& !Files.isRegularFile(lockFile, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe lock");
|
||||
try (var channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
|
||||
var lock = channel.tryLock()) {
|
||||
if (lock == null) throw new IOException("Configuration busy");
|
||||
var options = new LoaderOptions();
|
||||
options.setAllowDuplicateKeys(false);
|
||||
options.setMaxAliasesForCollections(20);
|
||||
options.setCodePointLimit(MAX_BYTES);
|
||||
var yaml = new Yaml(new SafeConstructor(options));
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe configuration");
|
||||
byte[] bytes;
|
||||
try (var input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) { bytes = input.readNBytes(MAX_BYTES + 1); }
|
||||
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
|
||||
Object loaded = yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());
|
||||
if (loaded != null) {
|
||||
if (!(loaded instanceof Map<?, ?> map)) throw new IOException("Invalid configuration root");
|
||||
for (var entry : map.entrySet()) {
|
||||
if (!(entry.getKey() instanceof String key)) throw new IOException("Invalid configuration key");
|
||||
values.put(key, entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
values.put("adventure-mode", value);
|
||||
byte[] bytes = yaml.dump(values).getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
|
||||
Path temporary = Files.createTempFile(directory, ".config-", ".tmp");
|
||||
try {
|
||||
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
|
||||
var buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) output.write(buffer);
|
||||
output.force(true);
|
||||
}
|
||||
replacement.move(temporary, file);
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
} catch (OverlappingFileLockException busy) { throw new IOException("Configuration busy"); }
|
||||
}
|
||||
|
||||
private synchronized void finished() {
|
||||
pending--;
|
||||
if (closed && pending == 0) drained.complete(null);
|
||||
}
|
||||
|
||||
public CompletionStage<Void> drained() { return drained.minimalCompletionStage(); }
|
||||
|
||||
/** Drain accepted writes without waiting on the server thread. */
|
||||
@Override public synchronized void close() {
|
||||
closed = true;
|
||||
worker.shutdown();
|
||||
if (pending == 0) drained.complete(null);
|
||||
}
|
||||
}
|
||||
@@ -210,18 +210,51 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
/** Session-owned remaining health; retain all other current fields and reject concurrent revision changes. */
|
||||
public CompletableFuture<Optional<CharacterRecord>> saveHealth(UUID characterId, java.math.BigDecimal health,
|
||||
java.math.BigDecimal nativeLimit) {
|
||||
Objects.requireNonNull(characterId);
|
||||
if (health.signum() < 0 || nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid health bound");
|
||||
return submit(() -> {
|
||||
var found = repository.load(characterId);
|
||||
if (found.isEmpty() || found.orElseThrow().dead()) return Optional.empty();
|
||||
var old = found.orElseThrow();
|
||||
var bounded = health.min(old.maximumHealth()).min(nativeLimit);
|
||||
if (old.health().compareTo(bounded) == 0) return Optional.of(old);
|
||||
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
|
||||
old.experience(), old.unspentPoints(), bounded, old.learned(), old.loadout(), old.cooldowns(),
|
||||
false, old.deathId(), old.diedAt());
|
||||
repository.replace(saved, old.revision());
|
||||
return Optional.of(saved);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* One accepted defeat against the latest live record on this worker, including queued names.
|
||||
* The repository's locked revision compare-and-replace prevents overwriting a concurrent
|
||||
* external writer; a conflict fails rather than retrying an uncertain death or reviving it.
|
||||
* Callers must retain their one-use session authority until the result resolves.
|
||||
*/
|
||||
public CompletableFuture<Optional<CharacterRecord>> recordDeath(UUID characterId) {
|
||||
return death(characterId, null);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<CharacterRecord>> recordDeath(UUID characterId, BigInteger expectedRevision) {
|
||||
return death(characterId, Objects.requireNonNull(expectedRevision));
|
||||
}
|
||||
|
||||
private CompletableFuture<Optional<CharacterRecord>> death(UUID characterId, BigInteger expectedRevision) {
|
||||
Objects.requireNonNull(characterId);
|
||||
Objects.requireNonNull(expectedRevision);
|
||||
Instant diedAt = clock.instant();
|
||||
UUID deathId = UUID.randomUUID();
|
||||
return submit(() -> {
|
||||
Optional<CharacterRecord> found = repository.load(characterId);
|
||||
if (found.isEmpty()) return Optional.empty();
|
||||
CharacterRecord old = found.orElseThrow();
|
||||
if (old.dead() || !old.revision().equals(expectedRevision)) return Optional.empty();
|
||||
if (old.dead() || expectedRevision != null && !old.revision().equals(expectedRevision)) return Optional.empty();
|
||||
var dead = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
|
||||
old.level(), old.experience(), old.unspentPoints(), java.math.BigDecimal.ZERO, old.learned(),
|
||||
old.loadout(), old.cooldowns(), true, UUID.randomUUID(), diedAt);
|
||||
old.loadout(), old.cooldowns(), true, deathId, diedAt);
|
||||
repository.replace(dead, old.revision());
|
||||
return Optional.of(dead);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/**
|
||||
* Player/session receipts, never an external copy of equipment or proof of restoration.
|
||||
* All disk work is deferred. Coordination assumes cooperating writers, not adversarial
|
||||
* replacement of directories. Forced atomic file replacement is not inventory/save atomicity
|
||||
* or a guarantee of directory durability after power loss. Ambiguous receipts are retained.
|
||||
*/
|
||||
public final class EquipmentSessionStore implements AutoCloseable {
|
||||
private static final int MAX_FILE_BYTES = 16_384;
|
||||
private final Path directory;
|
||||
private final Clock clock;
|
||||
private final Replacement replacement;
|
||||
|
||||
@FunctionalInterface
|
||||
interface Replacement { void move(Path source, Path target) throws IOException; }
|
||||
|
||||
private final ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
task -> new Thread(task, "fantasy-equipment-session-persistence"));
|
||||
|
||||
public record Receipt(UUID sessionId, UUID characterId, Instant preparedAt, String previousGameMode, OrdinaryVitals ordinaryVitals) {
|
||||
public Receipt(UUID sessionId, UUID characterId, Instant preparedAt) { this(sessionId, characterId, preparedAt, null, null); }
|
||||
public Receipt(UUID sessionId, UUID characterId, Instant preparedAt, String previousGameMode) {
|
||||
this(sessionId, characterId, preparedAt, previousGameMode, null);
|
||||
}
|
||||
public Receipt {
|
||||
Objects.requireNonNull(sessionId);
|
||||
Objects.requireNonNull(characterId);
|
||||
timestamp(preparedAt);
|
||||
if (previousGameMode != null && !Set.of("SURVIVAL", "CREATIVE", "ADVENTURE", "SPECTATOR").contains(previousGameMode)) {
|
||||
throw new IllegalArgumentException("Invalid previous game mode");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Exit(UUID sessionId, UUID characterId, Instant exitedAt, Instant deadline) {
|
||||
public Exit {
|
||||
Objects.requireNonNull(sessionId);
|
||||
Objects.requireNonNull(characterId);
|
||||
timestamp(exitedAt);
|
||||
timestamp(deadline);
|
||||
if (deadline.isBefore(exitedAt)) throw new IllegalArgumentException("Deadline precedes exit");
|
||||
}
|
||||
}
|
||||
|
||||
public record State(UUID playerId, BigInteger revision, Receipt pending, Exit lastExit) {
|
||||
public State {
|
||||
Objects.requireNonNull(playerId);
|
||||
Objects.requireNonNull(revision);
|
||||
if (revision.signum() < 0) throw new IllegalArgumentException("Negative session revision");
|
||||
if (pending != null && lastExit != null && pending.sessionId().equals(lastExit.sessionId())
|
||||
&& !pending.characterId().equals(lastExit.characterId())) {
|
||||
throw new IllegalArgumentException("Inconsistent session character");
|
||||
}
|
||||
}
|
||||
|
||||
/** Only a delay check; this does not authorize a sheet, equipment, or native state changes. */
|
||||
public boolean canEnter(UUID character, Duration configuredDelay, Instant now) {
|
||||
Objects.requireNonNull(character);
|
||||
Objects.requireNonNull(configuredDelay);
|
||||
Objects.requireNonNull(now);
|
||||
if (configuredDelay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
|
||||
return configuredDelay.isZero() || lastExit == null || character.equals(lastExit.characterId())
|
||||
|| !now.isBefore(lastExit.deadline());
|
||||
}
|
||||
}
|
||||
|
||||
/** No filesystem access, directory creation or recovery occurs in the constructor. */
|
||||
public EquipmentSessionStore(Path pluginDataDirectory, Clock clock) {
|
||||
this(pluginDataDirectory, clock, (source, target) -> Files.move(source, target,
|
||||
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
|
||||
}
|
||||
|
||||
// Narrow disk-boundary seam for deterministic acknowledgment/failure tests.
|
||||
EquipmentSessionStore(Path pluginDataDirectory, Clock clock, Replacement replacement) {
|
||||
directory = Objects.requireNonNull(pluginDataDirectory).resolve("sessions").toAbsolutePath();
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.replacement = Objects.requireNonNull(replacement);
|
||||
}
|
||||
|
||||
public CompletionStage<Optional<State>> find(UUID player) {
|
||||
Objects.requireNonNull(player);
|
||||
return submit(() -> withLock(() -> load(player)));
|
||||
}
|
||||
|
||||
public CompletionStage<State> prepare(UUID player, UUID session, UUID character) {
|
||||
return prepare(player, session, character, null);
|
||||
}
|
||||
|
||||
/** A receipt acknowledgment precedes mode/gear mutation; it is not proof either happened. */
|
||||
public CompletionStage<State> prepare(UUID player, UUID session, UUID character, String previousGameMode) {
|
||||
return prepare(player, session, character, previousGameMode, null);
|
||||
}
|
||||
|
||||
public CompletionStage<State> prepare(UUID player, UUID session, UUID character, String previousGameMode, OrdinaryVitals ordinaryVitals) {
|
||||
Objects.requireNonNull(player);
|
||||
var receipt = new Receipt(session, character, clock.instant(), previousGameMode, ordinaryVitals);
|
||||
return submit(() -> withLock(() -> {
|
||||
var found = load(player);
|
||||
if (found.isPresent()) {
|
||||
var old = found.orElseThrow();
|
||||
if (old.pending() != null) {
|
||||
if (session.equals(old.pending().sessionId()) && character.equals(old.pending().characterId())
|
||||
&& Objects.equals(previousGameMode, old.pending().previousGameMode())
|
||||
&& Objects.equals(ordinaryVitals, old.pending().ordinaryVitals())) {
|
||||
return old;
|
||||
}
|
||||
throw new IOException("Conflicting pending equipment session");
|
||||
}
|
||||
if (old.lastExit() != null && session.equals(old.lastExit().sessionId())) {
|
||||
throw new IOException("Exited session cannot be prepared again");
|
||||
}
|
||||
return write(new State(player, old.revision().add(BigInteger.ONE), receipt, old.lastExit()));
|
||||
}
|
||||
return write(new State(player, BigInteger.ZERO, receipt, null));
|
||||
}));
|
||||
}
|
||||
|
||||
/** Capture the actual exit request time, never queue completion time. The receipt remains pending. */
|
||||
public CompletionStage<State> recordExit(UUID player, UUID session, Duration delay) {
|
||||
Objects.requireNonNull(player);
|
||||
Objects.requireNonNull(session);
|
||||
Objects.requireNonNull(delay);
|
||||
Instant exitedAt = clock.instant();
|
||||
return submit(() -> {
|
||||
if (delay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
|
||||
Instant deadline = exitedAt.plus(delay);
|
||||
timestamp(exitedAt);
|
||||
timestamp(deadline);
|
||||
return withLock(() -> {
|
||||
var old = load(player).orElseThrow(() -> new IOException("Equipment session not found"));
|
||||
if (old.lastExit() != null && session.equals(old.lastExit().sessionId())) return old;
|
||||
if (old.pending() == null || !session.equals(old.pending().sessionId())) {
|
||||
throw new IOException("Exit does not identify the prepared session");
|
||||
}
|
||||
var exit = new Exit(session, old.pending().characterId(), exitedAt, deadline);
|
||||
return write(new State(player, old.revision().add(BigInteger.ONE), old.pending(), exit));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Atomically record a proven native restoration and clear only its matching receipt. */
|
||||
public CompletionStage<State> completeExit(UUID player, UUID session, Duration delay) {
|
||||
Objects.requireNonNull(player);
|
||||
Objects.requireNonNull(session);
|
||||
Objects.requireNonNull(delay);
|
||||
Instant exitedAt = clock.instant();
|
||||
return submit(() -> {
|
||||
if (delay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
|
||||
Instant deadline = exitedAt.plus(delay);
|
||||
timestamp(exitedAt);
|
||||
timestamp(deadline);
|
||||
return withLock(() -> {
|
||||
var old = load(player).orElseThrow(() -> new IOException("Equipment session not found"));
|
||||
boolean recorded = old.lastExit() != null && session.equals(old.lastExit().sessionId());
|
||||
boolean matching = old.pending() != null && session.equals(old.pending().sessionId());
|
||||
if (recorded && !matching) return old; // Never clear a newer pending receipt.
|
||||
if (!matching) throw new IOException("Exit does not identify the prepared session");
|
||||
var exit = recorded ? old.lastExit()
|
||||
: new Exit(session, old.pending().characterId(), exitedAt, deadline);
|
||||
return write(new State(player, old.revision().add(BigInteger.ONE), null, exit));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Caller must prove never-packed or actually restored; absent items are not such proof. */
|
||||
public CompletionStage<State> clearReceipt(UUID player, UUID session) {
|
||||
Objects.requireNonNull(player);
|
||||
Objects.requireNonNull(session);
|
||||
return submit(() -> withLock(() -> {
|
||||
var old = load(player).orElseThrow(() -> new IOException("Equipment session not found"));
|
||||
if (old.pending() == null) return old;
|
||||
if (!session.equals(old.pending().sessionId())) throw new IOException("Receipt session mismatch");
|
||||
return write(new State(player, old.revision().add(BigInteger.ONE), null, old.lastExit()));
|
||||
}));
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface DiskOperation<T> { T run() throws IOException; }
|
||||
|
||||
private <T> CompletionStage<T> submit(DiskOperation<T> operation) {
|
||||
try {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return operation.run();
|
||||
} catch (IOException exception) {
|
||||
throw new CompletionException(exception);
|
||||
}
|
||||
}, worker).minimalCompletionStage();
|
||||
} catch (RejectedExecutionException exception) {
|
||||
return CompletableFuture.failedStage(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T withLock(DiskOperation<T> operation) throws IOException {
|
||||
try {
|
||||
Files.createDirectories(directory);
|
||||
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Unsafe session directory");
|
||||
}
|
||||
Path lockPath = directory.resolve(".sessions.lock");
|
||||
if (Files.exists(lockPath, LinkOption.NOFOLLOW_LINKS)
|
||||
&& !Files.isRegularFile(lockPath, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Unsafe session coordination file");
|
||||
}
|
||||
try (var channel = FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
|
||||
LinkOption.NOFOLLOW_LINKS);
|
||||
var lock = channel.tryLock()) {
|
||||
if (lock == null) throw new IOException("Equipment session busy; retry the operation");
|
||||
return operation.run();
|
||||
}
|
||||
} catch (OverlappingFileLockException exception) {
|
||||
throw new IOException("Equipment session busy; retry the operation");
|
||||
} catch (IOException exception) {
|
||||
// Filesystem paths and parser data must not escape through diagnostics/cause chains.
|
||||
throw new IOException("Equipment session IO refused or failed; original state must be inspected");
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<State> load(UUID player) throws IOException {
|
||||
Path path = file(player);
|
||||
if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe session record");
|
||||
try (var input = Files.newInputStream(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
|
||||
byte[] bytes = input.readNBytes(MAX_FILE_BYTES + 1);
|
||||
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Session record exceeds size limit");
|
||||
String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
|
||||
State state = decode(text);
|
||||
if (!state.playerId().equals(player)) throw new IllegalArgumentException("Session player mismatch");
|
||||
return Optional.of(state);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IOException("Invalid equipment session YAML");
|
||||
}
|
||||
}
|
||||
|
||||
private State write(State state) throws IOException {
|
||||
byte[] bytes = encode(state).getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Session record exceeds size limit");
|
||||
Path temporary = Files.createTempFile(directory, ".session-", ".tmp");
|
||||
try {
|
||||
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) output.write(buffer);
|
||||
output.force(true);
|
||||
}
|
||||
// Do not fall back to truncating or non-atomic replacement of an existing record.
|
||||
replacement.move(temporary, file(state.playerId()));
|
||||
return state;
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
private Path file(UUID player) { return directory.resolve(player + ".yml"); }
|
||||
|
||||
private static Yaml yaml() {
|
||||
var options = new LoaderOptions();
|
||||
options.setAllowDuplicateKeys(false);
|
||||
options.setMaxAliasesForCollections(0);
|
||||
options.setNestingDepthLimit(8);
|
||||
options.setCodePointLimit(MAX_FILE_BYTES);
|
||||
return new Yaml(new SafeConstructor(options));
|
||||
}
|
||||
|
||||
private static String encode(State state) {
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
root.put("schema-version", 1);
|
||||
root.put("player-id", state.playerId().toString());
|
||||
root.put("revision", state.revision().toString());
|
||||
if (state.pending() != null) {
|
||||
var receipt = state.pending();
|
||||
var pending = new LinkedHashMap<String, Object>();
|
||||
pending.put("session-id", receipt.sessionId().toString());
|
||||
pending.put("character-id", receipt.characterId().toString());
|
||||
pending.put("prepared-at", receipt.preparedAt().toString());
|
||||
if (receipt.previousGameMode() != null) pending.put("previous-game-mode", receipt.previousGameMode());
|
||||
if (receipt.ordinaryVitals() != null) pending.put("ordinary-vitals", receipt.ordinaryVitals().encode());
|
||||
root.put("pending", pending);
|
||||
}
|
||||
if (state.lastExit() != null) {
|
||||
var exit = state.lastExit();
|
||||
root.put("last-exit", Map.of("session-id", exit.sessionId().toString(),
|
||||
"character-id", exit.characterId().toString(), "exited-at", exit.exitedAt().toString(),
|
||||
"deadline", exit.deadline().toString()));
|
||||
}
|
||||
return yaml().dump(root);
|
||||
}
|
||||
|
||||
private static State decode(String input) {
|
||||
Map<?, ?> root = mapping(yaml().load(input), Set.of("schema-version", "player-id", "revision"),
|
||||
Set.of("schema-version", "player-id", "revision", "pending", "last-exit"));
|
||||
if (!Integer.valueOf(1).equals(root.get("schema-version"))) {
|
||||
throw new IllegalArgumentException("Unsupported session schema");
|
||||
}
|
||||
Receipt pending = null;
|
||||
Exit exit = null;
|
||||
if (root.containsKey("pending")) {
|
||||
var keys = Set.of("session-id", "character-id", "prepared-at");
|
||||
var row = mapping(root.get("pending"), keys, Set.of("session-id", "character-id", "prepared-at", "previous-game-mode", "ordinary-vitals"));
|
||||
String previousMode = null;
|
||||
if (row.containsKey("previous-game-mode")) {
|
||||
if (!(row.get("previous-game-mode") instanceof String value)) throw new IllegalArgumentException("Invalid previous mode");
|
||||
previousMode = value;
|
||||
}
|
||||
pending = new Receipt(id(row.get("session-id")), id(row.get("character-id")), instant(row.get("prepared-at")), previousMode,
|
||||
row.containsKey("ordinary-vitals") ? OrdinaryVitals.decode(text(row.get("ordinary-vitals"))) : null);
|
||||
}
|
||||
if (root.containsKey("last-exit")) {
|
||||
var keys = Set.of("session-id", "character-id", "exited-at", "deadline");
|
||||
var row = mapping(root.get("last-exit"), keys, keys);
|
||||
exit = new Exit(id(row.get("session-id")), id(row.get("character-id")),
|
||||
instant(row.get("exited-at")), instant(row.get("deadline")));
|
||||
}
|
||||
String revision = text(root.get("revision"));
|
||||
if (!revision.matches("0|[1-9][0-9]*")) throw new IllegalArgumentException("Invalid revision");
|
||||
return new State(id(root.get("player-id")), new BigInteger(revision), pending, exit);
|
||||
}
|
||||
|
||||
private static Map<?, ?> mapping(Object value, Set<String> required, Set<String> allowed) {
|
||||
if (value instanceof Map<?, ?> map && map.keySet().containsAll(required) && allowed.containsAll(map.keySet())) {
|
||||
return map;
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid session mapping");
|
||||
}
|
||||
|
||||
private static String text(Object value) {
|
||||
if (value instanceof String string) return string;
|
||||
throw new IllegalArgumentException("Expected session string");
|
||||
}
|
||||
|
||||
private static UUID id(Object value) {
|
||||
String string = text(value);
|
||||
UUID id = UUID.fromString(string);
|
||||
if (!id.toString().equals(string)) throw new IllegalArgumentException("Noncanonical session UUID");
|
||||
return id;
|
||||
}
|
||||
|
||||
private static Instant instant(Object value) {
|
||||
String string = text(value);
|
||||
if (!string.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](?:\\.[0-9]{1,9})?Z")) {
|
||||
throw new IllegalArgumentException("Expected UTC session timestamp");
|
||||
}
|
||||
return Instant.parse(string);
|
||||
}
|
||||
|
||||
private static void timestamp(Instant value) {
|
||||
instant(Objects.requireNonNull(value).toString());
|
||||
}
|
||||
|
||||
/** Nonblocking shutdown: accepted work drains; no recovery sweep, deletion or replay. */
|
||||
@Override public void close() { worker.shutdown(); }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
/** Holder-owned ordinary state, never transferable character progress or an attribute snapshot. */
|
||||
public record OrdinaryVitals(double health, int food, float saturation, float exhaustion,
|
||||
boolean scaled, double scale) {
|
||||
public OrdinaryVitals {
|
||||
if (!Double.isFinite(health) || health < 0 || food < 0 || food > 20
|
||||
|| !Float.isFinite(saturation) || saturation < 0 || !Float.isFinite(exhaustion) || exhaustion < 0
|
||||
|| !Double.isFinite(scale) || scale <= 0) throw new IllegalArgumentException("Invalid ordinary vitals");
|
||||
}
|
||||
|
||||
public String encode() {
|
||||
return health + ";" + food + ";" + saturation + ";" + exhaustion + ";" + scaled + ";" + scale;
|
||||
}
|
||||
|
||||
public static OrdinaryVitals decode(String encoded) {
|
||||
if (encoded.length() > 256) throw new IllegalArgumentException("Oversized ordinary vitals");
|
||||
String[] fields = encoded.split(";", -1);
|
||||
if (fields.length != 6 || !fields[4].equals("true") && !fields[4].equals("false")) {
|
||||
throw new IllegalArgumentException("Invalid ordinary vitals fields");
|
||||
}
|
||||
var value = new OrdinaryVitals(Double.parseDouble(fields[0]), Integer.parseInt(fields[1]),
|
||||
Float.parseFloat(fields[2]), Float.parseFloat(fields[3]), Boolean.parseBoolean(fields[4]), Double.parseDouble(fields[5]));
|
||||
if (!encoded.equals(value.encode())) throw new IllegalArgumentException("Noncanonical ordinary vitals");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
/** Substitutes only the renderer's sender-name argument; signed body and delivery stay native. */
|
||||
public final class CharacterChatNames implements Listener {
|
||||
private final Function<UUID, String> names;
|
||||
public CharacterChatNames(Function<UUID, String> names) { this.names = names; }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onChat(AsyncChatEvent event) {
|
||||
if (event.isCancelled()) return;
|
||||
String name = names.apply(event.getPlayer().getUniqueId());
|
||||
if (name == null) return;
|
||||
var literal = net.kyori.adventure.text.Component.text(name);
|
||||
var ordinary = event.renderer();
|
||||
event.renderer((source, ignoredName, message, viewer) -> ordinary.render(source, literal, message, viewer));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Immutable session decisions shared by chat/packet threads; native output stays on the server thread. */
|
||||
public final class CharacterPresentation implements SessionPresentation, AutoCloseable {
|
||||
public record View(UUID holder, UUID session, UUID character, BigInteger revision, String name) { }
|
||||
public interface Output extends AutoCloseable {
|
||||
void show(Player player, View view);
|
||||
void rename(View view);
|
||||
void clear(View view);
|
||||
@Override void close();
|
||||
}
|
||||
private final Output output;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final BooleanSupplier mainThread;
|
||||
private final Consumer<Throwable> failures;
|
||||
private volatile Map<UUID, View> views = Map.of();
|
||||
private boolean closed;
|
||||
private java.util.function.Function<UUID, java.util.concurrent.CompletionStage<java.util.Optional<CharacterRecord>>> currentRecord =
|
||||
ignored -> java.util.concurrent.CompletableFuture.completedFuture(java.util.Optional.empty());
|
||||
public CharacterPresentation(Output output, Consumer<Runnable> nextTick, BooleanSupplier mainThread, Consumer<Throwable> failures) {
|
||||
this.output = output; this.nextTick = nextTick; this.mainThread = mainThread; this.failures = failures;
|
||||
}
|
||||
public CharacterPresentation(Output output, Consumer<Runnable> nextTick, BooleanSupplier mainThread, Consumer<Throwable> failures,
|
||||
java.util.function.Function<UUID, java.util.concurrent.CompletionStage<java.util.Optional<CharacterRecord>>> currentRecord) {
|
||||
this(output, nextTick, mainThread, failures);
|
||||
this.currentRecord = java.util.Objects.requireNonNull(currentRecord);
|
||||
}
|
||||
public Map<UUID, View> snapshot() { return views; }
|
||||
public String name(UUID holder) { var view = views.get(holder); return view == null ? null : view.name(); }
|
||||
@Override public synchronized void activate(Player player, UUID session, CharacterRecord record) {
|
||||
if (closed) return;
|
||||
UUID holder = player.getUniqueId();
|
||||
var previous = views.get(holder);
|
||||
if (previous != null) withdraw(holder, previous.session());
|
||||
var view = new View(holder, session, record.id(), record.revision(), record.name());
|
||||
put(view);
|
||||
safely(() -> output.show(player, view));
|
||||
if (!closed && view.equals(views.get(holder))) safely(() -> currentRecord.apply(record.id()).whenComplete((saved, failure) -> {
|
||||
if (failure != null) { safely(() -> { throw new java.util.concurrent.CompletionException(failure); }); return; }
|
||||
saved.ifPresent(fresh -> acknowledge(view, fresh));
|
||||
}));
|
||||
}
|
||||
@Override public synchronized void withdraw(UUID player, UUID session) {
|
||||
var view = views.get(player);
|
||||
if (view == null || !view.session().equals(session)) return;
|
||||
var copy = new java.util.HashMap<>(views); copy.remove(player); views = Map.copyOf(copy);
|
||||
// Invalidate synchronously even on a worker failure; never access Bukkit on that worker.
|
||||
if (mainThread.getAsBoolean()) safely(() -> output.clear(view));
|
||||
else safely(() -> nextTick.accept(() -> safely(() -> output.clear(view))));
|
||||
}
|
||||
/** File acknowledgment, not the physical sheet name. Safe to call from the persistence worker. */
|
||||
public void acknowledged(CharacterRecord record) {
|
||||
// Capture lifetime tokens now. A late callback cannot name a replacement holder/session.
|
||||
for (var view : views.values()) acknowledge(view, record);
|
||||
}
|
||||
private void acknowledge(View target, CharacterRecord record) {
|
||||
if (!newer(target, record)) return;
|
||||
safely(() -> nextTick.accept(() -> {
|
||||
synchronized (CharacterPresentation.this) {
|
||||
if (closed || !newer(target, record)) return;
|
||||
var updated = new View(target.holder(), target.session(), target.character(), record.revision(), record.name());
|
||||
put(updated);
|
||||
safely(() -> output.rename(updated));
|
||||
}
|
||||
}));
|
||||
}
|
||||
private boolean newer(View target, CharacterRecord record) {
|
||||
var current = views.get(target.holder());
|
||||
return current != null && current.session().equals(target.session()) && record.id().equals(current.character())
|
||||
&& !record.dead() && record.revision().compareTo(current.revision()) > 0;
|
||||
}
|
||||
private void put(View view) {
|
||||
var copy = new java.util.HashMap<>(views); copy.put(view.holder(), view); views = Map.copyOf(copy);
|
||||
}
|
||||
private void safely(Runnable action) {
|
||||
try { action.run(); }
|
||||
catch (RuntimeException | LinkageError failure) {
|
||||
try { failures.accept(failure); } catch (RuntimeException | LinkageError ignored) { /* Cleanup must continue. */ }
|
||||
}
|
||||
}
|
||||
@Override public synchronized void close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (var view : java.util.List.copyOf(views.values())) withdraw(view.holder(), view.session());
|
||||
safely(output::close);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Entry;
|
||||
import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.AttributeSnapshot;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Display.BillboardConstraints;
|
||||
import net.minecraft.world.entity.Display.TextDisplay;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.entity.PositionMoveRotation;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Display-only codec pinned to Purpur 26.2 build 2618. No packet delivery, world insertion,
|
||||
* profile/team changes, or authoritative player mutations belong here.
|
||||
*
|
||||
* <p>Player reads and detached-label creation/updates belong on the server thread. Pure
|
||||
* packet projections accept already-captured session identity/text; the caller owns visibility,
|
||||
* per-viewer range, lifecycle checks and removing each viewer's client-only labels.
|
||||
*/
|
||||
public final class NativePresentationPackets {
|
||||
private NativePresentationPackets() { }
|
||||
|
||||
/**
|
||||
* Replace only the selected UUID's display component when its action is already present.
|
||||
* Preserve all other entry fields and the exact action set, including mixed ADD packets.
|
||||
* ADD without UPDATE_DISPLAY_NAME needs a separate targeted update after acceptance.
|
||||
*/
|
||||
public static ClientboundPlayerInfoUpdatePacket projectPlayerInfo(
|
||||
ClientboundPlayerInfoUpdatePacket packet, UUID activePlayer, String name) {
|
||||
var actions = packet.actions();
|
||||
if (!actions.contains(Action.UPDATE_DISPLAY_NAME)) {
|
||||
return packet;
|
||||
}
|
||||
var entries = new ArrayList<Entry>(packet.entries().size());
|
||||
boolean changed = false;
|
||||
for (var entry : packet.entries()) {
|
||||
if (entry.profileId().equals(activePlayer)) {
|
||||
entries.add(new Entry(entry.profileId(), entry.profile(), entry.listed(), entry.latency(),
|
||||
entry.gameMode(), literal(name), entry.showHat(), entry.listOrder(), entry.chatSession()));
|
||||
changed = true;
|
||||
} else {
|
||||
entries.add(entry);
|
||||
}
|
||||
}
|
||||
if (!changed) { return packet; }
|
||||
return new ClientboundPlayerInfoUpdatePacket(EnumSet.copyOf(actions), entries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace an existing NAME_TAG_DISTANCE snapshot with base zero/no modifiers, only for
|
||||
* the selected entity. Do not inject absent attributes; use suppressNameTag on activation.
|
||||
*/
|
||||
public static ClientboundUpdateAttributesPacket projectAttributes(
|
||||
ClientboundUpdateAttributesPacket packet, int activeEntityId) {
|
||||
if (packet.getEntityId() != activeEntityId || packet.getValues().stream()
|
||||
.noneMatch(value -> value.attribute().equals(Attributes.NAME_TAG_DISTANCE))) {
|
||||
return packet;
|
||||
}
|
||||
var projected = new ClientboundUpdateAttributesPacket(activeEntityId, List.of());
|
||||
for (var value : packet.getValues()) {
|
||||
projected.getValues().add(value.attribute().equals(Attributes.NAME_TAG_DISTANCE)
|
||||
? new AttributeSnapshot(Attributes.NAME_TAG_DISTANCE, 0, List.of()) : value);
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
/** One client-only distance snapshot; never changes the server's attribute instance. */
|
||||
public static ClientboundUpdateAttributesPacket suppressNameTag(int entityId) {
|
||||
var packet = new ClientboundUpdateAttributesPacket(entityId, List.of());
|
||||
packet.getValues().add(new AttributeSnapshot(Attributes.NAME_TAG_DISTANCE, 0, List.of()));
|
||||
return packet;
|
||||
}
|
||||
|
||||
/** Snapshot the current authoritative distance base and all modifiers, not an old default. */
|
||||
public static ClientboundUpdateAttributesPacket restoreNameTag(ServerPlayer player) {
|
||||
var distance = player.getAttribute(Attributes.NAME_TAG_DISTANCE);
|
||||
if (distance == null) {
|
||||
throw new IllegalStateException("Native player has no NAME_TAG_DISTANCE attribute");
|
||||
}
|
||||
var packet = new ClientboundUpdateAttributesPacket(player.getId(), List.of());
|
||||
packet.getValues().add(new AttributeSnapshot(Attributes.NAME_TAG_DISTANCE,
|
||||
distance.getBaseValue(), List.copyOf(distance.getModifiers())));
|
||||
return packet;
|
||||
}
|
||||
|
||||
/** UPDATE_DISPLAY_NAME only, using the current ordinary native tab display (including null). */
|
||||
public static ClientboundPlayerInfoUpdatePacket refreshTab(ServerPlayer player) {
|
||||
// Only UUID and displayName are serialized by this action. Do not capture unrelated
|
||||
// connection/game-mode state or synthesize ADD_PLAYER/listed/profile updates.
|
||||
var ordinary = player.getTabListDisplayName();
|
||||
var entry = new Entry(player.getUUID(), null, false, 0,
|
||||
GameType.DEFAULT_MODE, ordinary == null ? null : ordinary.copy(),
|
||||
false, 0, null);
|
||||
return new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.UPDATE_DISPLAY_NAME), List.of(entry));
|
||||
}
|
||||
|
||||
/** Pure targeted display update: no profile, listed, game-mode or reconnect actions. */
|
||||
public static ClientboundPlayerInfoUpdatePacket displayName(UUID player, String name) {
|
||||
var entry = new Entry(player, null, false, 0, GameType.DEFAULT_MODE, literal(name), false, 0, null);
|
||||
return new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.UPDATE_DISPLAY_NAME), List.of(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a detached TextDisplay in the player's current native level at explicit coordinates.
|
||||
* Native construction allocates its ID through ServerLevel.getNextEntityId; never register it.
|
||||
* The caller chooses overhead position and recreates the label after world changes.
|
||||
*/
|
||||
public static Label createLabel(ServerPlayer player, String text, double x, double y, double z) {
|
||||
validatePosition(x, y, z);
|
||||
var component = literal(text);
|
||||
var level = player.level();
|
||||
if (level == null) { throw new IllegalStateException("Native player has no current server level"); }
|
||||
// A native constructor supplies the exact metadata schema and native ID allocation.
|
||||
// Never spawn, tick, wrap in a Bukkit entity, or expose this detached instance.
|
||||
var display = new TextDisplay(EntityTypes.TEXT_DISPLAY, level);
|
||||
display.persist = false;
|
||||
display.setNoGravity(true);
|
||||
display.setBillboardConstraints(BillboardConstraints.CENTER);
|
||||
display.getEntityData().set(TextDisplay.DATA_LINE_WIDTH_ID, Integer.MAX_VALUE);
|
||||
display.setFlags((byte) (TextDisplay.FLAG_SHADOW | TextDisplay.FLAG_USE_DEFAULT_BACKGROUND));
|
||||
display.setText(component);
|
||||
display.setPos(x, y, z);
|
||||
return new Label(display);
|
||||
}
|
||||
|
||||
private static Component literal(String text) {
|
||||
if (text == null) { throw new IllegalArgumentException("Display text must not be null"); }
|
||||
return Component.literal(text);
|
||||
}
|
||||
|
||||
private static void validatePosition(double x, double y, double z) {
|
||||
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)) {
|
||||
throw new IllegalArgumentException("Label coordinates must be finite");
|
||||
}
|
||||
}
|
||||
|
||||
/** A session-owned detached entity; no native entity is exposed for accidental world insertion. */
|
||||
public static final class Label {
|
||||
private final TextDisplay display;
|
||||
|
||||
private Label(TextDisplay display) { this.display = display; }
|
||||
|
||||
public int id() { return display.getId(); }
|
||||
public UUID uuid() { return display.getUUID(); }
|
||||
|
||||
/** Send spawn followed by metadata to each newly eligible viewer. */
|
||||
public ClientboundAddEntityPacket spawn() {
|
||||
return new ClientboundAddEntityPacket(id(), uuid(), display.getX(), display.getY(), display.getZ(),
|
||||
0, 0, display.getType(), 0, Vec3.ZERO, 0);
|
||||
}
|
||||
|
||||
/** Complete metadata, not consumable packDirty state: safe for multiple viewers. */
|
||||
public ClientboundSetEntityDataPacket metadata() {
|
||||
return new ClientboundSetEntityDataPacket(id(), display.getEntityData().packAll());
|
||||
}
|
||||
|
||||
/** Update only the detached label and return an absolute teleport packet. */
|
||||
public ClientboundTeleportEntityPacket move(double x, double y, double z) {
|
||||
validatePosition(x, y, z);
|
||||
display.setPos(x, y, z);
|
||||
return ClientboundTeleportEntityPacket.teleport(id(),
|
||||
PositionMoveRotation.of(display), Set.of(), false);
|
||||
}
|
||||
|
||||
/** Replace only the detached label's literal text and return complete metadata. */
|
||||
public ClientboundSetEntityDataPacket rename(String text) {
|
||||
display.setText(literal(text));
|
||||
return metadata();
|
||||
}
|
||||
|
||||
/** Client-only removal; never calls entity discard/remove on the server world. */
|
||||
public ClientboundRemoveEntitiesPacket remove() {
|
||||
return new ClientboundRemoveEntitiesPacket(id());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.ProtocolManager;
|
||||
import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
import com.comphenix.protocol.events.NetworkMarker;
|
||||
import com.comphenix.protocol.events.PacketPostListener;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation.View;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundBundlePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundRespawnPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.craftbukkit.entity.CraftPlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
/**
|
||||
* Pinned native output adapter. Public lifecycle methods and the scheduled reconciliation run
|
||||
* on the server thread. Packet callbacks use only immutable decisions, the parent's published
|
||||
* snapshot, packet values and recipient UUIDs. No authoritative presentation is ever changed.
|
||||
* The snapshot supplier is not read during construction: the owner may initialize its field
|
||||
* lazily, then publish a View before calling show/rename. Diagnostics may run on packet threads.
|
||||
*/
|
||||
public final class ProtocolPresentation implements CharacterPresentation.Output {
|
||||
private final Plugin plugin;
|
||||
private final ProtocolManager protocol;
|
||||
private final Supplier<Map<UUID, View>> snapshot;
|
||||
private final Consumer<Throwable> diagnostics;
|
||||
private final Map<UUID, State> states = new HashMap<>();
|
||||
private final PacketAdapter listener;
|
||||
// Cancelled events never post. Weak keys release their immutable context with the marker.
|
||||
private final Map<NetworkMarker, Map<UUID, Decision>> deliveries = new WeakHashMap<>();
|
||||
private final PacketPostListener postListener = new PacketPostListener() {
|
||||
@Override public Plugin getPlugin() { return plugin; }
|
||||
@Override public void onPostEvent(PacketEvent event) { accepted(event); }
|
||||
};
|
||||
private record Decision(View view, int entity, Map<UUID, Integer> labels) { }
|
||||
private Map<UUID, Decision> decisions = Map.of();
|
||||
private record Route(UUID holder, UUID session, UUID viewer) { }
|
||||
private final Map<Route, Integer> blocked = new HashMap<>();
|
||||
private final Set<Route> retired = new HashSet<>();
|
||||
private final Set<Route> tracking = new HashSet<>();
|
||||
private static final int UNTRACKED = 1;
|
||||
private static final int INVISIBLE = 2;
|
||||
private static final int FAILED = 4;
|
||||
private static final int TAB_REMOVED = 8;
|
||||
private BukkitTask task;
|
||||
private boolean installed;
|
||||
private boolean closed;
|
||||
private int warnings;
|
||||
private boolean operating;
|
||||
private boolean draining;
|
||||
private final ArrayDeque<Runnable> pending = new ArrayDeque<>();
|
||||
|
||||
private static final class State {
|
||||
private final Player player;
|
||||
private int entity;
|
||||
private View view;
|
||||
private org.bukkit.World world;
|
||||
private NativePresentationPackets.Label label;
|
||||
private final Map<UUID, Player> viewers = new HashMap<>();
|
||||
private State(Player player, View view) {
|
||||
this.player = player; this.view = view; this.entity = player.getEntityId();
|
||||
this.world = player.getWorld();
|
||||
}
|
||||
}
|
||||
|
||||
public ProtocolPresentation(Plugin plugin, ProtocolManager protocol,
|
||||
Supplier<Map<UUID, View>> snapshot, Consumer<Throwable> diagnostics) {
|
||||
this.plugin = Objects.requireNonNull(plugin);
|
||||
this.protocol = Objects.requireNonNull(protocol);
|
||||
this.snapshot = Objects.requireNonNull(snapshot);
|
||||
this.diagnostics = Objects.requireNonNull(diagnostics);
|
||||
listener = new PacketAdapter(plugin, ListenerPriority.HIGHEST,
|
||||
PacketType.Play.Server.PLAYER_INFO, PacketType.Play.Server.UPDATE_ATTRIBUTES,
|
||||
PacketType.Play.Server.ENTITY_DESTROY, PacketType.Play.Server.ENTITY_METADATA,
|
||||
PacketType.Play.Server.SPAWN_ENTITY, PacketType.Play.Server.PLAYER_INFO_REMOVE,
|
||||
PacketType.Play.Server.RESPAWN, PacketType.Play.Server.BUNDLE) {
|
||||
@Override public void onPacketSending(PacketEvent event) { project(event); }
|
||||
};
|
||||
}
|
||||
|
||||
/** Idempotent; the supplied manager is the sole ProtocolLib dependency. */
|
||||
public synchronized void install() {
|
||||
if (closed || installed) { return; }
|
||||
installed = true;
|
||||
try {
|
||||
protocol.addPacketListener(listener);
|
||||
task = plugin.getServer().getScheduler().runTaskTimer(plugin, this::tick, 1L, 1L);
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
report(failure); close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override public synchronized void show(Player player, View view) {
|
||||
if (!begin(() -> show(player, view))) { return; }
|
||||
try {
|
||||
if (closed || !view.equals(snapshot.get().get(view.holder()))
|
||||
|| !player.getUniqueId().equals(view.holder())) { return; }
|
||||
var old = states.get(view.holder());
|
||||
if (old != null) {
|
||||
if (sameSession(old.view, view)) { rename(view); return; }
|
||||
states.remove(view.holder());
|
||||
removeLabels(old);
|
||||
forget(old);
|
||||
}
|
||||
if (closed || !view.equals(snapshot.get().get(view.holder())) || states.containsKey(view.holder())) { return; }
|
||||
var state = new State(player, view);
|
||||
states.put(view.holder(), state);
|
||||
// Existing trackers predate activation; subsequent viewers need an accepted pairing.
|
||||
for (var viewer : player.getTrackedBy()) { tracking.add(route(view, viewer.getUniqueId())); }
|
||||
publish();
|
||||
refreshTab(state, true);
|
||||
reconcile(state);
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
@Override public synchronized void rename(View view) {
|
||||
if (!begin(() -> rename(view))) { return; }
|
||||
try {
|
||||
var state = states.get(view.holder());
|
||||
if (closed || state == null || !sameSession(state.view, view)
|
||||
|| !view.equals(snapshot.get().get(view.holder()))
|
||||
|| view.revision().compareTo(state.view.revision()) < 0) { return; }
|
||||
state.view = view;
|
||||
publish();
|
||||
refreshTab(state, true);
|
||||
reconcile(state);
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
@Override public synchronized void clear(View view) {
|
||||
if (!begin(() -> clear(view))) { return; }
|
||||
try {
|
||||
var state = states.get(view.holder());
|
||||
if (state == null || !sameSession(state.view, view)) { return; }
|
||||
states.remove(view.holder());
|
||||
publish();
|
||||
removeLabels(state);
|
||||
forget(state);
|
||||
restore(state);
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
private synchronized void tick() {
|
||||
if (!begin(this::tick)) { return; }
|
||||
try {
|
||||
if (closed) { return; }
|
||||
for (var state : List.copyOf(states.values())) {
|
||||
try {
|
||||
if (!state.player.isOnline() || !sameSession(state.view, snapshot.get().get(state.view.holder()))) {
|
||||
clear(state.view);
|
||||
} else { reconcile(state); }
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
report(failure); removeLabels(state);
|
||||
}
|
||||
}
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
private boolean current(State state, View expected) {
|
||||
return !closed && states.get(expected.holder()) == state && expected.equals(state.view)
|
||||
&& expected.equals(snapshot.get().get(expected.holder()));
|
||||
}
|
||||
|
||||
private boolean deliver(State state, View expected, Player viewer, Object packet) {
|
||||
// A stale decision is skipped, not classified as an uncertain transport failure.
|
||||
return !current(state, expected) || send(viewer, packet);
|
||||
}
|
||||
|
||||
private void reconcile(State state) {
|
||||
var expected = state.view;
|
||||
if (!current(state, expected)) { return; }
|
||||
try {
|
||||
var player = state.player;
|
||||
for (var id : List.copyOf(state.viewers.keySet())) {
|
||||
if (retired.remove(route(state.view, id))) { state.viewers.remove(id); }
|
||||
}
|
||||
publish();
|
||||
var location = player.getLocation();
|
||||
if (state.world != player.getWorld() || state.entity != player.getEntityId()) {
|
||||
removeLabels(state);
|
||||
if (!current(state, expected)) { return; }
|
||||
state.label = null;
|
||||
state.world = player.getWorld();
|
||||
state.entity = player.getEntityId();
|
||||
// A world/entity change is not delivery evidence. Only an accepted native
|
||||
// spawn may clear UNTRACKED/INVISIBLE, never a tick with stale platform trackers.
|
||||
publish();
|
||||
}
|
||||
if (state.label == null) {
|
||||
state.label = NativePresentationPackets.createLabel(((CraftPlayer) player).getHandle(),
|
||||
state.view.name(), location.getX(), location.getY() + player.getHeight() + 0.3, location.getZ());
|
||||
}
|
||||
var move = state.label.move(location.getX(), location.getY() + player.getHeight() + 0.3, location.getZ());
|
||||
var metadata = state.label.rename(state.view.name());
|
||||
var tracked = player.getTrackedBy();
|
||||
for (var entry : List.copyOf(state.viewers.entrySet())) {
|
||||
if (!tracked.contains(entry.getValue()) || !eligible(player, entry.getValue())) {
|
||||
state.viewers.remove(entry.getKey());
|
||||
removeLabel(state, entry.getValue());
|
||||
}
|
||||
}
|
||||
for (var viewer : tracked) {
|
||||
if (!current(state, expected)) { return; }
|
||||
try {
|
||||
if (!eligible(player, viewer)) { continue; }
|
||||
var id = viewer.getUniqueId();
|
||||
var key = route(state.view, id);
|
||||
if (!tracking.contains(key) || blocked.containsKey(key)) { continue; }
|
||||
if (!state.viewers.containsKey(id)) {
|
||||
state.viewers.put(id, viewer);
|
||||
publish();
|
||||
if (!deliver(state, expected, viewer, NativePresentationPackets.suppressNameTag(state.entity))
|
||||
|| !deliver(state, expected, viewer, state.label.spawn()) || !deliver(state, expected, viewer, metadata)) {
|
||||
quarantine(state, viewer);
|
||||
}
|
||||
} else if (!deliver(state, expected, viewer, move) || !deliver(state, expected, viewer, metadata)) {
|
||||
quarantine(state, viewer);
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); removeLabels(state); }
|
||||
finally { publish(); }
|
||||
}
|
||||
|
||||
private void quarantine(State state, Player viewer) {
|
||||
if (states.get(state.view.holder()) != state) { return; }
|
||||
var id = viewer.getUniqueId();
|
||||
// A send can have escaped before throwing. Retire once; never retry its spawn sequence.
|
||||
blocked.merge(route(state.view, id), FAILED, (before, flag) -> before | flag);
|
||||
state.viewers.remove(id);
|
||||
publish();
|
||||
send(viewer, state.label.remove());
|
||||
}
|
||||
|
||||
private boolean eligible(Player target, Player viewer) {
|
||||
if (viewer.getUniqueId().equals(target.getUniqueId()) || !viewer.isOnline()
|
||||
|| target.getWorld() != viewer.getWorld() || !viewer.canSee(target)
|
||||
|| target.isInvisible() || target.getGameMode() == GameMode.SPECTATOR) { return false; }
|
||||
var nativeTarget = ((CraftPlayer) target).getHandle();
|
||||
var distance = nativeTarget.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE);
|
||||
if (distance == null) { return false; }
|
||||
double range = distance.getValue();
|
||||
if (target.isSneaking()) { range = Math.min(32, range); }
|
||||
if (!(range > 0) || !(viewer.getLocation().distanceSquared(target.getLocation()) < range * range)) { return false; }
|
||||
// The recipient's native scoreboard is the one its client sees (it may differ from
|
||||
// the main scoreboard). Read existing membership only; never create private teams.
|
||||
var board = ((CraftPlayer) viewer).getScoreboard().getHandle();
|
||||
var team = board.getPlayersTeam(target.getName());
|
||||
if (team == null) { return true; }
|
||||
var viewerTeam = board.getPlayersTeam(viewer.getName());
|
||||
return switch (team.getNameTagVisibility()) {
|
||||
case ALWAYS -> true;
|
||||
case NEVER -> false;
|
||||
case HIDE_FOR_OTHER_TEAMS -> viewerTeam == null || team.isAlliedTo(viewerTeam);
|
||||
case HIDE_FOR_OWN_TEAM -> viewerTeam == null || !team.isAlliedTo(viewerTeam);
|
||||
};
|
||||
}
|
||||
|
||||
private void refreshTab(State state, boolean fantasy) {
|
||||
var expected = state.view;
|
||||
try {
|
||||
var ordinary = NativePresentationPackets.refreshTab(((CraftPlayer) state.player).getHandle());
|
||||
var packet = fantasy ? NativePresentationPackets.projectPlayerInfo(ordinary, state.view.holder(), state.view.name()) : ordinary;
|
||||
for (var viewer : List.copyOf(plugin.getServer().getOnlinePlayers())) {
|
||||
if (fantasy ? !current(state, expected) : !restorable(state)) { return; }
|
||||
try { if (viewer.canSee(state.player)) { send(viewer, packet); } }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
|
||||
private boolean restorable(State state) {
|
||||
var replacement = snapshot.get().get(state.view.holder());
|
||||
return !states.containsKey(state.view.holder()) && (replacement == null || sameSession(state.view, replacement));
|
||||
}
|
||||
|
||||
private void restore(State state) {
|
||||
if (!restorable(state)) { return; }
|
||||
refreshTab(state, false);
|
||||
try {
|
||||
var packet = NativePresentationPackets.restoreNameTag(((CraftPlayer) state.player).getHandle());
|
||||
var recipients = new HashSet<>(state.player.getTrackedBy());
|
||||
recipients.add(state.player);
|
||||
for (var viewer : recipients) {
|
||||
if (!restorable(state)) { return; }
|
||||
try { if (viewer.canSee(state.player)) { send(viewer, packet); } }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
|
||||
private void removeLabel(State state, Player viewer) {
|
||||
if (!send(viewer, state.label.remove()) && states.get(state.view.holder()) == state) {
|
||||
blocked.merge(route(state.view, viewer.getUniqueId()), FAILED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeLabels(State state) {
|
||||
var viewers = List.copyOf(state.viewers.values());
|
||||
var label = state.label;
|
||||
state.viewers.clear();
|
||||
publish();
|
||||
if (label != null) {
|
||||
for (var viewer : viewers) {
|
||||
if (!send(viewer, label.remove()) && states.get(state.view.holder()) == state) {
|
||||
blocked.merge(route(state.view, viewer.getUniqueId()), FAILED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
var next = new HashMap<UUID, Decision>();
|
||||
for (var state : states.values()) {
|
||||
var labels = new HashMap<UUID, Integer>();
|
||||
if (state.label != null) {
|
||||
for (var viewer : state.viewers.keySet()) { labels.put(viewer, state.label.id()); }
|
||||
}
|
||||
next.put(state.view.holder(), new Decision(state.view, state.entity, Map.copyOf(labels)));
|
||||
}
|
||||
decisions = Map.copyOf(next);
|
||||
}
|
||||
|
||||
private static Route route(View view, UUID viewer) { return new Route(view.holder(), view.session(), viewer); }
|
||||
|
||||
private void forget(State state) {
|
||||
blocked.keySet().removeIf(key -> key.holder().equals(state.view.holder()) && key.session().equals(state.view.session()));
|
||||
retired.removeIf(key -> key.holder().equals(state.view.holder()) && key.session().equals(state.view.session()));
|
||||
tracking.removeIf(key -> key.holder().equals(state.view.holder()) && key.session().equals(state.view.session()));
|
||||
}
|
||||
|
||||
private synchronized void project(PacketEvent event) {
|
||||
if (closed) { return; }
|
||||
try {
|
||||
var original = event.getPacket().getHandle();
|
||||
var viewer = event.getPlayer().getUniqueId();
|
||||
reserveSpawn(original, viewer);
|
||||
if (event.isCancelled()) { return; }
|
||||
var marker = event.getNetworkMarker();
|
||||
deliveries.putIfAbsent(marker, decisions);
|
||||
marker.addPostListener(postListener); // The parent and children share this deduplicating set.
|
||||
// ProtocolLib visits children AFTER the parent, including lower-priority vetoes.
|
||||
// Never expand a child into a bundle or mutate route state speculatively here.
|
||||
Object projected = original;
|
||||
for (var decision : decisions.values()) {
|
||||
var view = currentView(decision);
|
||||
if (view == null) { continue; }
|
||||
if (projected instanceof ClientboundPlayerInfoUpdatePacket info) {
|
||||
projected = NativePresentationPackets.projectPlayerInfo(info, view.holder(), view.name());
|
||||
} else if (projected instanceof ClientboundUpdateAttributesPacket attributes) {
|
||||
projected = NativePresentationPackets.projectAttributes(attributes, decision.entity());
|
||||
}
|
||||
}
|
||||
if (projected != original) { event.setPacket(wrap(projected)); }
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
|
||||
private void reserveSpawn(Object packet, UUID viewer) {
|
||||
if (packet instanceof ClientboundBundlePacket bundle) {
|
||||
bundle.subPackets().forEach(child -> reserveSpawn(child, viewer));
|
||||
} else if (packet instanceof ClientboundAddEntityPacket spawn) {
|
||||
var decision = decisions.get(spawn.getUUID());
|
||||
if (decision != null && decision.entity() == spawn.getId() && !decision.labels().containsKey(viewer)) {
|
||||
// A tick between dispatch and post must not invent a successful new pairing.
|
||||
// Do not retire an existing label or clear any visibility flag on an attempt.
|
||||
blocked.merge(route(decision.view(), viewer), UNTRACKED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Native topology survives renames; any rendering payload uses the latest published view. */
|
||||
private View currentView(Decision expected) {
|
||||
var now = decisions.get(expected.view().holder());
|
||||
var latest = snapshot.get().get(expected.view().holder());
|
||||
return !closed && now != null && now.entity() == expected.entity()
|
||||
&& sameSession(expected.view(), now.view()) && sameSession(expected.view(), latest) ? latest : null;
|
||||
}
|
||||
|
||||
private synchronized void accepted(PacketEvent event) {
|
||||
if (!begin(() -> accepted(event))) { return; }
|
||||
try {
|
||||
var captured = deliveries.remove(NetworkMarker.getNetworkMarker(event));
|
||||
if (closed || event.isCancelled() || captured == null) { return; }
|
||||
var viewer = event.getPlayer();
|
||||
var id = viewer.getUniqueId();
|
||||
var removals = new HashMap<Decision, Integer>();
|
||||
var displays = new HashSet<Decision>();
|
||||
commitNative(event.getPacket().getHandle(), id, captured, removals, displays);
|
||||
for (var entry : removals.entrySet()) {
|
||||
var decision = entry.getKey();
|
||||
if (currentView(decision) != null && !send(viewer, new ClientboundRemoveEntitiesPacket(entry.getValue()))) {
|
||||
blocked.merge(route(decision.view(), id), FAILED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
for (var decision : displays) {
|
||||
var view = currentView(decision);
|
||||
if (view != null && (blocked.getOrDefault(route(view, id), 0) & TAB_REMOVED) == 0) {
|
||||
send(viewer, NativePresentationPackets.displayName(view.holder(), view.name()));
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
finally { finish(); }
|
||||
}
|
||||
|
||||
private void commitNative(Object packet, UUID viewer, Map<UUID, Decision> captured,
|
||||
Map<Decision, Integer> removals, Set<Decision> displays) {
|
||||
if (packet instanceof ClientboundBundlePacket bundle) {
|
||||
bundle.subPackets().forEach(child -> commitNative(child, viewer, captured, removals, displays));
|
||||
return;
|
||||
}
|
||||
for (var decision : captured.values()) {
|
||||
var view = currentView(decision);
|
||||
if (view == null) { continue; }
|
||||
var key = route(view, viewer);
|
||||
int mask = blocked.getOrDefault(key, 0);
|
||||
if (packet instanceof ClientboundPlayerInfoUpdatePacket info) {
|
||||
if (info.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)
|
||||
&& info.entries().stream().anyMatch(entry -> entry.profileId().equals(view.holder()))) {
|
||||
mask &= ~TAB_REMOVED;
|
||||
if (!info.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME)) {
|
||||
displays.add(decision);
|
||||
}
|
||||
}
|
||||
} else if (packet instanceof ClientboundRemoveEntitiesPacket removal
|
||||
&& removal.getEntityIds().contains(decision.entity())) { mask |= UNTRACKED; }
|
||||
else if (packet instanceof ClientboundPlayerInfoRemovePacket removal
|
||||
&& removal.profileIds().contains(view.holder())) { mask |= TAB_REMOVED; }
|
||||
else if (packet instanceof ClientboundRespawnPacket) { mask |= UNTRACKED; }
|
||||
else if (packet instanceof ClientboundAddEntityPacket spawn && spawn.getId() == decision.entity()
|
||||
&& spawn.getUUID().equals(view.holder())) {
|
||||
mask &= ~(UNTRACKED | INVISIBLE);
|
||||
tracking.add(key);
|
||||
}
|
||||
else if (packet instanceof ClientboundSetEntityDataPacket metadata && metadata.id() == decision.entity()) {
|
||||
for (var value : metadata.packedItems()) {
|
||||
if (value.id() == 0 && value.serializer() == net.minecraft.network.syncher.EntityDataSerializers.BYTE
|
||||
&& value.value() instanceof Byte flags) {
|
||||
mask = (flags & 0x20) != 0 ? mask | INVISIBLE : mask & ~INVISIBLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mask == 0) { blocked.remove(key); } else { blocked.put(key, mask); }
|
||||
var label = decisions.get(view.holder()).labels().get(viewer);
|
||||
if (mask != 0 && label != null && retired.add(key)) { removals.put(decision, label); }
|
||||
}
|
||||
}
|
||||
|
||||
private boolean send(Player viewer, Object raw) {
|
||||
try { protocol.sendServerPacket(viewer, wrap(raw), false); return true; }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); return false; }
|
||||
}
|
||||
|
||||
private boolean begin(Runnable retry) {
|
||||
if (operating) { pending.add(retry); return false; }
|
||||
operating = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void finish() {
|
||||
operating = false;
|
||||
if (draining) { return; }
|
||||
// Reentrant lifecycle operations wait until the transport attempt AND its failure/
|
||||
// resource bookkeeping finish. Cleanup is thus ordered after every possibly escaped
|
||||
// old packet, and a queued rename cannot continue an uncertain spawn. Never replay it.
|
||||
draining = true;
|
||||
try {
|
||||
while (!pending.isEmpty()) {
|
||||
try { pending.removeFirst().run(); }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} finally { draining = false; }
|
||||
}
|
||||
|
||||
private static PacketContainer wrap(Object raw) {
|
||||
PacketType type;
|
||||
if (raw instanceof ClientboundBundlePacket) { type = PacketType.Play.Server.BUNDLE; }
|
||||
else if (raw instanceof ClientboundPlayerInfoUpdatePacket) { type = PacketType.Play.Server.PLAYER_INFO; }
|
||||
else if (raw instanceof ClientboundUpdateAttributesPacket) { type = PacketType.Play.Server.UPDATE_ATTRIBUTES; }
|
||||
else if (raw instanceof ClientboundAddEntityPacket) { type = PacketType.Play.Server.SPAWN_ENTITY; }
|
||||
else if (raw instanceof ClientboundSetEntityDataPacket) { type = PacketType.Play.Server.ENTITY_METADATA; }
|
||||
else if (raw instanceof ClientboundTeleportEntityPacket) { type = PacketType.Play.Server.ENTITY_TELEPORT; }
|
||||
else if (raw instanceof ClientboundRemoveEntitiesPacket) { type = PacketType.Play.Server.ENTITY_DESTROY; }
|
||||
else { throw new IllegalArgumentException("Unsupported presentation packet"); }
|
||||
return new PacketContainer(type, raw);
|
||||
}
|
||||
|
||||
private static boolean sameSession(View first, View second) {
|
||||
return second != null && first.holder().equals(second.holder())
|
||||
&& first.session().equals(second.session()) && first.character().equals(second.character());
|
||||
}
|
||||
|
||||
private void report(Throwable failure) {
|
||||
if (warnings < 8) {
|
||||
warnings++;
|
||||
try { diagnostics.accept(failure); } catch (RuntimeException | LinkageError ignored) { /* Cleanup must continue. */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Override public synchronized void close() {
|
||||
if (!begin(this::close)) { return; }
|
||||
try {
|
||||
if (closed) { return; }
|
||||
closed = true;
|
||||
deliveries.clear();
|
||||
if (task != null) {
|
||||
try { task.cancel(); } catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
if (installed) {
|
||||
try { protocol.removePacketListener(listener); } catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
for (var state : List.copyOf(states.values())) { clear(state.view); }
|
||||
} finally { finish(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Session-owned output only. Withdrawal must invalidate decisions even when native cleanup fails. */
|
||||
public interface SessionPresentation {
|
||||
SessionPresentation NONE = new SessionPresentation() {
|
||||
@Override public void activate(Player player, UUID session, CharacterRecord record) { }
|
||||
@Override public void withdraw(UUID player, UUID session) { }
|
||||
};
|
||||
void activate(Player player, UUID session, CharacterRecord record);
|
||||
/** May be called by a failed worker completion: no worker Bukkit access is permitted. */
|
||||
void withdraw(UUID player, UUID session);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ public final class CharacterProgress {
|
||||
|
||||
private final UUID characterId;
|
||||
private final ProgressionRules rules;
|
||||
private final BigDecimal nativeHealthLimit;
|
||||
private final EnumMap<Stat, BigInteger> stats = new EnumMap<>(Stat.class);
|
||||
private int level = 1;
|
||||
private BigInteger experience = BigInteger.ZERO;
|
||||
@@ -26,11 +27,19 @@ public final class CharacterProgress {
|
||||
private BigInteger revision = BigInteger.ZERO;
|
||||
private BigDecimal health = BigDecimal.TEN;
|
||||
|
||||
/** Uses the pinned runtime's default ceiling. Runtime adapters must supply their actual limit. */
|
||||
public CharacterProgress(UUID characterId, ProgressionRules rules) {
|
||||
this(characterId, rules, new BigDecimal("1024"));
|
||||
}
|
||||
|
||||
public CharacterProgress(UUID characterId, ProgressionRules rules, BigDecimal nativeHealthLimit) {
|
||||
this.characterId = Objects.requireNonNull(characterId);
|
||||
this.rules = Objects.requireNonNull(rules);
|
||||
this.nativeHealthLimit = Objects.requireNonNull(nativeHealthLimit);
|
||||
if (nativeHealthLimit.signum() <= 0) throw new IllegalArgumentException("Native health limit must be positive");
|
||||
this.points = rules.startingPoints();
|
||||
for (Stat stat : Stat.values()) stats.put(stat, BigInteger.ZERO);
|
||||
this.health = maximumHealth();
|
||||
}
|
||||
|
||||
public synchronized Snapshot snapshot() {
|
||||
@@ -47,9 +56,10 @@ public final class CharacterProgress {
|
||||
if (!revision.equals(expectedRevision)) return Purchase.STALE_REVISION;
|
||||
if (health.signum() == 0) return Purchase.NOT_ALIVE;
|
||||
if (points.signum() == 0) return Purchase.NO_POINTS;
|
||||
BigDecimal previousMaximum = maximumHealth();
|
||||
stats.put(stat, stats.get(stat).add(BigInteger.ONE));
|
||||
points = points.subtract(BigInteger.ONE);
|
||||
if (stat == Stat.CON) health = health.add(BigDecimal.ONE);
|
||||
if (stat == Stat.CON) health = health.add(maximumHealth().subtract(previousMaximum));
|
||||
revision = revision.add(BigInteger.ONE);
|
||||
return Purchase.APPLIED;
|
||||
}
|
||||
@@ -80,6 +90,6 @@ public final class CharacterProgress {
|
||||
}
|
||||
|
||||
private BigDecimal maximumHealth() {
|
||||
return new BigDecimal(stats.get(Stat.CON).add(BigInteger.TEN));
|
||||
return new BigDecimal(stats.get(Stat.CON).add(BigInteger.TEN)).min(nativeHealthLimit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.util.UUID;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/** Main-thread holder/session proof for optional Adventure mode; the receipt must already be saved. */
|
||||
public final class AdventureModeLease implements org.bukkit.event.Listener {
|
||||
@org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void changed(org.bukkit.event.player.PlayerGameModeChangeEvent event) {
|
||||
if (event.isCancelled()) return;
|
||||
var player = event.getPlayer();
|
||||
var mark = read(player);
|
||||
// Events precede the write. A currently non-Adventure mode proves a previous
|
||||
// external change already happened, even when this new request returns to Adventure.
|
||||
// A lone external change is also detected directly by restore(). Never infer success
|
||||
// from this event's requested value, which a later listener may still cancel.
|
||||
if (mark != null && mark.phase() == Phase.APPLIED && player.getGameMode() != GameMode.ADVENTURE) {
|
||||
write(player, new Mark(mark.session(), mark.previous(), Phase.RELEASED));
|
||||
}
|
||||
}
|
||||
private static final NamespacedKey KEY = new NamespacedKey("fantasystick", "adventure_session");
|
||||
private enum Phase { APPLYING, APPLIED, RESTORING, RELEASED }
|
||||
private record Mark(UUID session, String previous, Phase phase) {
|
||||
boolean matches(UUID expected, String original) { return session.equals(expected) && previous.equals(original); }
|
||||
}
|
||||
|
||||
public boolean available(Player player) {
|
||||
var mark = read(player);
|
||||
return !player.getPersistentDataContainer().has(KEY) || mark != null && mark.phase() == Phase.RELEASED;
|
||||
}
|
||||
|
||||
public boolean enter(Player player, UUID session, String previous) {
|
||||
if (previous == null) return true;
|
||||
var existing = read(player);
|
||||
if (player.getPersistentDataContainer().has(KEY) && (existing == null || existing.phase() != Phase.RELEASED)) {
|
||||
return existing != null && existing.matches(session, previous) && existing.phase() == Phase.APPLIED
|
||||
&& player.getGameMode() == GameMode.ADVENTURE;
|
||||
}
|
||||
if (player.getGameMode() != GameMode.valueOf(previous)) return false;
|
||||
write(player, new Mark(session, previous, Phase.APPLYING));
|
||||
player.setGameMode(GameMode.ADVENTURE);
|
||||
if (player.getGameMode() != GameMode.ADVENTURE) {
|
||||
write(player, new Mark(session, previous, Phase.RELEASED));
|
||||
return false;
|
||||
}
|
||||
write(player, new Mark(session, previous, Phase.APPLIED));
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean restore(Player player, UUID session, String previous) {
|
||||
if (previous == null) return true;
|
||||
var mark = read(player);
|
||||
if (mark == null || !mark.matches(session, previous)) return false;
|
||||
if (mark.phase() == Phase.RELEASED) return true;
|
||||
if (mark.phase() != Phase.APPLIED) return false; // Interrupted setter is not restoration proof.
|
||||
if (player.getGameMode() != GameMode.ADVENTURE) {
|
||||
write(player, new Mark(session, previous, Phase.RELEASED));
|
||||
return true; // A later external/admin change is not ours to undo.
|
||||
}
|
||||
write(player, new Mark(session, previous, Phase.RESTORING));
|
||||
player.setGameMode(GameMode.valueOf(previous));
|
||||
if (player.getGameMode() == GameMode.ADVENTURE && !previous.equals("ADVENTURE")) {
|
||||
write(player, new Mark(session, previous, Phase.APPLIED));
|
||||
return false; // Native veto: unchanged and still owned, not successful restoration.
|
||||
}
|
||||
write(player, new Mark(session, previous, Phase.RELEASED));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Mark read(Player player) {
|
||||
var data = player.getPersistentDataContainer();
|
||||
if (!data.has(KEY, PersistentDataType.STRING)) return null;
|
||||
try {
|
||||
String[] fields = data.get(KEY, PersistentDataType.STRING).split("\\|", -1);
|
||||
if (fields.length != 4 || !fields[0].equals("1")) return null;
|
||||
var session = UUID.fromString(fields[1]);
|
||||
if (!session.toString().equals(fields[1])) return null;
|
||||
GameMode.valueOf(fields[2]);
|
||||
return new Mark(session, fields[2], Phase.valueOf(fields[3]));
|
||||
} catch (IllegalArgumentException invalid) { return null; }
|
||||
}
|
||||
|
||||
private static void write(Player player, Mark mark) {
|
||||
player.getPersistentDataContainer().set(KEY, PersistentDataType.STRING,
|
||||
"1|" + mark.session() + "|" + mark.previous() + "|" + mark.phase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Internal server-thread input port for book/combat/ability adapters, not an add-on API.
|
||||
* Containment of vanilla item behavior is separate from executing an ability. Recipients
|
||||
* must revalidate after deferred work; this notification is never durable cast authority.
|
||||
*/
|
||||
public record ControlInput(Player player, EquipmentSessions.Active session, int slot, String ability,
|
||||
Kind kind, Gesture gesture, Entity target, int heldTicks, float attackStrength,
|
||||
BooleanSupplier validity) {
|
||||
public enum Kind { BOOK, BASIC_ATTACK, ABILITY }
|
||||
public enum Gesture { USE, ATTACK, DRAW_RELEASE }
|
||||
|
||||
public ControlInput {
|
||||
Objects.requireNonNull(player);
|
||||
Objects.requireNonNull(session);
|
||||
Objects.requireNonNull(ability);
|
||||
Objects.requireNonNull(kind);
|
||||
Objects.requireNonNull(gesture);
|
||||
Objects.requireNonNull(validity);
|
||||
if (slot < 0 || slot > 8 || heldTicks < 0 || !Float.isFinite(attackStrength)
|
||||
|| attackStrength < 0 || attackStrength > 1) throw new IllegalArgumentException("Invalid control input");
|
||||
}
|
||||
|
||||
public boolean stillCurrent() { return validity.getAsBoolean(); }
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import games.dmg.fantasystick.persistence.EquipmentSessionStore;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
|
||||
/** Server-thread command entry; persistence callbacks never access senders or players. */
|
||||
public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
public static final String PERMISSION = "fantasystick.admin";
|
||||
public record Failure(UUID player, String operation, Throwable cause) { }
|
||||
private final EquipmentSessionStore receipts;
|
||||
private final EquipmentSessions sessions;
|
||||
private final Server server;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<Failure> diagnostics;
|
||||
private volatile boolean closed;
|
||||
private games.dmg.fantasystick.persistence.AdventureSettings settings;
|
||||
|
||||
public EquipmentAdminCommand(EquipmentSessionStore receipts, EquipmentSessions sessions, Server server,
|
||||
Consumer<Runnable> nextTick, Consumer<Failure> diagnostics) {
|
||||
this.receipts = Objects.requireNonNull(receipts);
|
||||
this.sessions = Objects.requireNonNull(sessions);
|
||||
this.server = Objects.requireNonNull(server);
|
||||
this.nextTick = Objects.requireNonNull(nextTick);
|
||||
this.diagnostics = Objects.requireNonNull(diagnostics);
|
||||
}
|
||||
|
||||
public EquipmentAdminCommand(EquipmentSessionStore receipts, EquipmentSessions sessions, Server server,
|
||||
Consumer<Runnable> nextTick, Consumer<Failure> diagnostics,
|
||||
games.dmg.fantasystick.persistence.AdventureSettings settings) {
|
||||
this(receipts, sessions, server, nextTick, diagnostics);
|
||||
this.settings = Objects.requireNonNull(settings);
|
||||
}
|
||||
|
||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (closed) return true;
|
||||
if (!sender.hasPermission(PERMISSION)) {
|
||||
sender.sendMessage("You need fantasystick.admin to administer Fantasy Stick.");
|
||||
return true;
|
||||
}
|
||||
if (args.length > 0 && args[0].equals("config")) {
|
||||
configuration(sender, args);
|
||||
return true;
|
||||
}
|
||||
UUID owner;
|
||||
try {
|
||||
if (args.length != 2 || !(args[0].equals("inspect") || args[0].equals("recover"))) {
|
||||
throw new IllegalArgumentException("Invalid command shape");
|
||||
}
|
||||
owner = UUID.fromString(args[1]);
|
||||
if (!owner.toString().equalsIgnoreCase(args[1])) throw new IllegalArgumentException("Noncanonical UUID shape");
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
sender.sendMessage("Usage: /fantasystick <inspect|recover> <player-uuid> (full UUID required)");
|
||||
return true;
|
||||
}
|
||||
if (args[0].equals("recover")) {
|
||||
var player = server.getPlayer(owner);
|
||||
if (player == null || !player.isOnline()) {
|
||||
sender.sendMessage("Recovery refused: target " + owner + " must be online. No items changed.");
|
||||
return true;
|
||||
}
|
||||
sessions.recover(player);
|
||||
sender.sendMessage("Validated equipment recovery requested for " + owner
|
||||
+ ". This is not confirmation of restoration; ambiguous items and receipts are retained.");
|
||||
return true;
|
||||
}
|
||||
receipts.find(owner).whenComplete((state, failure) -> {
|
||||
if (failure != null) report(owner, "inspect", failure);
|
||||
if (closed) return;
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (closed || !sender.hasPermission(PERMISSION)) return;
|
||||
if (sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return;
|
||||
if (failure != null) {
|
||||
sender.sendMessage("Equipment inspection failed for " + owner + "; retained state requires inspection. See server diagnostics.");
|
||||
return;
|
||||
}
|
||||
sender.sendMessage("Equipment receipt player=" + owner + " (file and native observations are not atomic)");
|
||||
if (state.isEmpty()) sender.sendMessage("Saved receipt: none; pending=none; last exit=none.");
|
||||
else {
|
||||
var saved = state.orElseThrow();
|
||||
var pending = saved.pending();
|
||||
sender.sendMessage(pending == null ? "pending=none" : "pending session=" + pending.sessionId()
|
||||
+ " character=" + pending.characterId() + " prepared=" + pending.preparedAt());
|
||||
var exit = saved.lastExit();
|
||||
sender.sendMessage(exit == null ? "last exit=none; deadline=none" : "last exit session=" + exit.sessionId()
|
||||
+ " character=" + exit.characterId() + " exited=" + exit.exitedAt() + " deadline=" + exit.deadline());
|
||||
}
|
||||
var player = server.getPlayer(owner);
|
||||
if (player == null || !player.isOnline()) sender.sendMessage("Native state: offline; not inspected.");
|
||||
else {
|
||||
var marker = EquipmentSessionMarker.read(player);
|
||||
sender.sendMessage("Online native marker=" + marker.map(token -> "session=" + token.session()
|
||||
+ " character=" + token.character() + " phase=" + token.phase()).orElseGet(() ->
|
||||
EquipmentSessionMarker.present(player) ? "malformed (retained)" : "none"));
|
||||
sender.sendMessage("Online active=" + sessions.active(owner).map(active -> "session=" + active.session()
|
||||
+ " character=" + active.character()).orElse("none"));
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException rejected) { report(owner, "inspect-response", rejected); }
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
private void configuration(CommandSender sender, String[] args) {
|
||||
if (args.length < 2 || args.length > 3 || !args[1].equals("adventure-mode")
|
||||
|| args.length == 3 && !args[2].equals("true") && !args[2].equals("false")) {
|
||||
sender.sendMessage("Usage: /fantasystick config adventure-mode [true|false]");
|
||||
return;
|
||||
}
|
||||
if (settings == null) { sender.sendMessage("Adventure configuration is unavailable."); return; }
|
||||
if (args.length == 2) {
|
||||
sender.sendMessage("adventure-mode=" + settings.enabled() + " (applies to new sessions only)");
|
||||
return;
|
||||
}
|
||||
settings.set(Boolean.parseBoolean(args[2])).whenComplete((saved, failure) -> {
|
||||
if (failure != null) report(null, "config-adventure-mode", failure);
|
||||
if (closed) return;
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (closed || !sender.hasPermission(PERMISSION)
|
||||
|| sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return;
|
||||
sender.sendMessage(failure == null
|
||||
? "Saved adventure-mode=" + saved + " for new sessions only; active sessions are unchanged."
|
||||
: "Adventure configuration save failed; the effective setting is unchanged.");
|
||||
});
|
||||
} catch (RuntimeException rejected) { report(null, "config-response", rejected); }
|
||||
});
|
||||
}
|
||||
|
||||
private void report(UUID owner, String operation, Throwable cause) {
|
||||
try { diagnostics.accept(new Failure(owner, operation, cause)); }
|
||||
catch (RuntimeException ignored) { /* Diagnostics cannot authorize recovery. */ }
|
||||
}
|
||||
|
||||
// Never fall back to Bukkit's online-player-name suggestions for a UUID-only admin interface.
|
||||
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
return List.of();
|
||||
}
|
||||
@Override public void close() { closed = true; }
|
||||
}
|
||||
@@ -0,0 +1,890 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import games.dmg.fantasystick.crafting.ManualDropDelivery;
|
||||
import games.dmg.fantasystick.crafting.PlayerSheetDrops;
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.items.EquipmentStorage;
|
||||
import games.dmg.fantasystick.items.SessionControls;
|
||||
import io.papermc.paper.event.player.PlayerInventorySlotChangeEvent;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryAction;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCreativeEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.event.inventory.InventoryType;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/** Server-thread equipment bridge. The scheduler must defer, never execute inline. */
|
||||
public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
private final EquipmentSessions sessions;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<EquipmentSessions.Failure> diagnostics;
|
||||
private final CharacterSheets sheets = new CharacterSheets();
|
||||
private final SessionControls controls = new SessionControls();
|
||||
private static final class Intent { boolean started; }
|
||||
private final Map<UUID, Intent> swaps = new HashMap<>();
|
||||
private final Map<UUID, UUID> observed = new HashMap<>();
|
||||
private final Map<UUID, Object> queued = new HashMap<>();
|
||||
private final Set<UUID> writing = new HashSet<>();
|
||||
private final Map<UUID, BoxMove> moves = new HashMap<>();
|
||||
private static final class BoxMove {
|
||||
final Player player;
|
||||
final InventoryView view;
|
||||
final EquipmentSessions.Active active;
|
||||
final ItemStack box;
|
||||
final ItemStack control;
|
||||
boolean issued;
|
||||
boolean placing;
|
||||
BoxMove(Player player, InventoryView view, EquipmentSessions.Active active, ItemStack box) {
|
||||
this.player = player; this.view = view; this.active = active; this.box = box.clone();
|
||||
control = new ItemStack(org.bukkit.Material.GRAY_DYE);
|
||||
var meta = control.getItemMeta();
|
||||
meta.displayName(net.kyori.adventure.text.Component.text("Move Fantasy Storage Box"));
|
||||
meta.setMaxStackSize(1);
|
||||
var data = meta.getPersistentDataContainer();
|
||||
data.set(new NamespacedKey("fantasystick", "control_move_version"), PersistentDataType.INTEGER, 1);
|
||||
data.set(new NamespacedKey("fantasystick", "control_move_owner"), PersistentDataType.STRING, active.player().toString());
|
||||
data.set(new NamespacedKey("fantasystick", "control_move_session"), PersistentDataType.STRING, active.session().toString());
|
||||
data.set(new NamespacedKey("fantasystick", "control_move_token"), PersistentDataType.STRING, UUID.randomUUID().toString());
|
||||
control.setItemMeta(meta);
|
||||
}
|
||||
}
|
||||
private boolean closed;
|
||||
private Consumer<ControlInput> inputs = ignored -> { };
|
||||
private record Draw(Player player, ItemStack item, EquipmentSessions.SelectedControl selected) { }
|
||||
private final Map<UUID, Draw> draws = new HashMap<>();
|
||||
|
||||
public EquipmentSessionEvents(EquipmentSessions sessions, Consumer<Runnable> nextTick) {
|
||||
this(sessions, nextTick, failure -> System.getLogger(EquipmentSessionEvents.class.getName())
|
||||
.log(System.Logger.Level.WARNING, "Equipment event failure for " + failure.player(), failure.cause()));
|
||||
}
|
||||
|
||||
/** Diagnostics report contained scheduler failures and possibly exposed drop outcomes; never throw. */
|
||||
public EquipmentSessionEvents(EquipmentSessions sessions, Consumer<Runnable> nextTick,
|
||||
Consumer<EquipmentSessions.Failure> diagnostics) {
|
||||
this.sessions = Objects.requireNonNull(sessions);
|
||||
this.nextTick = Objects.requireNonNull(nextTick);
|
||||
this.diagnostics = Objects.requireNonNull(diagnostics);
|
||||
sessions.attachCursorCustody(this::cancelCustody);
|
||||
}
|
||||
|
||||
/** The input recipient belongs to this plugin; it does not authorize vanilla item use. */
|
||||
public EquipmentSessionEvents(EquipmentSessions sessions, Consumer<Runnable> nextTick,
|
||||
Consumer<EquipmentSessions.Failure> diagnostics, Consumer<ControlInput> inputs) {
|
||||
this(sessions, nextTick, diagnostics);
|
||||
this.inputs = Objects.requireNonNull(inputs);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void death(org.bukkit.event.entity.PlayerDeathEvent event) {
|
||||
if (closed) return;
|
||||
UUID owner = event.getEntity().getUniqueId();
|
||||
queued.remove(owner);
|
||||
swaps.remove(owner);
|
||||
sessions.cancelEntry(owner);
|
||||
boolean reserved = writing.add(owner);
|
||||
try { sessions.defeat(event); }
|
||||
finally { if (reserved) writing.remove(owner); }
|
||||
}
|
||||
|
||||
// Only actual ordinary death invalidates context; preserve a prior cancellation entirely.
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void ordinaryDeath(org.bukkit.event.entity.PlayerDeathEvent event) {
|
||||
if (closed) return;
|
||||
invalidate(event.getEntity());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void respawn(org.bukkit.event.player.PlayerRespawnEvent event) {
|
||||
if (!closed) invalidate(event.getPlayer());
|
||||
}
|
||||
|
||||
private void invalidate(Player player) {
|
||||
UUID owner = player.getUniqueId();
|
||||
queued.remove(owner);
|
||||
swaps.remove(owner);
|
||||
observed.put(owner, sheets.identify(player.getInventory().getItemInOffHand()).orElse(null));
|
||||
sessions.invalidateContext(owner);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void changed(PlayerInventorySlotChangeEvent event) { reconcile(event.getPlayer()); }
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void join(org.bukkit.event.player.PlayerJoinEvent event) {
|
||||
if (closed) return;
|
||||
var player = event.getPlayer();
|
||||
UUID owner = player.getUniqueId();
|
||||
queued.remove(owner);
|
||||
observed.put(owner, sheets.identify(player.getInventory().getItemInOffHand()).orElse(null));
|
||||
sessions.arrive(player);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void quit(org.bukkit.event.player.PlayerQuitEvent event) {
|
||||
var player = event.getPlayer();
|
||||
UUID owner = player.getUniqueId();
|
||||
queued.remove(owner);
|
||||
swaps.remove(owner);
|
||||
boolean reserved = writing.add(owner);
|
||||
try { sessions.invalidateContext(owner); sessions.exit(player); }
|
||||
finally { if (reserved) writing.remove(owner); observed.remove(owner); }
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void swap(org.bukkit.event.player.PlayerSwapHandItemsEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
int slot = player.getInventory().getHeldItemSlot();
|
||||
if (reservedExchange(player, slot)) {
|
||||
event.setCancelled(true);
|
||||
// Purpur 2618 snapshots the proposed hand stacks BEFORE dispatch. Never let its
|
||||
// continuation write the old fantasy control over the restored ordinary stack.
|
||||
if (Objects.equals(event.getMainHandItem(), player.getInventory().getItemInOffHand())
|
||||
&& Objects.equals(event.getOffHandItem(), player.getInventory().getItem(slot))) {
|
||||
exchange(player, slot, null);
|
||||
}
|
||||
} else if (special(event.getMainHandItem()) || special(event.getOffHandItem())
|
||||
|| special(player.getInventory().getItemInMainHand()) || special(player.getInventory().getItemInOffHand())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void click(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) return;
|
||||
if (ownInventory(player, event.getClickedInventory()) && event.getSlot() == 40
|
||||
&& (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP)
|
||||
&& (event.getAction() == InventoryAction.DROP_ONE_SLOT || event.getAction() == InventoryAction.DROP_ALL_SLOT)
|
||||
&& sheets.identify(event.getCurrentItem()).isPresent()) {
|
||||
// LivingEntity.drop's cancelled-source fallback adds to inventory, not the offhand;
|
||||
// at full capacity it discards leftovers. Keep custody until detached insertion succeeds.
|
||||
event.setCancelled(true);
|
||||
dropSheet(player, event.getView(), event.getClick() == ClickType.CONTROL_DROP);
|
||||
return;
|
||||
}
|
||||
int slot = -1;
|
||||
if (event.getClickedInventory() instanceof PlayerInventory) {
|
||||
if (event.getSlot() == 40 && event.getClick() == ClickType.NUMBER_KEY) slot = event.getHotbarButton();
|
||||
else if (event.getClick() == ClickType.SWAP_OFFHAND) slot = event.getSlot();
|
||||
}
|
||||
if (event.getAction() == InventoryAction.HOTBAR_SWAP && reservedExchange(player, slot)) {
|
||||
event.setCancelled(true);
|
||||
exchange(player, slot, event.getView());
|
||||
return;
|
||||
}
|
||||
if (pickupClaim(event.getCursor(), "control_move_") && !cursorIndependent(event)) {
|
||||
event.setCancelled(true);
|
||||
if (!(event instanceof InventoryCreativeEvent)
|
||||
&& (event.getClick() == ClickType.LEFT || event.getClick() == ClickType.RIGHT)) {
|
||||
if (event.getRawSlot() == -999) cancelMove(player.getUniqueId());
|
||||
else if (ownInventory(player, event.getClickedInventory()) && event.getSlot() >= 9 && event.getSlot() < 36
|
||||
&& (event.getAction() == InventoryAction.PLACE_ALL || event.getAction() == InventoryAction.PLACE_ONE
|
||||
|| event.getAction() == InventoryAction.SWAP_WITH_CURSOR)) {
|
||||
placeMove(player, event.getView(), event.getSlot(), event.getCursor());
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (box(event.getCurrentItem()) != null && empty(event.getCursor())
|
||||
&& ownInventory(player, event.getClickedInventory()) && event.getSlot() >= 9 && event.getSlot() < 36
|
||||
&& !(event instanceof InventoryCreativeEvent)
|
||||
&& (event.getClick() == ClickType.LEFT || event.getClick() == ClickType.RIGHT)
|
||||
&& (event.getAction() == InventoryAction.PICKUP_ALL || event.getAction() == InventoryAction.PICKUP_HALF)) {
|
||||
event.setCancelled(true);
|
||||
beginMove(player, event.getView(), event.getCurrentItem());
|
||||
return;
|
||||
}
|
||||
if (blockedClick(player, event)) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void recipeBook(com.destroystokyo.paper.event.player.PlayerRecipeBookClickEvent event) {
|
||||
var player = event.getPlayer();
|
||||
// Native recipe-book placement can pull directly from the hotbar without a click
|
||||
// event. Exact recipe ingredients also bypass vanilla's custom-name exclusion.
|
||||
if (Arrays.stream(player.getOpenInventory().getTopInventory().getContents()).anyMatch(this::special)) {
|
||||
event.setCancelled(true); return;
|
||||
}
|
||||
var recipe = player.getServer().getRecipe(event.getRecipe());
|
||||
java.util.Collection<org.bukkit.inventory.RecipeChoice> choices;
|
||||
if (recipe instanceof org.bukkit.inventory.ShapedRecipe shaped) choices = shaped.getChoiceMap().values();
|
||||
else if (recipe instanceof org.bukkit.inventory.ShapelessRecipe shapeless) choices = shapeless.getChoiceList();
|
||||
else if (recipe instanceof org.bukkit.inventory.CookingRecipe<?> cooking) choices = java.util.List.of(cooking.getInputChoice());
|
||||
else return; // Other recipe types do not use these native auto-fill routes.
|
||||
for (var item : player.getInventory().getStorageContents()) {
|
||||
if (!special(item)) continue;
|
||||
boolean ordinaryEligible = net.minecraft.world.entity.player.Inventory.isUsableForCrafting(
|
||||
org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(item));
|
||||
if (choices.stream().filter(Objects::nonNull).anyMatch(choice -> choice.test(item)
|
||||
&& (ordinaryEligible || choice instanceof org.bukkit.inventory.RecipeChoice.ExactChoice))) {
|
||||
event.setCancelled(true); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean cursorIndependent(InventoryClickEvent event) {
|
||||
return switch (event.getAction()) {
|
||||
case DROP_ONE_SLOT, DROP_ALL_SLOT, MOVE_TO_OTHER_INVENTORY, HOTBAR_SWAP -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean blockedClick(Player player, InventoryClickEvent event) {
|
||||
var current = event.getCurrentItem();
|
||||
var cursor = pickupClaim(event.getCursor(), "control_move_") && cursorIndependent(event) ? null : event.getCursor();
|
||||
var inventory = event.getClickedInventory();
|
||||
int slot = event.getSlot();
|
||||
if (event.getSlotType() == InventoryType.SlotType.RESULT
|
||||
&& Arrays.stream(event.getView().getTopInventory().getContents()).anyMatch(this::special)) return true;
|
||||
if (control(current) || control(cursor)) return true;
|
||||
if (event instanceof InventoryCreativeEvent && (special(current) || special(cursor))) return true;
|
||||
// Native pickup swaps the active sheet onto the cursor and its own box into offhand.
|
||||
// Reconciliation then restores into that freed offhand, without needing main capacity.
|
||||
if (ownInventory(player, inventory) && slot == 40
|
||||
&& event.getAction() == InventoryAction.SWAP_WITH_CURSOR
|
||||
&& (event.getClick() == ClickType.LEFT || event.getClick() == ClickType.RIGHT)) {
|
||||
var active = sessions.active(player.getUniqueId()).orElse(null);
|
||||
var heldBox = box(cursor);
|
||||
if (active != null && heldBox != null && heldBox.owner().equals(active.player())
|
||||
&& heldBox.session().equals(active.session())
|
||||
&& sheets.identify(current).filter(active.character()::equals).isPresent()) return false;
|
||||
}
|
||||
if (event.getClick() == ClickType.NUMBER_KEY || event.getClick() == ClickType.SWAP_OFFHAND) {
|
||||
int source = event.getClick() == ClickType.SWAP_OFFHAND ? 40 : event.getHotbarButton();
|
||||
if (source < 0) return false;
|
||||
var hidden = player.getInventory().getItem(source);
|
||||
return special(current) || special(hidden)
|
||||
|| destinationBlocked(player, inventory, slot, hidden)
|
||||
|| destinationBlocked(player, player.getInventory(), source, current);
|
||||
}
|
||||
// Normal pickup is exclusively the bound move-control path above. No unsupported
|
||||
// action may fall back to vanilla taking the genuine box onto the cursor.
|
||||
if (box(current) != null) return true;
|
||||
if (box(cursor) != null && destinationBlocked(player, inventory, slot, cursor)) return true;
|
||||
if (event.getAction() == InventoryAction.COLLECT_TO_CURSOR && !empty(cursor)) {
|
||||
for (var item : event.getView().getTopInventory().getContents()) if (special(item) && item.isSimilar(cursor)) return true;
|
||||
for (var item : player.getInventory().getContents()) if (special(item) && item.isSimilar(cursor)) return true;
|
||||
}
|
||||
if (!active(player)) return false;
|
||||
if (ownInventory(player, inventory) && slot >= 0 && slot < 9) return true;
|
||||
if (event.isShiftClick() && !empty(current)) {
|
||||
if (ownInventory(player, inventory) && event.getView().getType() == InventoryType.CRAFTING && slot >= 9 && slot < 36) {
|
||||
// Native InventoryMenu tries armor first, otherwise routes main -> hotbar.
|
||||
return !(cosmetic(current) && !forbiddenEquip(current) && empty(player.getInventory().getHelmet()));
|
||||
}
|
||||
if (!ownInventory(player, inventory) && mainCapacity(player, current) < current.getAmount()) return true;
|
||||
}
|
||||
return destinationBlocked(player, inventory, slot, cursor);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void drag(InventoryDragEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) return;
|
||||
if (control(event.getOldCursor())) {
|
||||
event.setCancelled(true);
|
||||
if (pickupClaim(event.getOldCursor(), "control_move_") && event.getNewItems().size() == 1) {
|
||||
int raw = event.getNewItems().keySet().iterator().next();
|
||||
int slot = event.getView().convertSlot(raw);
|
||||
if (ownInventory(player, event.getView().getInventory(raw)) && slot >= 9 && slot < 36) {
|
||||
// QUICK_CRAFT temporarily debits carried before event dispatch; DENY
|
||||
// restores it afterwards. Confirm that live cursor only in the deferred task.
|
||||
placeMove(player, event.getView(), slot, event.getOldCursor());
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (var entry : event.getNewItems().entrySet()) {
|
||||
int raw = entry.getKey();
|
||||
if (special(event.getView().getItem(raw)) || destinationBlocked(player,
|
||||
event.getView().getInventory(raw), event.getView().convertSlot(raw), entry.getValue())) {
|
||||
event.setCancelled(true); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void drop(org.bukkit.event.player.PlayerDropItemEvent event) {
|
||||
if (special(event.getItemDrop().getItemStack())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
// isCancelled() is only the block decision on this event. Denying item use must
|
||||
// also run for RIGHT_CLICK_AIR / an existing block veto, without changing that veto.
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void use(org.bukkit.event.player.PlayerInteractEvent event) {
|
||||
boolean allowed = event.useItemInHand() != org.bukkit.event.Event.Result.DENY;
|
||||
if (special(event.getItem()) || active(event.getPlayer()) && forbiddenEquip(event.getItem())) {
|
||||
// Do not veto an unrelated door/chest interaction or undo another plugin's block veto.
|
||||
event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
|
||||
}
|
||||
if (allowed && event.getHand() == EquipmentSlot.HAND && (event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_AIR
|
||||
|| event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK)) {
|
||||
var selected = sessions.selectedControl(event.getPlayer(), event.getItem()).orElse(null);
|
||||
if (selected != null && useGesture(selected)) emit(event.getPlayer(), event.getItem(), selected,
|
||||
ControlInput.Gesture.USE, null, 0, 0);
|
||||
else if (selected != null && selected.ability().equals("longbow")) beginDraw(event.getPlayer(), event.getItem(), selected);
|
||||
}
|
||||
}
|
||||
|
||||
private void beginDraw(Player player, ItemStack item, EquipmentSessions.SelectedControl selected) {
|
||||
UUID owner = player.getUniqueId();
|
||||
if (closed || draws.containsKey(owner) || player.hasActiveItem()) return;
|
||||
var draw = new Draw(player, item.clone(), selected);
|
||||
draws.put(owner, draw);
|
||||
try {
|
||||
// Keep the native bow animation/timing, without BowItem.use's ammunition lookup.
|
||||
player.startUsingItem(EquipmentSlot.HAND);
|
||||
if (closed || draws.get(owner) != draw || !sessions.selectedControl(player, draw.item()).filter(selected::equals).isPresent()
|
||||
|| !draw.item().equals(player.getActiveItem())) cancelDraw(draw);
|
||||
} catch (RuntimeException failure) {
|
||||
cancelDraw(draw);
|
||||
report(owner, selected.session().session(), failure);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void release(io.papermc.paper.event.player.PlayerStopUsingItemEvent event) {
|
||||
var player = event.getPlayer();
|
||||
UUID owner = player.getUniqueId();
|
||||
var draw = draws.get(owner);
|
||||
if (draw != null && draw.player() != player) draw = null;
|
||||
if (draw != null) draws.remove(owner, draw); // One-use, before a native setter or recipient can reenter.
|
||||
try {
|
||||
boolean matching = draw != null && draw.item().equals(event.getItem())
|
||||
&& draw.item().equals(player.getActiveItem()) && event.getTicksHeldFor() >= 0;
|
||||
// Purpur 2618 reloads LivingEntity.useItem AFTER this event, then calls releaseUsing.
|
||||
// Clear it first: cancelling EntityShootBowEvent alone is too late to own ammo draw.
|
||||
if (special(event.getItem()) && event.getItem().equals(player.getActiveItem())) player.clearActiveItem();
|
||||
if (matching) emit(player, draw.item(), draw.selected(), ControlInput.Gesture.DRAW_RELEASE,
|
||||
null, event.getTicksHeldFor(), 0);
|
||||
} catch (RuntimeException failure) {
|
||||
// Unknown native state is not a completed cast or authority to replay an input.
|
||||
report(owner, draw == null ? null : draw.selected().session().session(), failure);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void held(org.bukkit.event.player.PlayerItemHeldEvent event) {
|
||||
var draw = draws.get(event.getPlayer().getUniqueId());
|
||||
if (draw != null && draw.player() == event.getPlayer() && event.getPreviousSlot() != event.getNewSlot()) cancelDraw(draw);
|
||||
}
|
||||
|
||||
private void cancelCustody(UUID owner) {
|
||||
try { cancelMove(owner); }
|
||||
finally {
|
||||
var draw = draws.get(owner);
|
||||
if (draw != null) cancelDraw(draw);
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelDraw(Draw draw) {
|
||||
draws.remove(draw.player().getUniqueId(), draw);
|
||||
try {
|
||||
if (draw.item().equals(draw.player().getActiveItem())) draw.player().clearActiveItem();
|
||||
} catch (RuntimeException failure) {
|
||||
report(draw.player().getUniqueId(), draw.selected().session().session(), failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean useGesture(EquipmentSessions.SelectedControl selected) {
|
||||
return selected.slot() == 0 || selected.slot() >= 2
|
||||
&& !selected.ability().equals("great_sword") && !selected.ability().equals("longbow");
|
||||
}
|
||||
|
||||
private void emit(Player player, ItemStack item, EquipmentSessions.SelectedControl selected,
|
||||
ControlInput.Gesture gesture, org.bukkit.entity.Entity target, int heldTicks, float strength) {
|
||||
var captured = item.clone();
|
||||
var kind = selected.slot() == 0 ? ControlInput.Kind.BOOK
|
||||
: selected.slot() == 1 ? ControlInput.Kind.BASIC_ATTACK : ControlInput.Kind.ABILITY;
|
||||
var input = new ControlInput(player, selected.session(), selected.slot(), selected.ability(), kind,
|
||||
gesture, target, heldTicks, strength,
|
||||
() -> !closed && sessions.selectedControl(player, captured).filter(selected::equals).isPresent());
|
||||
if (!input.stillCurrent()) return;
|
||||
try { inputs.accept(input); }
|
||||
catch (RuntimeException failure) { report(player.getUniqueId(), selected.session().session(), failure); }
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void useEntity(org.bukkit.event.player.PlayerInteractEntityEvent event) {
|
||||
var player = event.getPlayer();
|
||||
var item = player.getInventory().getItem(event.getHand());
|
||||
if (special(item)) event.setCancelled(true);
|
||||
if (event.getHand() == EquipmentSlot.HAND) {
|
||||
var selected = sessions.selectedControl(player, item).orElse(null);
|
||||
if (selected != null && useGesture(selected)) emit(player, item, selected,
|
||||
ControlInput.Gesture.USE, event.getRightClicked(), 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void attack(io.papermc.paper.event.player.PrePlayerAttackEntityEvent event) {
|
||||
// The ability/basic-attack adapter owns intentional damage. Never also execute
|
||||
// vanilla Player.attack with the icon's material, enchantments or attributes.
|
||||
var player = event.getPlayer();
|
||||
var item = player.getInventory().getItemInMainHand();
|
||||
boolean willAttack = event.willAttack();
|
||||
if (special(item)) event.setCancelled(true);
|
||||
if (willAttack) {
|
||||
var selected = sessions.selectedControl(player, item).orElse(null);
|
||||
if (selected != null && (selected.slot() == 1 || selected.ability().equals("great_sword"))) {
|
||||
emit(player, item, selected, ControlInput.Gesture.ATTACK, event.getAttacked(), 0, player.getAttackCooldown());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void armorStand(org.bukkit.event.player.PlayerArmorStandManipulateEvent event) {
|
||||
if (special(event.getPlayerItem()) || special(event.getArmorStandItem())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void consume(org.bukkit.event.player.PlayerItemConsumeEvent event) {
|
||||
if (special(event.getItem())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void place(org.bukkit.event.block.BlockPlaceEvent event) {
|
||||
if (special(event.getItemInHand())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void transfer(org.bukkit.event.inventory.InventoryMoveItemEvent event) {
|
||||
if (special(event.getItem())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void attemptPickup(org.bukkit.event.player.PlayerAttemptPickupItemEvent event) {
|
||||
if (pickupBlocked(event.getPlayer(), event.getItem().getItemStack(), event.getRemaining())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void pickup(org.bukkit.event.entity.EntityPickupItemEvent event) {
|
||||
if (pickupBlocked(event.getEntity(), event.getItem().getItemStack(), event.getRemaining())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void inventoryPickup(org.bukkit.event.inventory.InventoryPickupItemEvent event) {
|
||||
var item = event.getItem().getItemStack();
|
||||
if (pickupClaim(item, "control_") || pickupClaim(item, "storage_")) event.setCancelled(true);
|
||||
}
|
||||
|
||||
private boolean pickupBlocked(org.bukkit.entity.LivingEntity entity, ItemStack item, int remaining) {
|
||||
if (pickupClaim(item, "control_")) return true;
|
||||
if (!pickupClaim(item, "storage_")) return false;
|
||||
var box = box(item);
|
||||
// ItemEntity.playerTouch temporarily narrows the stack to canHold before entity
|
||||
// pickup dispatch, then restores count + remaining before Inventory.add. Never
|
||||
// mistake a partial/oversized claim for one genuine nonstackable box.
|
||||
if (box == null || item.getAmount() != 1 || item.getMaxStackSize() != 1 || remaining != 0
|
||||
|| !item.getPersistentDataContainer().has(BOX_SLOTS, PersistentDataType.INTEGER_ARRAY)
|
||||
|| !Arrays.equals(BOX_SLOT_MAP, item.getPersistentDataContainer().get(BOX_SLOTS, PersistentDataType.INTEGER_ARRAY))
|
||||
|| !(entity instanceof Player player) || !box.owner().equals(player.getUniqueId())
|
||||
|| player.getInventory().getMaxStackSize() < 1) return true;
|
||||
// Purpur 2618 Inventory.add(-1, stack): factory nonstackable boxes cannot merge;
|
||||
// getFreeSlot scans 0..35, NOT the selected slot or only main storage. Read only:
|
||||
// leave native insertion to the caller, and never invent a recovery destination.
|
||||
for (int slot = 0; slot < 36; slot++) {
|
||||
if (empty(player.getInventory().getItem(slot))) return slot < 9;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Pickup-only fail-closed claims: malformed/future metadata must not turn protected
|
||||
// remnants into ordinary loot. This grants no session/recovery authority and does not
|
||||
// change the existing cursor/click policy or EquipmentStorage's payload validation.
|
||||
private static boolean pickupClaim(ItemStack item, String prefix) {
|
||||
if (empty(item)) return false;
|
||||
return item.getPersistentDataContainer().getKeys().stream()
|
||||
.anyMatch(key -> key.getNamespace().equals("fantasystick") && key.getKey().startsWith(prefix));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void launch(com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent event) {
|
||||
if (special(event.getItemStack())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void shoot(org.bukkit.event.entity.EntityShootBowEvent event) {
|
||||
if (special(event.getBow()) || special(event.getConsumable())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void dispense(org.bukkit.event.block.BlockDispenseArmorEvent event) {
|
||||
if (special(event.getItem()) || event.getTargetEntity() instanceof Player player
|
||||
&& active(player) && (!cosmetic(event.getItem()) || forbiddenEquip(event.getItem()))) event.setCancelled(true);
|
||||
}
|
||||
|
||||
private static boolean forbiddenEquip(ItemStack item) {
|
||||
if (empty(item)) return false;
|
||||
var equippable = item.getData(io.papermc.paper.datacomponent.DataComponentTypes.EQUIPPABLE);
|
||||
if (equippable == null) return false;
|
||||
return switch (equippable.slot()) {
|
||||
case HEAD -> !cosmetic(item);
|
||||
case CHEST, LEGS, FEET -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean destinationBlocked(Player player, Inventory inventory, int slot, ItemStack item) {
|
||||
if (control(item)) return true;
|
||||
var box = box(item);
|
||||
if (box != null) return !ownerMain(player, inventory, slot, box.owner());
|
||||
if (!active(player) || !ownInventory(player, inventory)) return false;
|
||||
if (slot >= 0 && slot < 9) return true;
|
||||
return !empty(item) && slot >= 36 && slot <= 39 && (slot != 39 || !cosmetic(item));
|
||||
}
|
||||
|
||||
private boolean active(Player player) { return sessions.active(player.getUniqueId()).isPresent(); }
|
||||
private boolean control(ItemStack item) { return pickupClaim(item, "control_move_") || controls.identify(item).isPresent(); }
|
||||
private boolean special(ItemStack item) { return control(item) || box(item) != null; }
|
||||
private static boolean ownInventory(Player player, Inventory inventory) {
|
||||
return inventory instanceof PlayerInventory && inventory.equals(player.getInventory());
|
||||
}
|
||||
private static boolean ownerMain(Player player, Inventory inventory, int slot, UUID owner) {
|
||||
return owner.equals(player.getUniqueId()) && ownInventory(player, inventory) && slot >= 9 && slot < 36;
|
||||
}
|
||||
private static int mainCapacity(Player player, ItemStack item) {
|
||||
int capacity = 0;
|
||||
for (int slot = 9; slot < 36; slot++) {
|
||||
var current = player.getInventory().getItem(slot);
|
||||
if (empty(current)) capacity += item.getMaxStackSize();
|
||||
else if (current.isSimilar(item)) capacity += Math.max(0, item.getMaxStackSize() - current.getAmount());
|
||||
}
|
||||
return capacity;
|
||||
}
|
||||
|
||||
// Identity only, not restoration validation. The slot map and actual contents remain
|
||||
// exclusively EquipmentStorage's responsibility. Names never confer protected identity.
|
||||
private record Box(UUID owner, UUID session) { }
|
||||
private static final NamespacedKey BOX_VERSION = new NamespacedKey("fantasystick", "storage_version");
|
||||
private static final NamespacedKey BOX_OWNER = new NamespacedKey("fantasystick", "storage_owner_id");
|
||||
private static final NamespacedKey BOX_SESSION = new NamespacedKey("fantasystick", "storage_session_id");
|
||||
private static final NamespacedKey BOX_SLOTS = new NamespacedKey("fantasystick", "storage_slots");
|
||||
private static final int[] BOX_SLOT_MAP = {0, 1, 2, 3, 4, 5, 6, 7, 8, 36, 37, 38, 39};
|
||||
private static Box box(ItemStack item) {
|
||||
if (empty(item) || !item.getType().name().endsWith("SHULKER_BOX")) return null;
|
||||
var data = item.getPersistentDataContainer();
|
||||
if (!data.has(BOX_VERSION, PersistentDataType.INTEGER) || !data.has(BOX_OWNER, PersistentDataType.STRING)
|
||||
|| !data.has(BOX_SESSION, PersistentDataType.STRING)
|
||||
|| !Integer.valueOf(1).equals(data.get(BOX_VERSION, PersistentDataType.INTEGER))) return null;
|
||||
String owner = data.get(BOX_OWNER, PersistentDataType.STRING);
|
||||
String session = data.get(BOX_SESSION, PersistentDataType.STRING);
|
||||
if (owner == null || session == null) return null;
|
||||
try {
|
||||
UUID ownerId = UUID.fromString(owner), sessionId = UUID.fromString(session);
|
||||
return ownerId.toString().equals(owner) && sessionId.toString().equals(session) ? new Box(ownerId, sessionId) : null;
|
||||
} catch (IllegalArgumentException invalid) { return null; }
|
||||
}
|
||||
private static boolean cosmetic(ItemStack item) {
|
||||
if (empty(item)) return false;
|
||||
boolean head = switch (item.getType()) {
|
||||
case PLAYER_HEAD, ZOMBIE_HEAD, CREEPER_HEAD, DRAGON_HEAD, PIGLIN_HEAD,
|
||||
SKELETON_SKULL, WITHER_SKELETON_SKULL, CARVED_PUMPKIN -> true;
|
||||
default -> false;
|
||||
};
|
||||
if (!head) return false;
|
||||
var modifiers = item.getAttributeModifiers(EquipmentSlot.HEAD);
|
||||
if (modifiers != null && (modifiers.containsKey(Attribute.ARMOR) || modifiers.containsKey(Attribute.ARMOR_TOUGHNESS))) return false;
|
||||
return !item.containsEnchantment(Enchantment.PROTECTION) && !item.containsEnchantment(Enchantment.FIRE_PROTECTION)
|
||||
&& !item.containsEnchantment(Enchantment.BLAST_PROTECTION) && !item.containsEnchantment(Enchantment.PROJECTILE_PROTECTION)
|
||||
&& !item.containsEnchantment(Enchantment.FEATHER_FALLING);
|
||||
}
|
||||
private static boolean empty(ItemStack item) { return item == null || item.isEmpty(); }
|
||||
|
||||
private void beginMove(Player player, InventoryView view, ItemStack box) {
|
||||
UUID owner = player.getUniqueId();
|
||||
var active = sessions.active(owner).orElse(null);
|
||||
if (closed || active == null || writing.contains(owner) || moves.containsKey(owner) || swaps.containsKey(owner)
|
||||
|| box.getAmount() != 1 || box.getMaxStackSize() != 1
|
||||
|| !new Box(owner, active.session()).equals(box(box))) return;
|
||||
var move = new BoxMove(player, view, active, box);
|
||||
moves.put(owner, move);
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (moves.get(owner) != move || move.issued) return;
|
||||
writing.add(owner);
|
||||
try {
|
||||
if (!moveCurrent(move) || !empty(player.getItemOnCursor()) || source(move) < 0) {
|
||||
cancelMove(move); return;
|
||||
}
|
||||
move.issued = true;
|
||||
player.setItemOnCursor(move.control.clone());
|
||||
if (!issuedCurrent(move)) { cancelMove(move); return; }
|
||||
player.updateInventory();
|
||||
if (!issuedCurrent(move)) cancelMove(move);
|
||||
} catch (RuntimeException failure) { cancelMove(move); report(owner, active.session(), failure); }
|
||||
finally { writing.remove(owner); }
|
||||
});
|
||||
} catch (RuntimeException failure) { cancelMove(move); report(owner, active.session(), failure); }
|
||||
}
|
||||
|
||||
private void placeMove(Player player, InventoryView view, int destination, ItemStack presented) {
|
||||
UUID owner = player.getUniqueId();
|
||||
var move = moves.get(owner);
|
||||
if (move == null || move.player != player || move.view != view || !move.issued || move.placing
|
||||
|| writing.contains(owner) || !moveCurrent(move) || !move.control.equals(presented)) return;
|
||||
var displaced = copy(player.getInventory().getItem(destination));
|
||||
if (special(displaced) && !move.box.equals(displaced)) return;
|
||||
move.placing = true;
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (moves.get(owner) != move || !move.placing) {
|
||||
// A cancelled native drag can restore its old harmless carried token AFTER
|
||||
// a reentrant close. Revoke/clean only this issued token, never a replacement.
|
||||
cancelMove(move); return;
|
||||
}
|
||||
move.placing = false; // One-use callback, including native exceptions.
|
||||
writing.add(owner);
|
||||
try {
|
||||
int source = source(move);
|
||||
if (!moveCurrent(move) || source < 0 || !move.control.equals(player.getItemOnCursor())
|
||||
|| !Objects.equals(displaced, copy(player.getInventory().getItem(destination)))) return;
|
||||
// Cursor setters can synchronously reenter close/exit or change either slot.
|
||||
// Remove the harmless control FIRST, then revalidate before touching gear.
|
||||
player.setItemOnCursor(null);
|
||||
if (!moveCurrent(move) || !empty(player.getItemOnCursor()) || source(move) != source
|
||||
|| !Objects.equals(displaced, copy(player.getInventory().getItem(destination)))) return;
|
||||
if (source != destination) {
|
||||
NativeMainInventorySwap.swap(player.getInventory(), source, destination);
|
||||
}
|
||||
moves.remove(owner, move);
|
||||
player.updateInventory(); // No planned writes after this reentrant boundary.
|
||||
} catch (RuntimeException failure) { report(owner, move.active.session(), failure); }
|
||||
finally { cancelMove(move); writing.remove(owner); reconcile(player); }
|
||||
});
|
||||
} catch (RuntimeException failure) { cancelMove(move); report(owner, move.active.session(), failure); }
|
||||
}
|
||||
|
||||
private boolean issuedCurrent(BoxMove move) {
|
||||
return moveCurrent(move) && move.control.equals(move.player.getItemOnCursor()) && source(move) >= 0;
|
||||
}
|
||||
|
||||
private boolean moveCurrent(BoxMove move) {
|
||||
return !closed && moves.get(move.active.player()) == move && move.player.isOnline()
|
||||
&& move.player.getOpenInventory() == move.view
|
||||
&& sessions.active(move.active.player()).filter(move.active::equals).isPresent();
|
||||
}
|
||||
|
||||
/** Follow the unique current box, not its index before a sorting operation. */
|
||||
private int source(BoxMove move) {
|
||||
int found = -1;
|
||||
var expected = new Box(move.active.player(), move.active.session());
|
||||
var inventory = move.player.getInventory();
|
||||
for (int slot = 0; slot < inventory.getSize(); slot++) {
|
||||
var item = inventory.getItem(slot);
|
||||
if (!expected.equals(box(item))) continue;
|
||||
if (found != -1 || slot < 9 || slot >= 36 || !move.box.equals(item)) return -1;
|
||||
found = slot;
|
||||
}
|
||||
return expected.equals(box(move.player.getItemOnCursor())) ? -1 : found;
|
||||
}
|
||||
|
||||
private void cancelMove(UUID owner) {
|
||||
var move = moves.get(owner);
|
||||
if (move != null) cancelMove(move);
|
||||
}
|
||||
|
||||
private void cancelMove(BoxMove move) {
|
||||
UUID owner = move.active.player();
|
||||
moves.remove(owner, move); // Invalidate before a cursor setter can reenter; never revoke a replacement.
|
||||
if (!move.issued) return;
|
||||
boolean reserved = writing.add(owner);
|
||||
try {
|
||||
if (move.control.equals(move.player.getItemOnCursor())) move.player.setItemOnCursor(null);
|
||||
} catch (RuntimeException failure) { report(owner, move.active.session(), failure); }
|
||||
finally { if (reserved) writing.remove(owner); }
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void close(org.bukkit.event.inventory.InventoryCloseEvent event) {
|
||||
UUID owner = event.getPlayer().getUniqueId();
|
||||
cancelCustody(owner);
|
||||
swaps.remove(owner);
|
||||
sessions.invalidateTail(owner);
|
||||
}
|
||||
|
||||
private boolean reservedExchange(Player player, int slot) {
|
||||
if (slot < 0 || slot > 8) return false;
|
||||
var active = sessions.active(player.getUniqueId()).orElse(null);
|
||||
return active != null && sheets.identify(player.getInventory().getItemInOffHand()).filter(active.character()::equals).isPresent()
|
||||
&& controls.owned(player.getInventory().getItem(slot), active.player(), active.session());
|
||||
}
|
||||
|
||||
private void exchange(Player player, int slot, InventoryView view) {
|
||||
UUID owner = player.getUniqueId();
|
||||
if (closed || writing.contains(owner) || swaps.containsKey(owner)) return;
|
||||
var active = sessions.active(owner).orElseThrow();
|
||||
var before = snapshot(player);
|
||||
var cursor = copy(player.getItemOnCursor());
|
||||
var heldBox = box(cursor);
|
||||
// A successful restore consumes exactly this own cursor box, replacing it with
|
||||
// the pre-restore head (or empty). Do not also accept the old box afterwards.
|
||||
var move = moves.get(owner);
|
||||
var restoredCursor = move != null && move.issued && move.control.equals(cursor) ? null
|
||||
: heldBox != null && heldBox.owner().equals(owner) && heldBox.session().equals(active.session())
|
||||
? copy(before[39]) : cursor;
|
||||
var token = new Intent();
|
||||
submit(owner, active.session(), token, () -> {
|
||||
if (closed || !player.isOnline()
|
||||
|| !sessions.active(owner).filter(active::equals).isPresent()
|
||||
|| !Arrays.equals(before, snapshot(player))
|
||||
|| !Objects.equals(cursor, copy(player.getItemOnCursor()))
|
||||
|| (view != null ? player.getOpenInventory() != view : player.getInventory().getHeldItemSlot() != slot)) return;
|
||||
queued.remove(owner);
|
||||
writing.add(owner);
|
||||
try {
|
||||
if (sessions.exit(player) != EquipmentStorage.RestoreResult.RESTORED) return;
|
||||
// Only this still-current, contained hotbar/offhand request is replayed.
|
||||
// Ordinary cursor/slot moves are already complete and never enter this path.
|
||||
if (closed || swaps.get(owner) != token || !Objects.equals(before[40], copy(player.getInventory().getItemInOffHand()))
|
||||
|| !Objects.equals(restoredCursor, copy(player.getItemOnCursor()))
|
||||
|| view != null && player.getOpenInventory() != view) return;
|
||||
var ordinary = copy(player.getInventory().getItem(slot));
|
||||
var sheet = copy(player.getInventory().getItemInOffHand());
|
||||
player.getInventory().setItem(slot, sheet);
|
||||
player.getInventory().setItemInOffHand(ordinary);
|
||||
// An actual exit happened even if the restored ordinary stack is a sheet
|
||||
// for the same character. The coordinator must check the next entry.
|
||||
observed.put(owner, null);
|
||||
player.updateInventory();
|
||||
} finally { writing.remove(owner); }
|
||||
reconcile(player);
|
||||
});
|
||||
}
|
||||
|
||||
private void dropSheet(Player player, InventoryView view, boolean all) {
|
||||
UUID owner = player.getUniqueId();
|
||||
if (closed || writing.contains(owner) || swaps.containsKey(owner)) return;
|
||||
var active = sessions.active(owner);
|
||||
var marker = EquipmentSessionMarker.read(player);
|
||||
var before = snapshot(player);
|
||||
var cursor = copy(player.getItemOnCursor());
|
||||
var token = new Intent();
|
||||
java.util.function.BooleanSupplier current = () -> !closed && swaps.get(owner) == token && player.isOnline()
|
||||
&& EquipmentSessionMarker.read(player).equals(marker) && sessions.active(owner).equals(active) && player.getOpenInventory() == view
|
||||
&& Arrays.equals(before, snapshot(player)) && Objects.equals(cursor, copy(player.getItemOnCursor()));
|
||||
UUID session = active.map(EquipmentSessions.Active::session).orElse(null);
|
||||
submit(owner, session, token, () -> {
|
||||
if (!current.getAsBoolean()) return;
|
||||
writing.add(owner);
|
||||
try {
|
||||
if (empty(before[40]) || before[40].getAmount() > before[40].getMaxStackSize()) {
|
||||
throw new IllegalArgumentException("Offhand sheet references exceed the native stack limit");
|
||||
}
|
||||
var selected = before[40].clone();
|
||||
selected.setAmount(all ? selected.getAmount() : 1);
|
||||
var result = new PlayerSheetDrops(player, event -> player.getServer().getPluginManager().callEvent(event))
|
||||
.dropReferences(selected, current);
|
||||
if (result == ManualDropDelivery.Status.COMPLETE && current.getAsBoolean()) {
|
||||
int remaining = before[40].getAmount() - selected.getAmount();
|
||||
if (remaining > 0) {
|
||||
var retained = before[40].clone();
|
||||
retained.setAmount(remaining);
|
||||
player.getInventory().setItemInOffHand(retained);
|
||||
} else {
|
||||
queued.remove(owner);
|
||||
sessions.cancelEntry(owner);
|
||||
player.getInventory().setItemInOffHand(null);
|
||||
observed.put(owner, null);
|
||||
sessions.exit(player);
|
||||
}
|
||||
player.updateInventory();
|
||||
} else if (result == ManualDropDelivery.Status.UNCONFIRMED || result == ManualDropDelivery.Status.COMPLETE) {
|
||||
report(owner, session, new IllegalStateException(
|
||||
"Sheet drop outcome is uncertain; retained current inventory, never replayed or charged stale contents"));
|
||||
}
|
||||
} finally { writing.remove(owner); reconcile(player); }
|
||||
});
|
||||
}
|
||||
|
||||
private void submit(UUID owner, UUID session, Intent token, Runnable action) {
|
||||
swaps.put(owner, token);
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (swaps.get(owner) != token || token.started) return;
|
||||
token.started = true;
|
||||
try { action.run(); }
|
||||
catch (RuntimeException failure) { report(owner, session, failure); }
|
||||
finally { swaps.remove(owner, token); }
|
||||
});
|
||||
} catch (RuntimeException failure) { swaps.remove(owner, token); report(owner, session, failure); }
|
||||
}
|
||||
|
||||
private void report(UUID owner, UUID session, Throwable failure) {
|
||||
try { diagnostics.accept(new EquipmentSessions.Failure(owner, session, failure)); }
|
||||
catch (RuntimeException ignored) { /* Diagnostics cannot authorize retries or abort custody cleanup. */ }
|
||||
}
|
||||
|
||||
private static ItemStack copy(ItemStack item) { return item == null || item.isEmpty() ? null : item.clone(); }
|
||||
private static ItemStack[] snapshot(Player player) {
|
||||
return Arrays.stream(player.getInventory().getContents()).map(EquipmentSessionEvents::copy).toArray(ItemStack[]::new);
|
||||
}
|
||||
|
||||
private void reconcile(Player player) {
|
||||
UUID owner = player.getUniqueId();
|
||||
var draw = draws.get(owner);
|
||||
if (draw != null && draw.player() == player
|
||||
&& !sessions.selectedControl(player, draw.item()).filter(draw.selected()::equals).isPresent()) cancelDraw(draw);
|
||||
if (closed || writing.contains(owner) || !player.isOnline()) return;
|
||||
var marker = EquipmentSessionMarker.read(player).orElse(null);
|
||||
if (marker != null && (marker.phase() == EquipmentSessionMarker.Phase.PACKING
|
||||
|| marker.phase() == EquipmentSessionMarker.Phase.RESTORING)) return;
|
||||
UUID character = sheets.identify(player.getInventory().getItemInOffHand()).orElse(null);
|
||||
var active = sessions.active(owner).orElse(null);
|
||||
boolean initial = !observed.containsKey(owner);
|
||||
boolean changed = initial || !Objects.equals(observed.get(owner), character);
|
||||
observed.put(owner, character);
|
||||
// A terminal recovery/client-sync observation is not a fresh offhand move.
|
||||
if (initial && active == null && marker != null) return;
|
||||
if (active != null && !active.character().equals(character)) {
|
||||
queued.remove(owner);
|
||||
writing.add(owner);
|
||||
try { sessions.exit(player); }
|
||||
finally { writing.remove(owner); }
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return;
|
||||
queued.remove(owner);
|
||||
sessions.cancelEntry(owner);
|
||||
if (character == null || sessions.active(owner).isPresent()) return;
|
||||
Object token = new Object();
|
||||
var entryMarker = EquipmentSessionMarker.read(player);
|
||||
queued.put(owner, token);
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (!queued.remove(owner, token) || closed || !player.isOnline()
|
||||
|| !EquipmentSessionMarker.read(player).equals(entryMarker)
|
||||
|| sessions.active(owner).isPresent()
|
||||
|| !sheets.identify(player.getInventory().getItemInOffHand()).filter(character::equals).isPresent()) return;
|
||||
sessions.enter(player);
|
||||
});
|
||||
} catch (RuntimeException failure) { queued.remove(owner, token); throw failure; }
|
||||
}
|
||||
|
||||
/** Invalidate deferred native actions before closing the coordinator/stores on disable. */
|
||||
@Override public void close() {
|
||||
closed = true;
|
||||
for (var owner : java.util.List.copyOf(moves.keySet())) cancelMove(owner);
|
||||
for (var draw : java.util.List.copyOf(draws.values())) cancelDraw(draw);
|
||||
queued.clear();
|
||||
swaps.clear();
|
||||
observed.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/**
|
||||
* Small versioned proof carried with native player state; owner is implicitly that player.
|
||||
* Server-thread only. One PDC value avoids partially written fields, not cross-save/crash
|
||||
* atomicity. No equipment copy, forced player save, or external recovery journal lives here.
|
||||
*/
|
||||
final class EquipmentSessionMarker {
|
||||
enum Phase { PACKING, PACKED, RESTORING, RESTORED }
|
||||
record Token(UUID session, UUID character, Phase phase) {
|
||||
Token {
|
||||
Objects.requireNonNull(session);
|
||||
Objects.requireNonNull(character);
|
||||
Objects.requireNonNull(phase);
|
||||
}
|
||||
boolean matches(UUID sessionId, UUID characterId) {
|
||||
return session.equals(sessionId) && character.equals(characterId);
|
||||
}
|
||||
}
|
||||
private static final NamespacedKey KEY = new NamespacedKey("fantasystick", "equipment_session");
|
||||
|
||||
static boolean present(Player player) { return player.getPersistentDataContainer().has(KEY); }
|
||||
|
||||
static Optional<Token> read(Player player) {
|
||||
var data = player.getPersistentDataContainer();
|
||||
if (!data.has(KEY, PersistentDataType.STRING)) return Optional.empty();
|
||||
String value = data.get(KEY, PersistentDataType.STRING);
|
||||
if (value == null || value.length() > 100) return Optional.empty();
|
||||
String[] fields = value.split("\\|", -1);
|
||||
if (fields.length != 4 || !fields[0].equals("1")) return Optional.empty();
|
||||
try {
|
||||
return Optional.of(new Token(uuid(fields[1]), uuid(fields[2]), Phase.valueOf(fields[3])));
|
||||
} catch (IllegalArgumentException invalid) { return Optional.empty(); }
|
||||
}
|
||||
|
||||
static void write(Player player, UUID session, UUID character, Phase phase) {
|
||||
var token = new Token(session, character, phase);
|
||||
player.getPersistentDataContainer().set(KEY, PersistentDataType.STRING,
|
||||
"1|" + token.session() + "|" + token.character() + "|" + token.phase());
|
||||
}
|
||||
|
||||
static void clear(Player player) { player.getPersistentDataContainer().remove(KEY); }
|
||||
|
||||
private static UUID uuid(String value) {
|
||||
UUID parsed = UUID.fromString(value);
|
||||
if (!parsed.toString().equals(value)) throw new IllegalArgumentException("Noncanonical UUID");
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,880 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.items.EquipmentStorage;
|
||||
import games.dmg.fantasystick.items.SessionControls;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.EquipmentSessionStore;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/**
|
||||
* Server-thread equipment custody, optional native vitals overlay and intercepted defeat.
|
||||
* Rewards and active food overrides remain separate. Presentation is independently cleaned. No inventory/file transaction,
|
||||
* automatic retry or snapshot rollback is promised. The scheduler must defer onto
|
||||
* the server thread; diagnostics must be thread-safe and must not use Player APIs.
|
||||
*/
|
||||
public final class EquipmentSessions implements AutoCloseable {
|
||||
public record Notice(UUID player, String code, String message) { }
|
||||
public record Failure(UUID player, UUID session, Throwable cause) { }
|
||||
public record Active(UUID player, UUID session, UUID character) { }
|
||||
public record SelectedControl(Active session, int slot, String ability) { }
|
||||
|
||||
private final CharacterStorage characters;
|
||||
private final EquipmentSessionStore receipts;
|
||||
private final Duration switchDelay;
|
||||
private final Clock clock;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<Notice> notices;
|
||||
private final Consumer<Failure> diagnostics;
|
||||
private games.dmg.fantasystick.presentation.SessionPresentation presentation = games.dmg.fantasystick.presentation.SessionPresentation.NONE;
|
||||
private final SessionClaims claims = new SessionClaims();
|
||||
private final EquipmentStorage equipment = new EquipmentStorage();
|
||||
private final SessionControls controls = new SessionControls();
|
||||
private final CharacterSheets sheets = new CharacterSheets();
|
||||
private final Map<UUID, Attempt> pending = new HashMap<>();
|
||||
private final Map<UUID, Attempt> owned = new HashMap<>();
|
||||
private final Map<UUID, Attempt> active = new HashMap<>();
|
||||
// Covers reentrant inventory setters and client sync, not just asynchronous work.
|
||||
private final Map<UUID, Attempt> transitioning = new HashMap<>();
|
||||
private Consumer<UUID> cursorCustody = ignored -> { };
|
||||
private boolean cursorCustodyAttached;
|
||||
private boolean closed;
|
||||
private java.util.function.BooleanSupplier adventureMode = () -> false;
|
||||
private AdventureModeLease gameModes = new AdventureModeLease();
|
||||
private SessionVitals vitals;
|
||||
private boolean closeSweepFinished;
|
||||
private int persistenceOperations;
|
||||
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
||||
|
||||
private static final class Attempt {
|
||||
final Player player;
|
||||
final UUID owner;
|
||||
UUID character;
|
||||
CharacterRecord record;
|
||||
SessionClaims.Claim claim;
|
||||
UUID session;
|
||||
ItemStack[] snapshot;
|
||||
ItemStack cursor;
|
||||
EquipmentSessionMarker.Token entryMarker;
|
||||
boolean markerValidated;
|
||||
boolean acknowledged;
|
||||
boolean saving;
|
||||
boolean effectsStarted;
|
||||
String previousGameMode;
|
||||
boolean modeStarted;
|
||||
games.dmg.fantasystick.persistence.OrdinaryVitals ordinaryVitals;
|
||||
boolean vitalsStarted;
|
||||
boolean healthSaveRequested;
|
||||
boolean healthAcknowledged = true;
|
||||
boolean nativeRestored;
|
||||
boolean gearRestoredForModeRecovery;
|
||||
boolean presentationInstalled;
|
||||
boolean cleaning;
|
||||
boolean cleanupAttempted;
|
||||
boolean uncertainSave;
|
||||
boolean nativeUncertain;
|
||||
boolean exitRequested;
|
||||
boolean arrival;
|
||||
Attempt recoveryOwner;
|
||||
org.bukkit.Location entryLocation;
|
||||
boolean defeated;
|
||||
boolean deathResolved;
|
||||
boolean gearAcknowledged;
|
||||
boolean bookAttempted;
|
||||
boolean bookDelivered;
|
||||
boolean deliveryInvalidated;
|
||||
boolean conversionReported;
|
||||
ItemStack deathReference;
|
||||
org.bukkit.inventory.InventoryView deathView;
|
||||
Attempt(Player player, UUID owner, UUID character) {
|
||||
this.player = player; this.owner = owner; this.character = character;
|
||||
}
|
||||
}
|
||||
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics) {
|
||||
this(characters, receipts, switchDelay, Clock.systemUTC(), nextTick, notices, diagnostics);
|
||||
}
|
||||
|
||||
/** Supply the same wall clock as persistence when testing entry/exit deadline boundaries. */
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics) {
|
||||
this.characters = Objects.requireNonNull(characters);
|
||||
this.receipts = Objects.requireNonNull(receipts);
|
||||
this.switchDelay = Objects.requireNonNull(switchDelay);
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
if (switchDelay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
|
||||
this.nextTick = Objects.requireNonNull(nextTick);
|
||||
this.notices = Objects.requireNonNull(notices);
|
||||
this.diagnostics = Objects.requireNonNull(diagnostics);
|
||||
}
|
||||
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics,
|
||||
games.dmg.fantasystick.presentation.SessionPresentation presentation) {
|
||||
this(characters, receipts, switchDelay, clock, nextTick, notices, diagnostics);
|
||||
this.presentation = Objects.requireNonNull(presentation);
|
||||
}
|
||||
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics,
|
||||
games.dmg.fantasystick.presentation.SessionPresentation presentation,
|
||||
java.util.function.BooleanSupplier adventureMode, AdventureModeLease gameModes) {
|
||||
this(characters, receipts, switchDelay, clock, nextTick, notices, diagnostics, presentation);
|
||||
this.adventureMode = Objects.requireNonNull(adventureMode);
|
||||
this.gameModes = Objects.requireNonNull(gameModes);
|
||||
}
|
||||
|
||||
/** Install before exposing entry; equipment-only adapter tests can omit the health overlay. */
|
||||
public synchronized void attachVitals(SessionVitals value) {
|
||||
if (vitals != null || !owned.isEmpty()) throw new IllegalStateException("Vitals already attached or sessions started");
|
||||
vitals = Objects.requireNonNull(value);
|
||||
}
|
||||
|
||||
/** One server-thread custody bridge per coordinator; never called by persistence workers. */
|
||||
synchronized void attachCursorCustody(Consumer<UUID> invalidate) {
|
||||
if (cursorCustodyAttached) throw new IllegalStateException("Cursor custody already attached");
|
||||
cursorCustody = Objects.requireNonNull(invalidate);
|
||||
cursorCustodyAttached = true;
|
||||
}
|
||||
|
||||
private void invalidateCursor(UUID owner) {
|
||||
try { cursorCustody.accept(owner); }
|
||||
catch (RuntimeException failure) { diagnostic(new Failure(owner, null, failure)); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes after close's native sweep and all owned receipt/death mutations finish,
|
||||
* including failed or ambiguous outcomes. Retained receipts/conversions are not outstanding operations.
|
||||
* Observers cannot complete/cancel the lifetime authority. Does not await queued server tasks.
|
||||
*/
|
||||
public CompletionStage<Void> drained() { return drained.minimalCompletionStage(); }
|
||||
|
||||
// All accounting, submissions and completion handlers share the lifecycle monitor. A handler
|
||||
// may submit its follow-up before its own reservation is released, including after close.
|
||||
private <T> void persist(Supplier<CompletionStage<T>> operation, BiConsumer<T, Throwable> completion) {
|
||||
persistenceOperations++;
|
||||
CompletionStage<T> work;
|
||||
try { work = operation.get(); }
|
||||
catch (RuntimeException failure) { work = CompletableFuture.failedStage(failure); }
|
||||
work.whenComplete((value, failure) -> {
|
||||
synchronized (EquipmentSessions.this) {
|
||||
try { completion.accept(value, failure); }
|
||||
finally {
|
||||
persistenceOperations--;
|
||||
finishDrain();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void finishDrain() {
|
||||
if (closeSweepFinished && persistenceOperations == 0 && transitioning.isEmpty()) drained.complete(null);
|
||||
}
|
||||
|
||||
public synchronized Optional<Active> active(UUID player) {
|
||||
var attempt = active.get(player);
|
||||
return attempt == null ? Optional.empty() : Optional.of(new Active(player, attempt.session, attempt.character));
|
||||
}
|
||||
|
||||
/** Server-thread effect authorization: registry identity alone is not live custody. */
|
||||
public synchronized boolean current(Active session) {
|
||||
var attempt = active.get(session.player());
|
||||
return !closed && attempt != null && attempt.session.equals(session.session())
|
||||
&& attempt.character.equals(session.character()) && attempt.player.isOnline()
|
||||
&& sheets.identify(attempt.player.getInventory().getItemInOffHand()).filter(attempt.character::equals).isPresent();
|
||||
}
|
||||
|
||||
/** Server-thread authorization for the currently held, issued control and saved loadout. */
|
||||
public synchronized Optional<SelectedControl> selectedControl(Player player, ItemStack reported) {
|
||||
var attempt = active.get(player.getUniqueId());
|
||||
if (closed || attempt == null || attempt.player != player || !player.isOnline() || attempt.record == null
|
||||
|| !sheets.identify(player.getInventory().getItemInOffHand()).filter(attempt.character::equals).isPresent()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
int slot = player.getInventory().getHeldItemSlot();
|
||||
var actual = player.getInventory().getItem(slot);
|
||||
var identity = controls.identify(actual).orElse(null);
|
||||
if (identity == null || identity.slot() != slot || !identity.owner().equals(attempt.owner)
|
||||
|| !identity.session().equals(attempt.session) || !Objects.equals(actual, reported)) return Optional.empty();
|
||||
String ability = "";
|
||||
if (slot >= 2) {
|
||||
ability = controls.ability(actual).orElse("");
|
||||
if (ability.isEmpty() || !ability.equals(attempt.record.loadout().get(slot - 2))) return Optional.empty();
|
||||
}
|
||||
return Optional.of(new SelectedControl(new Active(attempt.owner, attempt.session, attempt.character), slot, ability));
|
||||
}
|
||||
|
||||
public synchronized void enter(Player player) {
|
||||
UUID owner = player.getUniqueId();
|
||||
if (closed) return;
|
||||
if (transitioning.containsKey(owner)) {
|
||||
notice(owner, "BUSY", "An equipment transition is still completing; retry afterwards."); return;
|
||||
}
|
||||
if (active.containsKey(owner)) return;
|
||||
cancelEntry(owner);
|
||||
if (owned.containsKey(owner)) {
|
||||
notice(owner, "BUSY", "Equipment persistence or recovery is pending; retry after it completes.");
|
||||
return;
|
||||
}
|
||||
var character = sheets.identify(player.getInventory().getItemInOffHand());
|
||||
if (!player.isOnline() || character.isEmpty()) {
|
||||
notice(owner, "INVALID_SHEET", "Hold a valid live character sheet in your off hand.");
|
||||
return;
|
||||
}
|
||||
var attempt = new Attempt(player, owner, character.orElseThrow());
|
||||
if (adventureMode.getAsBoolean() && player.getGameMode() != org.bukkit.GameMode.ADVENTURE) {
|
||||
attempt.previousGameMode = player.getGameMode().name();
|
||||
}
|
||||
attempt.snapshot = snapshot(player);
|
||||
attempt.cursor = copy(player.getItemOnCursor());
|
||||
pending.put(owner, attempt);
|
||||
characters.find(attempt.character).thenCombine(receipts.find(owner), Loaded::new)
|
||||
.whenComplete((loaded, failure) -> schedule(attempt, () -> loaded(attempt, loaded, failure)));
|
||||
}
|
||||
|
||||
private record Loaded(Optional<CharacterRecord> character, Optional<EquipmentSessionStore.State> state) { }
|
||||
|
||||
private boolean entryNativeSafe(Attempt attempt, EquipmentSessionStore.State state) {
|
||||
if (hasRemnants(attempt.player) || !gameModes.available(attempt.player)
|
||||
|| vitals != null && !vitals.available(attempt.player)) return false;
|
||||
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
|
||||
if (EquipmentSessionMarker.present(attempt.player)) {
|
||||
// A terminal marker is resolved only by its matching completed file acknowledgment.
|
||||
// Keep it until the next successful entry; worker acknowledgments never touch PDC.
|
||||
var exit = state == null ? null : state.lastExit();
|
||||
if (marker == null || marker.phase() != EquipmentSessionMarker.Phase.RESTORED
|
||||
|| state == null || state.pending() != null || exit == null
|
||||
|| !marker.matches(exit.sessionId(), exit.characterId())) return false;
|
||||
}
|
||||
attempt.entryMarker = marker;
|
||||
attempt.markerValidated = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean hasRemnants(Player player) {
|
||||
return Arrays.stream(player.getInventory().getContents()).anyMatch(EquipmentSessions::remnant)
|
||||
|| remnant(player.getItemOnCursor());
|
||||
}
|
||||
|
||||
private static boolean remnant(ItemStack item) {
|
||||
if (item == null || item.isEmpty() || !item.hasItemMeta()) return false;
|
||||
// Even malformed/foreign remnants are unsafe to pack as ordinary equipment.
|
||||
return item.getItemMeta().getPersistentDataContainer().getKeys().stream().anyMatch(key ->
|
||||
key.getNamespace().equals("fantasystick")
|
||||
&& (key.getKey().startsWith("storage_") || key.getKey().startsWith("control_")));
|
||||
}
|
||||
|
||||
private synchronized void loaded(Attempt attempt, Loaded loaded, Throwable failure) {
|
||||
if (!entryCurrent(attempt) || attempt.claim != null) return;
|
||||
if (failure != null) { fail(attempt, failure); return; }
|
||||
var record = loaded.character().orElse(null);
|
||||
if (record == null || record.dead() || record.health().signum() <= 0) {
|
||||
refuse(attempt, "UNAVAILABLE_CHARACTER", "The saved character is missing, dead or has no health."); return;
|
||||
}
|
||||
if (loaded.state().isPresent()) {
|
||||
var state = loaded.state().orElseThrow();
|
||||
if (state.pending() != null) {
|
||||
refuse(attempt, "RECOVERY_REQUIRED", "An unresolved equipment receipt requires validated recovery."); return;
|
||||
}
|
||||
Instant now = clock.instant();
|
||||
if (!state.canEnter(attempt.character, switchDelay, now)) {
|
||||
Duration remaining = Duration.between(now, state.lastExit().deadline());
|
||||
long seconds = remaining.getSeconds() + (remaining.getNano() == 0 ? 0 : 1);
|
||||
refuse(attempt, "COOLDOWN", "Wait " + seconds + " seconds to switch characters (until "
|
||||
+ state.lastExit().deadline() + "); the same character may be resumed now."); return;
|
||||
}
|
||||
}
|
||||
if (!entryNativeSafe(attempt, loaded.state().orElse(null))) {
|
||||
refuse(attempt, "NATIVE_RECOVERY_REQUIRED", "Native equipment marker or control/box remnants require inspection; entry did not change items.");
|
||||
return;
|
||||
}
|
||||
var refusal = equipment.refusal(attempt.player.getInventory(), attempt.owner, UUID.randomUUID());
|
||||
if (refusal.isPresent()) { refuse(attempt, refusal.orElseThrow().name(), "Equipment entry refused: " + refusal.orElseThrow()); return; }
|
||||
// Restart receipts can belong to dead/missing characters, so they cannot acquire a
|
||||
// live SessionClaims token. Their unresolved equipment outcome still excludes entry.
|
||||
if (owned.values().stream().anyMatch(other -> attempt.character.equals(other.character))) {
|
||||
refuse(attempt, "CHARACTER_BUSY", "This character has an unresolved equipment session."); return;
|
||||
}
|
||||
attempt.claim = claims.tryClaim(attempt.owner, record).orElse(null);
|
||||
if (attempt.claim == null) { refuse(attempt, "CHARACTER_BUSY", "This character or player already has a session."); return; }
|
||||
attempt.session = attempt.claim.sessionId();
|
||||
owned.put(attempt.owner, attempt);
|
||||
controls.create(record, attempt.owner, attempt.session); // Validate all nine controls before preparation/packing.
|
||||
if (vitals != null) attempt.ordinaryVitals = vitals.capture(attempt.player);
|
||||
attempt.saving = true;
|
||||
persist(() -> receipts.prepare(attempt.owner, attempt.session, attempt.character, attempt.previousGameMode, attempt.ordinaryVitals), (saved, error) -> {
|
||||
attempt.saving = false;
|
||||
if (error != null) { attempt.uncertainSave = true; fail(attempt, error); return; }
|
||||
attempt.acknowledged = true;
|
||||
if (!current(attempt)) { abandon(attempt); return; }
|
||||
// Queue the cross-worker read under lifecycle ownership: close cannot finish
|
||||
// its drain boundary and then have this callback submit fresh character IO.
|
||||
characters.find(attempt.character).whenComplete((fresh, readError) ->
|
||||
schedule(attempt, () -> complete(attempt, fresh, readError)));
|
||||
});
|
||||
}
|
||||
|
||||
private synchronized void complete(Attempt attempt, Optional<CharacterRecord> fresh, Throwable failure) {
|
||||
if (!entryCurrent(attempt)) return;
|
||||
if (failure != null) { fail(attempt, failure); return; }
|
||||
var record = fresh.orElse(null);
|
||||
if (record == null || record.dead() || record.health().signum() <= 0) {
|
||||
refuse(attempt, "UNAVAILABLE_CHARACTER", "The saved character is no longer live."); return;
|
||||
}
|
||||
transitioning.put(attempt.owner, attempt);
|
||||
boolean packed = false;
|
||||
try {
|
||||
var items = controls.create(record, attempt.owner, attempt.session);
|
||||
attempt.entryLocation = attempt.player.getLocation().clone(); // Server thread, before activation.
|
||||
attempt.modeStarted = attempt.previousGameMode != null;
|
||||
if (!gameModes.enter(attempt.player, attempt.session, attempt.previousGameMode)) {
|
||||
attempt.modeStarted = false; // Returned refusal is not an uncertain setter exception.
|
||||
refuse(attempt, "GAME_MODE_REFUSED", "Adventure mode was refused; entry did not pack equipment."); return;
|
||||
}
|
||||
if (!entryCurrent(attempt) || attempt.exitRequested) return;
|
||||
attempt.effectsStarted = true;
|
||||
mark(attempt, EquipmentSessionMarker.Phase.PACKING);
|
||||
var result = equipment.pack(attempt.player.getInventory(), attempt.owner, attempt.session);
|
||||
if (result != EquipmentStorage.PackResult.PACKED) {
|
||||
EquipmentSessionMarker.clear(attempt.player); // Adapter refusal proves no inventory writes.
|
||||
attempt.effectsStarted = false;
|
||||
refuse(attempt, result.name(), "Equipment entry refused: " + result); return;
|
||||
}
|
||||
packed = true;
|
||||
if (interrupted(attempt)) return;
|
||||
for (int slot = 0; slot < 9; slot++) {
|
||||
attempt.player.getInventory().setItem(slot, items[slot]);
|
||||
if (interrupted(attempt)) return;
|
||||
}
|
||||
mark(attempt, EquipmentSessionMarker.Phase.PACKED);
|
||||
if (vitals != null) {
|
||||
attempt.vitalsStarted = true;
|
||||
attempt.healthAcknowledged = false;
|
||||
vitals.enter(attempt.player, attempt.session, attempt.ordinaryVitals, record);
|
||||
if (attempt.exitRequested || !current(attempt)) return;
|
||||
}
|
||||
pending.remove(attempt.owner, attempt);
|
||||
if (!attempt.exitRequested) {
|
||||
attempt.record = record;
|
||||
active.put(attempt.owner, attempt);
|
||||
attempt.presentationInstalled = true;
|
||||
try { presentation.activate(attempt.player, attempt.session, record); }
|
||||
catch (RuntimeException | LinkageError error) { withdrawPresentation(attempt); diagnostic(attempt, error); }
|
||||
}
|
||||
attempt.player.updateInventory();
|
||||
} catch (RuntimeException error) {
|
||||
fail(attempt, error); // Effects may have started: never roll back or replay them.
|
||||
notice(attempt.owner, "NATIVE_UNCERTAIN", "Equipment mutation failed; items and receipt require inspection.");
|
||||
} finally {
|
||||
if (!active.containsKey(attempt.owner) && attempt.modeStarted) {
|
||||
restoreGameMode(attempt);
|
||||
if (!attempt.effectsStarted && attempt.exitRequested) pending.remove(attempt.owner, attempt);
|
||||
if (!attempt.effectsStarted && !current(attempt)) abandon(attempt);
|
||||
}
|
||||
transitioning.remove(attempt.owner, attempt);
|
||||
// The deferred exit must reserve persistence before drain can be signalled.
|
||||
try {
|
||||
if (packed && !attempt.nativeUncertain && !attempt.defeated && attempt.exitRequested) restoreExit(attempt);
|
||||
} finally { finishDrain(); }
|
||||
}
|
||||
}
|
||||
|
||||
private boolean interrupted(Attempt attempt) {
|
||||
if (current(attempt) || attempt.exitRequested) return false;
|
||||
notice(attempt.owner, "ENTRY_INTERRUPTED", "Entry was cancelled during packing; the genuine box and receipt were retained for recovery.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends mode without awaiting IO. Reentrant calls during an owned native transition request
|
||||
* teardown at that transition's boundary and return NOT_FOUND (no separate restore ran).
|
||||
* A native exception returns INVALID_BOX with NATIVE_UNCERTAIN notice/diagnostic; never retry it.
|
||||
*/
|
||||
public synchronized EquipmentStorage.RestoreResult exit(Player player) {
|
||||
UUID owner = player.getUniqueId();
|
||||
var transition = transitioning.get(owner);
|
||||
if (transition != null) {
|
||||
active.remove(owner, transition);
|
||||
withdrawPresentation(transition);
|
||||
transition.exitRequested = true;
|
||||
invalidateCursor(owner);
|
||||
return EquipmentStorage.RestoreResult.NOT_FOUND;
|
||||
}
|
||||
cancelEntry(owner);
|
||||
var attempt = active.remove(owner);
|
||||
if (attempt == null) { invalidateCursor(owner); return EquipmentStorage.RestoreResult.NOT_FOUND; }
|
||||
return restoreExit(attempt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paper dispatches death before inventory clearing/drop spawning. Cancellation returns from
|
||||
* ServerPlayer.die; keepInventory is neither needed nor sufficient for this transition.
|
||||
* Only an active session owns defeat. Later ordinary deaths and prior vetoes stay ordinary.
|
||||
*/
|
||||
public synchronized void defeat(org.bukkit.event.entity.PlayerDeathEvent event) {
|
||||
if (closed || event.isCancelled()) return;
|
||||
UUID owner = event.getEntity().getUniqueId();
|
||||
var attempt = active.remove(owner);
|
||||
if (attempt == null) {
|
||||
var transition = transitioning.get(owner);
|
||||
if (transition != null && transition.defeated) {
|
||||
// Contain only reentrance inside this native defeat, not a later ordinary
|
||||
// lethal outcome. This is not a grace period or post-defeat invulnerability.
|
||||
event.setCancelled(true);
|
||||
event.setReviveHealth(Objects.requireNonNull(event.getEntity()
|
||||
.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue());
|
||||
}
|
||||
return;
|
||||
}
|
||||
withdrawPresentation(attempt);
|
||||
attempt.defeated = true;
|
||||
event.setCancelled(true);
|
||||
boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null;
|
||||
// Submit first: any subsequent native getter/setter/notice can reenter disable, which
|
||||
// closes CharacterStorage. No dependent character work is submitted after this point.
|
||||
persist(() -> characters.recordDeath(attempt.character), (dead, failure) -> {
|
||||
if (failure != null) { diagnostic(attempt, failure); conversionUncertain(attempt, "Death save failed or is uncertain"); return; }
|
||||
if (dead.isEmpty()) { conversionUncertain(attempt, "Character was missing or already dead; no new Tail authorized"); return; }
|
||||
attempt.deathResolved = true;
|
||||
if (closed) { conversionUncertain(attempt, "Shutdown before Tail conversion"); return; }
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
synchronized (EquipmentSessions.this) { deliverTail(attempt, dead.orElseThrow()); }
|
||||
});
|
||||
} catch (RuntimeException error) { diagnostic(attempt, error); conversionUncertain(attempt, "Tail callback rejected"); }
|
||||
});
|
||||
try {
|
||||
attempt.deathReference = copy(attempt.player.getInventory().getItemInOffHand());
|
||||
attempt.deathView = attempt.player.getOpenInventory();
|
||||
restoreExit(attempt);
|
||||
// Read the current maximum after owned overlay cleanup, including legitimate
|
||||
// ordinary modifiers. Never reconstruct attributes from an entry snapshot.
|
||||
double maximum = Objects.requireNonNull(attempt.player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue();
|
||||
event.setReviveHealth(maximum);
|
||||
attempt.player.setHealth(maximum); // Native cancellation only fills health when <= 0.
|
||||
notice(attempt.owner, "DEFEAT", "§cYour character was defeated.");
|
||||
try {
|
||||
if (!attempt.player.teleport(attempt.entryLocation.clone())) {
|
||||
notice(attempt.owner, "DEFEAT_RETURN_FAILED", "Return to the session entry location was refused; you remain here.");
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
diagnostic(attempt, failure);
|
||||
notice(attempt.owner, "DEFEAT_RETURN_FAILED", "Return to the session entry location failed; you remain here.");
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
diagnostic(attempt, failure);
|
||||
conversionUncertain(attempt, "Native defeat transition failed; inspect retained equipment and death state");
|
||||
} finally {
|
||||
if (reserved) transitioning.remove(attempt.owner, attempt);
|
||||
finishDrain();
|
||||
}
|
||||
}
|
||||
|
||||
/** No automatic delivery after quit/respawn, including a reconnect of the same Player ID. */
|
||||
public synchronized void invalidateContext(UUID owner) {
|
||||
invalidateCursor(owner);
|
||||
cancelEntry(owner);
|
||||
invalidateTail(owner);
|
||||
}
|
||||
|
||||
/** Invalidates deferred conversion only; does not move a cursor, box, sheet or controls. */
|
||||
public synchronized void invalidateTail(UUID owner) {
|
||||
var attempt = owned.get(owner);
|
||||
if (attempt != null && attempt.defeated) attempt.deliveryInvalidated = true;
|
||||
}
|
||||
|
||||
private void deliverTail(Attempt attempt, CharacterRecord dead) {
|
||||
if (attempt.bookAttempted) return;
|
||||
attempt.bookAttempted = true; // Even an exception after a native write never permits replay.
|
||||
try {
|
||||
if (!tailContext(attempt)
|
||||
|| !Objects.equals(attempt.deathReference, copy(attempt.player.getInventory().getItemInOffHand()))
|
||||
|| !sheets.identify(attempt.deathReference).filter(attempt.character::equals).isPresent()
|
||||
|| attempt.deathReference.getAmount() < 1
|
||||
|| attempt.deathReference.getAmount() > attempt.deathReference.getMaxStackSize()) {
|
||||
conversionUncertain(attempt, "Tail destination/context is stale or equipment restoration is unresolved"); return;
|
||||
}
|
||||
// An exact captured stack of copied references represents ONE character, not N
|
||||
// deaths. Replace that whole stack with ONE book; never scan/delete other copies,
|
||||
// move items, overwrite a changed stack, or grant into an available slot.
|
||||
var book = new games.dmg.fantasystick.items.TailBooks().create(dead);
|
||||
attempt.player.getInventory().setItemInOffHand(book);
|
||||
if (!tailContext(attempt) || !book.equals(attempt.player.getInventory().getItemInOffHand())) {
|
||||
conversionUncertain(attempt, "Context changed during Tail write; delivery may already have happened"); return;
|
||||
}
|
||||
attempt.bookDelivered = true;
|
||||
release(attempt);
|
||||
sync(attempt);
|
||||
} catch (RuntimeException failure) {
|
||||
diagnostic(attempt, failure);
|
||||
conversionUncertain(attempt, "Tail native write failed or is uncertain; never replay");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tailContext(Attempt attempt) {
|
||||
if (closed || attempt.deliveryInvalidated || owned.get(attempt.owner) != attempt
|
||||
|| !attempt.player.isOnline() || attempt.player.getOpenInventory() != attempt.deathView) return false;
|
||||
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
|
||||
return marker != null && marker.matches(attempt.session, attempt.character)
|
||||
&& marker.phase() == EquipmentSessionMarker.Phase.RESTORED;
|
||||
}
|
||||
|
||||
private void conversionUncertain(Attempt attempt, String reason) {
|
||||
if (attempt.conversionReported) return;
|
||||
attempt.conversionReported = true;
|
||||
attempt.deliveryInvalidated = true;
|
||||
diagnostic(attempt, new IllegalStateException(reason + "; character " + attempt.character
|
||||
+ ". Retain current items and authoritative state; no automatic reissue or revival."));
|
||||
}
|
||||
|
||||
private void withdrawPresentation(Attempt attempt) {
|
||||
if (!attempt.presentationInstalled) return;
|
||||
attempt.presentationInstalled = false;
|
||||
try { presentation.withdraw(attempt.owner, attempt.session); }
|
||||
catch (RuntimeException | LinkageError failure) { diagnostic(attempt, failure); }
|
||||
}
|
||||
|
||||
private boolean restoreGameMode(Attempt attempt) {
|
||||
if (attempt.previousGameMode == null) return true;
|
||||
try {
|
||||
if (gameModes.restore(attempt.player, attempt.session, attempt.previousGameMode)) {
|
||||
attempt.modeStarted = false;
|
||||
return true;
|
||||
}
|
||||
} catch (RuntimeException failure) { diagnostic(attempt, failure); }
|
||||
notice(attempt.owner, "GAME_MODE_RECOVERY", "Game-mode restoration was refused or ambiguous; retained receipt requires inspection.");
|
||||
return false;
|
||||
}
|
||||
|
||||
private EquipmentStorage.RestoreResult restoreExit(Attempt attempt) {
|
||||
active.remove(attempt.owner, attempt);
|
||||
withdrawPresentation(attempt);
|
||||
boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null;
|
||||
try {
|
||||
invalidateCursor(attempt.owner);
|
||||
saveRemainingHealth(attempt);
|
||||
boolean modeRestored = restoreGameMode(attempt);
|
||||
EquipmentStorage.RestoreResult result;
|
||||
try {
|
||||
result = restoreMarked(attempt);
|
||||
} catch (RuntimeException failure) {
|
||||
attempt.nativeUncertain = true;
|
||||
restoreVitals(attempt); // Proven health ownership is independent of uncertain equipment writes.
|
||||
persistExit(attempt, false);
|
||||
diagnostic(attempt, failure);
|
||||
notice(attempt.owner, "NATIVE_UNCERTAIN", "Restoration failed; items and receipt require inspection.");
|
||||
return EquipmentStorage.RestoreResult.INVALID_BOX;
|
||||
}
|
||||
boolean vitalsRestored = restoreVitals(attempt);
|
||||
if (result == EquipmentStorage.RestoreResult.RESTORED && (!modeRestored || !vitalsRestored || !attempt.healthAcknowledged)) {
|
||||
attempt.gearRestoredForModeRecovery = true;
|
||||
}
|
||||
persistExit(attempt, result == EquipmentStorage.RestoreResult.RESTORED && modeRestored && vitalsRestored);
|
||||
if (result != EquipmentStorage.RestoreResult.RESTORED) {
|
||||
notice(attempt.owner, result.name(), "Equipment recovery refused: " + result);
|
||||
} else sync(attempt);
|
||||
return result;
|
||||
} finally {
|
||||
if (reserved) transitioning.remove(attempt.owner, attempt);
|
||||
finishDrain();
|
||||
}
|
||||
}
|
||||
|
||||
private void mark(Attempt attempt, EquipmentSessionMarker.Phase phase) {
|
||||
EquipmentSessionMarker.write(attempt.player, attempt.session, attempt.character, phase);
|
||||
}
|
||||
|
||||
private EquipmentStorage.RestoreResult restoreMarked(Attempt attempt) {
|
||||
invalidateCursor(attempt.owner);
|
||||
var marker = EquipmentSessionMarker.read(attempt.player);
|
||||
// Only a successful restoration observed by this process for this exact Player
|
||||
// permits finishing a mode-only retry. Serialized RESTORED alone proves nothing.
|
||||
if (attempt.gearRestoredForModeRecovery && !hasRemnants(attempt.player)
|
||||
&& marker.filter(token -> token.matches(attempt.session, attempt.character)
|
||||
&& token.phase() == EquipmentSessionMarker.Phase.RESTORED).isPresent()) {
|
||||
return EquipmentStorage.RestoreResult.RESTORED;
|
||||
}
|
||||
if (marker.filter(token -> token.matches(attempt.session, attempt.character)
|
||||
&& token.phase() == EquipmentSessionMarker.Phase.PACKED).isEmpty()) {
|
||||
notice(attempt.owner, "NATIVE_MARKER", "Missing, malformed, mismatched or ambiguous native equipment marker; "
|
||||
+ "expected session " + attempt.session + ", character " + attempt.character + ", observed "
|
||||
+ marker.map(Object::toString).orElse("missing/malformed")
|
||||
+ ". Items and receipt retained. RESTORED receipts require manual reconciliation too.");
|
||||
return EquipmentStorage.RestoreResult.INVALID_BOX;
|
||||
}
|
||||
mark(attempt, EquipmentSessionMarker.Phase.RESTORING);
|
||||
var result = equipment.restore(attempt.player.getInventory(), attempt.owner, attempt.session,
|
||||
item -> controls.owned(item, attempt.owner, attempt.session),
|
||||
attempt.player.getItemOnCursor(), attempt.player::setItemOnCursor);
|
||||
// Returned refusals are read-only. Exceptions must retain the ambiguous RESTORING phase.
|
||||
mark(attempt, result == EquipmentStorage.RestoreResult.RESTORED
|
||||
? EquipmentSessionMarker.Phase.RESTORED : EquipmentSessionMarker.Phase.PACKED);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void sync(Attempt attempt) {
|
||||
try { attempt.player.updateInventory(); }
|
||||
catch (RuntimeException failure) { diagnostic(attempt, failure); }
|
||||
}
|
||||
|
||||
private void saveRemainingHealth(Attempt attempt) {
|
||||
if (!attempt.vitalsStarted || attempt.defeated || attempt.healthSaveRequested) return;
|
||||
attempt.healthSaveRequested = true; // Failed/uncertain writes are not authority for an automatic replay.
|
||||
try {
|
||||
var remaining = vitals.remaining(attempt.player, attempt.session, attempt.ordinaryVitals);
|
||||
var limit = NativeHealthLimit.read();
|
||||
persist(() -> characters.saveHealth(attempt.character, remaining, limit), (saved, failure) -> {
|
||||
if (failure != null || saved.isEmpty()) {
|
||||
diagnostic(attempt, failure != null ? failure : new IllegalStateException("Character unavailable for health save"));
|
||||
return;
|
||||
}
|
||||
attempt.healthAcknowledged = true;
|
||||
if (attempt.nativeRestored) persistExit(attempt, true);
|
||||
});
|
||||
} catch (RuntimeException failure) { diagnostic(attempt, failure); }
|
||||
}
|
||||
|
||||
private boolean restoreVitals(Attempt attempt) {
|
||||
if (vitals == null || attempt.ordinaryVitals == null) return true;
|
||||
try {
|
||||
if (vitals.restore(attempt.player, attempt.session, attempt.ordinaryVitals)) return true;
|
||||
} catch (RuntimeException failure) { diagnostic(attempt, failure); }
|
||||
notice(attempt.owner, "VITALS_RECOVERY", "Health/nutrition restoration was refused or ambiguous; retained receipt requires inspection.");
|
||||
return false;
|
||||
}
|
||||
|
||||
private void persistExit(Attempt attempt, boolean restored) {
|
||||
attempt.nativeRestored = restored;
|
||||
boolean complete = restored && (attempt.healthAcknowledged || attempt.defeated);
|
||||
attempt.saving = true;
|
||||
persist(() -> complete
|
||||
? receipts.completeExit(attempt.owner, attempt.session, switchDelay)
|
||||
: receipts.recordExit(attempt.owner, attempt.session, switchDelay), (state, failure) -> {
|
||||
attempt.saving = false;
|
||||
if (failure != null) diagnostic(attempt, failure);
|
||||
else if (complete) { attempt.gearAcknowledged = true; release(attempt); }
|
||||
});
|
||||
}
|
||||
|
||||
public synchronized void cancelEntry(UUID player) {
|
||||
var attempt = pending.remove(player);
|
||||
if (attempt != null) abandon(attempt);
|
||||
}
|
||||
|
||||
private void abandon(Attempt attempt) {
|
||||
if (attempt.modeStarted || attempt.effectsStarted || attempt.cleanupAttempted || attempt.uncertainSave) return;
|
||||
if (attempt.acknowledged) {
|
||||
attempt.cleaning = true;
|
||||
attempt.cleanupAttempted = true;
|
||||
persist(() -> receipts.clearReceipt(attempt.owner, attempt.session), (state, failure) -> {
|
||||
attempt.cleaning = false;
|
||||
if (failure == null) release(attempt); else diagnostic(attempt, failure);
|
||||
});
|
||||
} else if (!attempt.saving) release(attempt);
|
||||
}
|
||||
|
||||
private void release(Attempt attempt) {
|
||||
if (attempt.defeated && (!attempt.deathResolved || !attempt.gearAcknowledged || !attempt.bookDelivered)) return;
|
||||
owned.remove(attempt.owner, attempt);
|
||||
if (attempt.claim != null) attempt.claim.close();
|
||||
}
|
||||
private boolean current(Attempt attempt) { return !closed && pending.get(attempt.owner) == attempt; }
|
||||
private boolean entryCurrent(Attempt attempt) {
|
||||
if (!current(attempt)) { abandon(attempt); return false; }
|
||||
if (!attempt.player.isOnline()
|
||||
|| attempt.previousGameMode != null && !attempt.modeStarted
|
||||
&& !attempt.player.getGameMode().name().equals(attempt.previousGameMode)
|
||||
|| attempt.ordinaryVitals != null && !attempt.vitalsStarted && !vitals.unchanged(attempt.player, attempt.ordinaryVitals)
|
||||
|| attempt.markerValidated && (EquipmentSessionMarker.present(attempt.player) != (attempt.entryMarker != null)
|
||||
|| !Objects.equals(attempt.entryMarker, EquipmentSessionMarker.read(attempt.player).orElse(null)))
|
||||
|| !Arrays.equals(attempt.snapshot, snapshot(attempt.player))
|
||||
|| !Objects.equals(attempt.cursor, copy(attempt.player.getItemOnCursor()))
|
||||
|| !sheets.identify(attempt.player.getInventory().getItemInOffHand()).filter(attempt.character::equals).isPresent()) {
|
||||
refuse(attempt, "STALE_ENTRY", "Entry changed before preparation completed; retry with your current equipment.");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private void refuse(Attempt attempt, String code, String message) {
|
||||
pending.remove(attempt.owner, attempt);
|
||||
abandon(attempt);
|
||||
notice(attempt.owner, code, message);
|
||||
}
|
||||
private void fail(Attempt attempt, Throwable failure) {
|
||||
if (attempt.effectsStarted && owned.get(attempt.owner) == attempt) attempt.nativeUncertain = true;
|
||||
pending.remove(attempt.owner, attempt);
|
||||
active.remove(attempt.owner, attempt);
|
||||
withdrawPresentation(attempt);
|
||||
if (attempt.vitalsStarted) {
|
||||
// Only native callbacks can reach this phase. Preserve observed character damage
|
||||
// before independent vitals teardown; the uncertain equipment receipt stays owned.
|
||||
saveRemainingHealth(attempt);
|
||||
restoreVitals(attempt);
|
||||
}
|
||||
abandon(attempt);
|
||||
diagnostic(attempt, failure);
|
||||
}
|
||||
private void diagnostic(Attempt attempt, Throwable failure) {
|
||||
diagnostic(new Failure(attempt.owner, attempt.session, failure));
|
||||
}
|
||||
private void diagnostic(Failure failure) {
|
||||
try { diagnostics.accept(failure); }
|
||||
catch (RuntimeException ignored) { /* Observers cannot abort owned cleanup or shutdown. */ }
|
||||
}
|
||||
private void notice(UUID owner, String code, String message) {
|
||||
try { notices.accept(new Notice(owner, code, message)); }
|
||||
catch (RuntimeException failure) { diagnostic(new Failure(owner, null, failure)); }
|
||||
}
|
||||
private synchronized void schedule(Attempt attempt, Runnable callback) {
|
||||
// close already invalidates pending work and owns its never-packed cleanup. Accepted
|
||||
// reads may still finish, but must not require another task on a disabled scheduler.
|
||||
if (closed) return;
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
synchronized (EquipmentSessions.this) {
|
||||
try { callback.run(); }
|
||||
catch (RuntimeException failure) { fail(attempt, failure); }
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException failure) { fail(attempt, failure); }
|
||||
}
|
||||
private static ItemStack copy(ItemStack item) { return item == null ? null : item.clone(); }
|
||||
private static ItemStack[] snapshot(Player player) {
|
||||
return Arrays.stream(player.getInventory().getContents()).map(EquipmentSessions::copy).toArray(ItemStack[]::new);
|
||||
}
|
||||
|
||||
/** Explicit proof-based reconciliation; never infer restoration from an absent box. */
|
||||
public synchronized void recover(Player player) { recover(player, false); }
|
||||
|
||||
/** Join reconciliation: recover a pending receipt, otherwise request normal entry. */
|
||||
public synchronized void arrive(Player player) { recover(player, true); }
|
||||
|
||||
private void recover(Player player, boolean arrival) {
|
||||
UUID owner = player.getUniqueId();
|
||||
invalidateCursor(owner);
|
||||
if (closed || !player.isOnline()) return;
|
||||
var previous = owned.get(owner);
|
||||
if (previous != null && previous.defeated && (arrival || previous.gearAcknowledged
|
||||
|| previous.bookDelivered || previous.player != player)) {
|
||||
notice(owner, "DEFEAT_PENDING", "Death or Tail conversion is pending/uncertain; retained state requires inspection, not automatic replay."); return;
|
||||
}
|
||||
if (previous != null && previous.nativeUncertain) {
|
||||
notice(owner, "NATIVE_UNCERTAIN", "A native equipment write had an uncertain outcome; automatic restoration is unsafe. Retain items for inspection."); return;
|
||||
}
|
||||
if (transitioning.containsKey(owner) || active.containsKey(owner)
|
||||
|| previous != null && (previous.saving || previous.cleaning)) {
|
||||
notice(owner, "BUSY", "A session transition is still pending; recovery did not change items."); return;
|
||||
}
|
||||
cancelEntry(owner);
|
||||
var attempt = new Attempt(player, owner, null);
|
||||
attempt.recoveryOwner = previous;
|
||||
// A recovered receipt has no process-local never-packed proof.
|
||||
attempt.effectsStarted = true;
|
||||
attempt.arrival = arrival;
|
||||
pending.put(owner, attempt);
|
||||
receipts.find(owner).whenComplete((state, failure) ->
|
||||
schedule(attempt, () -> recovered(attempt, state, failure)));
|
||||
}
|
||||
|
||||
private synchronized void recovered(Attempt attempt, Optional<EquipmentSessionStore.State> state, Throwable failure) {
|
||||
if (!current(attempt)) return;
|
||||
pending.remove(attempt.owner, attempt);
|
||||
if (!attempt.player.isOnline()) return;
|
||||
if (owned.get(attempt.owner) != attempt.recoveryOwner) {
|
||||
notice(attempt.owner, "STALE_RECOVERY", "Session ownership changed after the recovery read; no old receipt was replayed.");
|
||||
return;
|
||||
}
|
||||
if (failure != null) { diagnostic(attempt, failure); return; }
|
||||
var receipt = state.map(EquipmentSessionStore.State::pending).orElse(null);
|
||||
if (receipt == null) {
|
||||
if (attempt.arrival) {
|
||||
if (sheets.identify(attempt.player.getInventory().getItemInOffHand()).isPresent()) enter(attempt.player);
|
||||
else if (EquipmentSessionMarker.present(attempt.player) || hasRemnants(attempt.player)) {
|
||||
notice(attempt.owner, "NATIVE_RECOVERY_REQUIRED", "Native equipment remnants have no pending receipt; items were retained for inspection.");
|
||||
}
|
||||
return; // Ordinary no-sheet/no-receipt arrivals are not rejected entry attempts.
|
||||
}
|
||||
notice(attempt.owner, "NO_RECEIPT", "No saved equipment receipt is available; items were left unchanged."); return;
|
||||
}
|
||||
attempt.character = receipt.characterId();
|
||||
attempt.session = receipt.sessionId();
|
||||
attempt.previousGameMode = receipt.previousGameMode();
|
||||
attempt.ordinaryVitals = receipt.ordinaryVitals();
|
||||
attempt.vitalsStarted = attempt.ordinaryVitals != null;
|
||||
attempt.healthAcknowledged = !attempt.vitalsStarted;
|
||||
attempt.modeStarted = attempt.previousGameMode != null;
|
||||
var previous = owned.get(attempt.owner);
|
||||
if (previous != null && !attempt.session.equals(previous.session)) {
|
||||
notice(attempt.owner, "SESSION_MISMATCH", "Saved and process-local sessions disagree; items were left unchanged."); return;
|
||||
}
|
||||
if (previous != null && (previous.defeated || previous.vitalsStarted)) {
|
||||
// Explicit same-lifetime equipment recovery still uses matching receipt/PACKED
|
||||
// proof. Keep the original death authority and its pending worker completion;
|
||||
// do not replace it with a recovery Attempt that could release its claim early.
|
||||
previous.deliveryInvalidated = true;
|
||||
restoreExit(previous);
|
||||
return;
|
||||
}
|
||||
if (previous != null) {
|
||||
attempt.claim = previous.claim;
|
||||
attempt.gearRestoredForModeRecovery = previous.player == attempt.player && previous.gearRestoredForModeRecovery;
|
||||
}
|
||||
owned.put(attempt.owner, attempt);
|
||||
transitioning.put(attempt.owner, attempt);
|
||||
try {
|
||||
saveRemainingHealth(attempt);
|
||||
boolean modeRestored = restoreGameMode(attempt);
|
||||
var result = restoreMarked(attempt);
|
||||
boolean vitalsRestored = restoreVitals(attempt);
|
||||
if (result == EquipmentStorage.RestoreResult.RESTORED) {
|
||||
if (!modeRestored || !vitalsRestored || !attempt.healthAcknowledged) attempt.gearRestoredForModeRecovery = true;
|
||||
persistExit(attempt, modeRestored && vitalsRestored);
|
||||
sync(attempt);
|
||||
} else notice(attempt.owner, result.name(), "Equipment recovery refused: " + result + "; receipt and items retained.");
|
||||
} catch (RuntimeException error) {
|
||||
fail(attempt, error);
|
||||
notice(attempt.owner, "NATIVE_UNCERTAIN", "Recovery mutation failed; native phase, items and receipt retained for inspection.");
|
||||
} finally {
|
||||
transitioning.remove(attempt.owner, attempt);
|
||||
finishDrain();
|
||||
}
|
||||
}
|
||||
@Override public synchronized void close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
try {
|
||||
for (var attempt : transitioning.values()) {
|
||||
attempt.exitRequested = true;
|
||||
withdrawPresentation(attempt);
|
||||
}
|
||||
// Accepted main-thread tasks may be discarded on disable. Report now as well as
|
||||
// from worker completion; neither path needs a scheduler on a disabled plugin.
|
||||
for (var attempt : java.util.List.copyOf(owned.values())) {
|
||||
if (attempt.defeated && !attempt.bookDelivered) conversionUncertain(attempt, "Shutdown before confirmed Tail conversion");
|
||||
}
|
||||
for (var owner : java.util.List.copyOf(pending.keySet())) cancelEntry(owner);
|
||||
for (var attempt : java.util.List.copyOf(active.values())) exit(attempt.player);
|
||||
claims.close();
|
||||
} finally {
|
||||
closeSweepFinished = true;
|
||||
finishDrain();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
|
||||
/**
|
||||
* Read-only access to the pinned runtime's health range; never changes server settings or attributes.
|
||||
* Call on the server thread after registry initialization. The API exposes no range getter, so use the
|
||||
* supported runtime's public Craft/native accessors and fail explicitly if they are incompatible.
|
||||
* This reads the current range on each call, not a guessed default or cached configuration value.
|
||||
* Native session/health application is separate and must revalidate its context before mutation.
|
||||
*/
|
||||
public final class NativeHealthLimit {
|
||||
private NativeHealthLimit() { }
|
||||
|
||||
public static BigDecimal read() {
|
||||
try {
|
||||
Object range = Attribute.MAX_HEALTH.getClass().getMethod("getHandle").invoke(Attribute.MAX_HEALTH);
|
||||
double maximum = ((Number) range.getClass().getMethod("getMaxValue").invoke(range)).doubleValue();
|
||||
if (!Double.isFinite(maximum) || maximum <= 0
|
||||
|| !Float.isFinite((float) maximum) || (float) maximum <= 0) {
|
||||
throw new IllegalStateException("Native maximum health must be positive and representable as Minecraft health");
|
||||
}
|
||||
return BigDecimal.valueOf(maximum);
|
||||
} catch (ReflectiveOperationException | ClassCastException failure) {
|
||||
throw new IllegalStateException("Cannot read the supported native maximum-health range", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
|
||||
/**
|
||||
* Purpur 2618 main-storage-only exchange, called on the server thread after revalidation.
|
||||
* Public Craft/native accessors (as with NativeHealthLimit), no private-field access.
|
||||
* Native NonNullList.set only replaces a list reference: no item copying, packet emission,
|
||||
* equip notification, menu recomputation or plugin callback between the two writes.
|
||||
* Caller syncs AFTER completing/invalidation of its one-use move. Fail closed on other APIs.
|
||||
* Not a crash-atomic operation or a portable guarantee for arbitrary Inventory adapters.
|
||||
*/
|
||||
final class NativeMainInventorySwap {
|
||||
private NativeMainInventorySwap() { }
|
||||
|
||||
static void swap(PlayerInventory inventory, int source, int destination) {
|
||||
if (source < 9 || source >= 36 || destination < 9 || destination >= 36) {
|
||||
throw new IllegalArgumentException("Only main storage may be exchanged");
|
||||
}
|
||||
try {
|
||||
var craft = Class.forName("org.bukkit.craftbukkit.inventory.CraftInventoryPlayer");
|
||||
var nativeInventory = Class.forName("net.minecraft.world.entity.player.Inventory");
|
||||
Object handle = craft.getMethod("getInventory").invoke(craft.cast(inventory));
|
||||
Object contents = nativeInventory.getMethod("getNonEquipmentItems").invoke(handle);
|
||||
if (contents.getClass() != Class.forName("net.minecraft.core.NonNullList")
|
||||
|| !(contents instanceof List<?> items) || items.size() != 36) {
|
||||
throw new IllegalStateException("Unsupported native main storage");
|
||||
}
|
||||
exchange(items, source, destination);
|
||||
} catch (ReflectiveOperationException failure) {
|
||||
throw new IllegalStateException("Native main-storage exchange unavailable", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> void exchange(List<T> items, int source, int destination) {
|
||||
T box = Objects.requireNonNull(items.get(source));
|
||||
T displaced = Objects.requireNonNull(items.get(destination));
|
||||
items.set(destination, box);
|
||||
items.set(source, displaced);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
|
||||
|
||||
/**
|
||||
* Purpur 2618 instance-local effective-value lease. Base/modifiers remain in the native
|
||||
* instance, so additions, removals, potion expiry and serialization keep their normal owners.
|
||||
* The pinned dirty callback is synchronous: no polling interval can expose an external maximum.
|
||||
* No global attribute/range is changed. Native compatibility tests must gate runtime upgrades.
|
||||
*/
|
||||
public final class NativeMaximumHealth implements AutoCloseable {
|
||||
private static final Field DIRTY = field("dirty");
|
||||
private static final Field VALUE = field("cachedValue");
|
||||
private static final Field CALLBACK = field("onDirty");
|
||||
private final AttributeInstance attribute;
|
||||
private final Consumer<AttributeInstance> previous;
|
||||
private final Consumer<AttributeInstance> callback = this::changed;
|
||||
private final double maximum;
|
||||
private boolean closed;
|
||||
|
||||
/** Exercise the pinned hook on a detached instance before exposing any player entry. */
|
||||
public static void prepare() {
|
||||
var probe = new AttributeInstance(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH, ignored -> {});
|
||||
double bound = Math.min(10, NativeHealthLimit.read().doubleValue());
|
||||
try (var lease = new NativeMaximumHealth(probe, bound)) {
|
||||
Objects.requireNonNull(lease);
|
||||
if (probe.getValue() != bound) throw new IllegalStateException("Native maximum hook did not apply");
|
||||
probe.setBaseValue(probe.getBaseValue() + 1);
|
||||
if (probe.getValue() != bound) throw new IllegalStateException("Native dirty hook did not retain the maximum");
|
||||
}
|
||||
if (probe.getValue() != probe.getAttribute().value().sanitizeValue(probe.getBaseValue())) {
|
||||
throw new IllegalStateException("Native maximum hook did not restore ordinary calculation");
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public NativeMaximumHealth(AttributeInstance attribute, double maximum) {
|
||||
this.attribute = Objects.requireNonNull(attribute);
|
||||
if (!Double.isFinite(maximum) || maximum <= 0) throw new IllegalArgumentException("Invalid fantasy maximum");
|
||||
this.maximum = maximum;
|
||||
try { previous = (Consumer<AttributeInstance>) CALLBACK.get(attribute); }
|
||||
catch (ReflectiveOperationException failure) { throw incompatible(failure); }
|
||||
try {
|
||||
CALLBACK.set(attribute, callback);
|
||||
changed(attribute);
|
||||
} catch (ReflectiveOperationException | RuntimeException failure) {
|
||||
try { close(); }
|
||||
catch (RuntimeException cleanup) { failure.addSuppressed(cleanup); }
|
||||
throw incompatible(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void changed(AttributeInstance changed) {
|
||||
if (!closed) {
|
||||
try {
|
||||
VALUE.setDouble(attribute, maximum);
|
||||
DIRTY.setBoolean(attribute, false);
|
||||
} catch (ReflectiveOperationException failure) { throw incompatible(failure); }
|
||||
}
|
||||
previous.accept(changed);
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
try {
|
||||
// Never overwrite a later callback installed by someone else. If it wraps ours,
|
||||
// our now-closed callback simply passes through and no longer overrides values.
|
||||
if (CALLBACK.get(attribute) == callback) CALLBACK.set(attribute, previous);
|
||||
DIRTY.setBoolean(attribute, true);
|
||||
previous.accept(attribute);
|
||||
} catch (ReflectiveOperationException failure) { throw incompatible(failure); }
|
||||
}
|
||||
|
||||
private static Field field(String name) {
|
||||
try {
|
||||
var field = AttributeInstance.class.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
return field;
|
||||
} catch (ReflectiveOperationException failure) { throw incompatible(failure); }
|
||||
}
|
||||
private static IllegalStateException incompatible(Exception failure) {
|
||||
return new IllegalStateException("Unsupported native maximum-health internals; no fallback health policy", failure);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
/** Public particles only; never grants gameplay state, protection, health or persistence authority. */
|
||||
public final class SessionVisuals implements AutoCloseable {
|
||||
private final EquipmentSessions sessions;
|
||||
private final Consumer<Throwable> failures;
|
||||
private BukkitTask task;
|
||||
private boolean closed;
|
||||
|
||||
public SessionVisuals(EquipmentSessions sessions, Consumer<Throwable> failures) {
|
||||
this.sessions = Objects.requireNonNull(sessions); this.failures = Objects.requireNonNull(failures);
|
||||
}
|
||||
public void install(Plugin plugin) {
|
||||
if (closed || task != null) throw new IllegalStateException("Visual lifetime already used");
|
||||
task = plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
|
||||
if (closed) return;
|
||||
for (var player : plugin.getServer().getOnlinePlayers()) {
|
||||
try {
|
||||
var active = sessions.active(player.getUniqueId());
|
||||
if (active.isPresent() && sessions.current(active.orElseThrow())) burst(player, Color.BLUE, 3);
|
||||
} catch (RuntimeException failure) { failures.accept(failure); }
|
||||
}
|
||||
}, 1L, 10L);
|
||||
}
|
||||
public static void burst(Player player, Color color, int count) {
|
||||
player.getWorld().spawnParticle(Particle.DUST, player.getLocation().add(0, 1, 0), count,
|
||||
0.3, 0.4, 0.3, 0, new Particle.DustOptions(color, 1));
|
||||
}
|
||||
@Override public void close() {
|
||||
closed = true;
|
||||
if (task != null) { task.cancel(); task = null; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.OrdinaryVitals;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.craftbukkit.entity.CraftPlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/** Server-thread native overlay; native attributes themselves are never snapshotted/replayed. */
|
||||
public final class SessionVitals implements AutoCloseable {
|
||||
private static final NamespacedKey KEY = new NamespacedKey("fantasystick", "vitals_session");
|
||||
private enum Phase { APPLYING, APPLIED, RESTORING, RELEASED }
|
||||
private record Mark(UUID session, Phase phase, double maximum, OrdinaryVitals ordinary) { }
|
||||
private record Lease(UUID session, NativeMaximumHealth maximum) { }
|
||||
private final Map<UUID, Lease> leases = new HashMap<>();
|
||||
private boolean closed;
|
||||
|
||||
public SessionVitals() { NativeMaximumHealth.prepare(); }
|
||||
|
||||
public OrdinaryVitals capture(Player player) {
|
||||
return new OrdinaryVitals(player.getHealth(), player.getFoodLevel(), player.getSaturation(), player.getExhaustion(),
|
||||
player.isHealthScaled(), player.getHealthScale());
|
||||
}
|
||||
|
||||
public boolean available(Player player) {
|
||||
var mark = read(player);
|
||||
return !closed && (!player.getPersistentDataContainer().has(KEY) || mark != null && mark.phase() == Phase.RELEASED);
|
||||
}
|
||||
|
||||
public boolean unchanged(Player player, OrdinaryVitals ordinary) {
|
||||
return ordinary != null && ordinary.health() > 0 && ordinary.equals(capture(player));
|
||||
}
|
||||
|
||||
/** Caller already acknowledged this ordinary snapshot in its player/session receipt. */
|
||||
public void enter(Player player, UUID session, OrdinaryVitals ordinary, CharacterRecord record) {
|
||||
if (!available(player) || !unchanged(player, ordinary) || leases.containsKey(player.getUniqueId())) {
|
||||
throw new IllegalStateException("Stale native vitals entry");
|
||||
}
|
||||
double maximum = record.maximumHealth().min(NativeHealthLimit.read()).doubleValue();
|
||||
write(player, new Mark(session, Phase.APPLYING, maximum, ordinary));
|
||||
var nativeAttribute = Objects.requireNonNull(((CraftPlayer) player).getHandle()
|
||||
.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH));
|
||||
try {
|
||||
var lease = new NativeMaximumHealth(nativeAttribute, maximum);
|
||||
leases.put(player.getUniqueId(), new Lease(session, lease));
|
||||
// Equal to the actual native maximum, not virtual health. Native attribute packets
|
||||
// use CraftPlayer's scaled snapshot, without exposing ordinary modifier arithmetic.
|
||||
// Initialize once BEFORE display delivery can reenter damage/healing handlers.
|
||||
player.setHealth(Math.min(record.health().doubleValue(), maximum));
|
||||
if (closed) throw new IllegalStateException("Vitals lifetime ended during entry");
|
||||
player.setHealthScale(maximum);
|
||||
if (closed) throw new IllegalStateException("Vitals lifetime ended during entry");
|
||||
write(player, new Mark(session, Phase.APPLIED, maximum, ordinary));
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
try { releaseMaximum(player, session); }
|
||||
catch (RuntimeException | LinkageError cleanup) { failure.addSuppressed(cleanup); }
|
||||
try { restoreScale(player, maximum, ordinary); }
|
||||
catch (RuntimeException | LinkageError cleanup) { failure.addSuppressed(cleanup); }
|
||||
// Leave APPLYING proof and the acknowledged receipt: an uncertain health setter
|
||||
// is not permission to heal from a stale snapshot or replay the character save.
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
public BigDecimal remaining(Player player, UUID session, OrdinaryVitals ordinary) {
|
||||
var mark = read(player);
|
||||
if (mark == null || !mark.session().equals(session) || !mark.ordinary().equals(ordinary) || mark.phase() != Phase.APPLIED) {
|
||||
throw new IllegalStateException("No matching applied fantasy vitals proof");
|
||||
}
|
||||
return BigDecimal.valueOf(Math.max(0, Math.min(player.getHealth(), mark.maximum())));
|
||||
}
|
||||
|
||||
public boolean restore(Player player, UUID session, OrdinaryVitals ordinary) {
|
||||
if (ordinary == null) return true; // Legacy equipment-only receipt, not health restoration authority.
|
||||
var mark = read(player);
|
||||
if (mark == null || !mark.session().equals(session) || !mark.ordinary().equals(ordinary)
|
||||
|| mark.phase() != Phase.APPLIED) {
|
||||
// Process-local hook ownership is sufficient to retire our maximum override,
|
||||
// never to replay ordinary health/nutrition when native setter proof is missing.
|
||||
releaseMaximum(player, session);
|
||||
return mark != null && mark.session().equals(session) && mark.ordinary().equals(ordinary) && mark.phase() == Phase.RELEASED;
|
||||
}
|
||||
write(player, new Mark(session, Phase.RESTORING, mark.maximum(), ordinary));
|
||||
// Reconcile restored equipment's native modifiers before clamping ordinary health.
|
||||
try { ((CraftPlayer) player).getHandle().detectEquipmentUpdates(); }
|
||||
finally { releaseMaximum(player, session); }
|
||||
// On restart there is no hook: native attribute serialization retained ordinary
|
||||
// base/permanent modifiers, and the native effect lifecycle owns potion expiry/removal.
|
||||
// CraftPlayer scale setters send health packets immediately (or queue one for damage
|
||||
// completion). Restore positive health first: a zero-health packet opens a client death
|
||||
// screen even when Paper cancels the death and the server-side player survives.
|
||||
player.setHealth(Math.min(ordinary.health(), Objects.requireNonNull(player.getAttribute(Attribute.MAX_HEALTH)).getValue()));
|
||||
player.setFoodLevel(ordinary.food()); player.setSaturation(ordinary.saturation()); player.setExhaustion(ordinary.exhaustion());
|
||||
restoreScale(player, mark.maximum(), ordinary);
|
||||
write(player, new Mark(session, Phase.RELEASED, mark.maximum(), ordinary));
|
||||
return true;
|
||||
}
|
||||
|
||||
private void releaseMaximum(Player player, UUID session) {
|
||||
var lease = leases.get(player.getUniqueId());
|
||||
if (lease != null && lease.session().equals(session)) {
|
||||
leases.remove(player.getUniqueId(), lease);
|
||||
lease.maximum().close();
|
||||
}
|
||||
}
|
||||
|
||||
private static void restoreScale(Player player, double maximum, OrdinaryVitals ordinary) {
|
||||
if (player.isHealthScaled() && player.getHealthScale() == maximum) {
|
||||
player.setHealthScale(ordinary.scale());
|
||||
player.setHealthScaled(ordinary.scaled());
|
||||
}
|
||||
}
|
||||
|
||||
/** Only removes this process's effective-value hooks; never replays unknown ordinary snapshots. */
|
||||
@Override public void close() {
|
||||
closed = true;
|
||||
RuntimeException errors = null;
|
||||
for (var lease : java.util.List.copyOf(leases.values())) {
|
||||
try { lease.maximum().close(); }
|
||||
catch (RuntimeException | LinkageError failure) {
|
||||
if (errors == null) errors = new IllegalStateException("Native maximum cleanup failed");
|
||||
errors.addSuppressed(failure);
|
||||
}
|
||||
}
|
||||
leases.clear();
|
||||
if (errors != null) throw errors;
|
||||
}
|
||||
|
||||
private static Mark read(Player player) {
|
||||
var data = player.getPersistentDataContainer();
|
||||
if (!data.has(KEY, PersistentDataType.STRING)) return null;
|
||||
try {
|
||||
String encoded = data.get(KEY, PersistentDataType.STRING);
|
||||
if (encoded.length() > 400) return null;
|
||||
String[] fields = encoded.split("\\|", -1);
|
||||
if (fields.length != 5 || !fields[0].equals("1")) return null;
|
||||
UUID session = UUID.fromString(fields[1]);
|
||||
double maximum = Double.parseDouble(fields[3]);
|
||||
if (!session.toString().equals(fields[1]) || !Double.isFinite(maximum) || maximum <= 0) return null;
|
||||
return new Mark(session, Phase.valueOf(fields[2]), maximum, OrdinaryVitals.decode(fields[4]));
|
||||
} catch (IllegalArgumentException invalid) { return null; }
|
||||
}
|
||||
private static void write(Player player, Mark mark) {
|
||||
player.getPersistentDataContainer().set(KEY, PersistentDataType.STRING,
|
||||
"1|" + mark.session() + "|" + mark.phase() + "|" + mark.maximum() + "|" + mark.ordinary().encode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Captured when a new fantasy session starts; changing this does not alter active sessions.
|
||||
# Admin command: /fantasystick config adventure-mode [true|false]
|
||||
adventure-mode: true
|
||||
@@ -2,5 +2,15 @@ name: FantasyStick
|
||||
version: ${version}
|
||||
main: games.dmg.fantasystick.FantasyStickPlugin
|
||||
api-version: "26.2"
|
||||
description: Transferable RPG characters for SoMC; bootstrap only, gameplay not implemented.
|
||||
depend: [ProtocolLib]
|
||||
description: Transferable characters, native fantasy health, recoverable equipment, character books and parties.
|
||||
author: dmg.games
|
||||
commands:
|
||||
fantasystick:
|
||||
description: Inspect/recover equipment sessions or configure fantasy mode.
|
||||
usage: /fantasystick <inspect|recover> <player-uuid> | config adventure-mode [true|false]
|
||||
permission: fantasystick.admin
|
||||
permissions:
|
||||
fantasystick.admin:
|
||||
description: Inspect/recover equipment sessions and configure fantasy mode.
|
||||
default: op
|
||||
@@ -0,0 +1,111 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import games.dmg.fantasystick.session.AdventureModeLease;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class AdventureModeLeaseNativeTest {
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void changesAndRestoresOnlyTheAcknowledgedHoldersOriginalMode() {
|
||||
for (var original : new GameMode[]{GameMode.SURVIVAL, GameMode.CREATIVE, GameMode.SPECTATOR}) {
|
||||
var actor = new Actor(original);
|
||||
var lease = new AdventureModeLease();
|
||||
var session = UUID.randomUUID();
|
||||
assertTrue(lease.enter(actor.player, session, original.name()));
|
||||
assertEquals(GameMode.ADVENTURE, actor.mode.get());
|
||||
assertTrue(lease.restore(actor.player, session, original.name()));
|
||||
assertEquals(original, actor.mode.get());
|
||||
assertTrue(lease.restore(actor.player, session, original.name()));
|
||||
assertEquals(original, actor.mode.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void adminChangeAwayAndBackToAdventureRelinquishesOriginalRestoration() {
|
||||
var actor = new Actor(GameMode.CREATIVE);
|
||||
var lease = new AdventureModeLease(); var session = UUID.randomUUID();
|
||||
assertTrue(lease.enter(actor.player, session, "CREATIVE"));
|
||||
actor.mode.set(GameMode.SURVIVAL);
|
||||
// Native event is dispatched before the second external mode change takes effect.
|
||||
var event = new org.bukkit.event.player.PlayerGameModeChangeEvent(actor.player, GameMode.ADVENTURE);
|
||||
lease.changed(event);
|
||||
actor.mode.set(GameMode.ADVENTURE);
|
||||
assertTrue(lease.restore(actor.player, session, "CREATIVE"));
|
||||
assertEquals(GameMode.ADVENTURE, actor.mode.get(), "Do not override the administrator's final mode");
|
||||
}
|
||||
|
||||
@Test void nativeVetoesLeaveEntryUntouchedAndRestorationRetryableWithoutClaimingSuccess() {
|
||||
var actor = new Actor(GameMode.SURVIVAL); var lease = new AdventureModeLease(); var session = UUID.randomUUID();
|
||||
actor.change = ignored -> {};
|
||||
assertFalse(lease.enter(actor.player, session, "SURVIVAL"));
|
||||
assertEquals(GameMode.SURVIVAL, actor.mode.get()); assertTrue(lease.available(actor.player));
|
||||
actor.change = actor.mode::set;
|
||||
assertTrue(lease.enter(actor.player, session, "SURVIVAL"));
|
||||
actor.change = ignored -> {};
|
||||
assertFalse(lease.restore(actor.player, session, "SURVIVAL"));
|
||||
assertEquals(GameMode.ADVENTURE, actor.mode.get()); assertFalse(lease.available(actor.player));
|
||||
actor.change = actor.mode::set;
|
||||
assertTrue(lease.restore(actor.player, session, "SURVIVAL"));
|
||||
assertEquals(GameMode.SURVIVAL, actor.mode.get());
|
||||
}
|
||||
|
||||
@Test void serializedMatchingProofRecoversButMissingWrongOrInterruptedProofNeverGuesses() throws Exception {
|
||||
var actor = new Actor(GameMode.CREATIVE); var session = UUID.randomUUID();
|
||||
assertTrue(new AdventureModeLease().enter(actor.player, session, "CREATIVE"));
|
||||
var reloaded = new Actor(GameMode.ADVENTURE);
|
||||
reloaded.pdc.readFromBytes(actor.pdc.serializeToBytes(), true);
|
||||
var lease = new AdventureModeLease();
|
||||
assertFalse(lease.restore(reloaded.player, UUID.randomUUID(), "CREATIVE"));
|
||||
assertFalse(lease.restore(reloaded.player, session, "SURVIVAL"));
|
||||
assertEquals(GameMode.ADVENTURE, reloaded.mode.get());
|
||||
assertTrue(lease.restore(reloaded.player, session, "CREATIVE"));
|
||||
assertEquals(GameMode.CREATIVE, reloaded.mode.get());
|
||||
var key = new org.bukkit.NamespacedKey("fantasystick", "adventure_session");
|
||||
for (String phase : new String[]{"APPLYING", "RESTORING", "unknown"}) {
|
||||
reloaded.mode.set(GameMode.ADVENTURE);
|
||||
reloaded.pdc.set(key, org.bukkit.persistence.PersistentDataType.STRING, "1|" + session + "|CREATIVE|" + phase);
|
||||
var before = reloaded.pdc.serializeToBytes();
|
||||
assertFalse(lease.restore(reloaded.player, session, "CREATIVE"));
|
||||
assertArrayEquals(before, reloaded.pdc.serializeToBytes());
|
||||
assertEquals(GameMode.ADVENTURE, reloaded.mode.get());
|
||||
}
|
||||
reloaded.pdc.remove(key);
|
||||
assertFalse(lease.restore(reloaded.player, session, "CREATIVE"));
|
||||
}
|
||||
|
||||
@Test void setterExceptionsRetainAmbiguousProofWithoutAutomaticRetryAndDisabledNeverTouchesMode() {
|
||||
var actor = new Actor(GameMode.SURVIVAL); var lease = new AdventureModeLease(); var session = UUID.randomUUID();
|
||||
actor.change = ignored -> { throw new IllegalStateException("uncertain"); };
|
||||
assertTrue(lease.enter(actor.player, session, null)); assertTrue(lease.restore(actor.player, session, null));
|
||||
assertTrue(lease.available(actor.player));
|
||||
assertThrows(IllegalStateException.class, () -> lease.enter(actor.player, session, "SURVIVAL"));
|
||||
assertFalse(lease.restore(actor.player, session, "SURVIVAL"));
|
||||
assertFalse(lease.available(actor.player));
|
||||
}
|
||||
|
||||
static final class Actor {
|
||||
final UUID id = UUID.randomUUID();
|
||||
final AtomicReference<GameMode> mode;
|
||||
java.util.function.Consumer<GameMode> change;
|
||||
final org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer pdc =
|
||||
new org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer(
|
||||
new org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry());
|
||||
final Player player;
|
||||
Actor(GameMode original) {
|
||||
mode = new AtomicReference<>(original);
|
||||
change = mode::set;
|
||||
player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> switch (name) {
|
||||
case "getUniqueId" -> id;
|
||||
case "getGameMode" -> mode.get();
|
||||
case "setGameMode" -> { change.accept((GameMode) args[0]); yield null; }
|
||||
case "getPersistentDataContainer" -> pdc;
|
||||
default -> throw new AssertionError(name);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,47 @@ class CharacterAnvilNamesNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test
|
||||
void onlyAcknowledgedCopyRenameRefreshesAnActiveOtherHolderAndLateCallbacksCannotReplay() throws Exception {
|
||||
var original = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
var anvil = new AnvilFixture();
|
||||
var sheet = new CharacterSheets().create(original); anvil.grid.setItem(0, sheet);
|
||||
var problems = new CopyOnWriteArrayList<CharacterAnvilNames.Failure>();
|
||||
var tasks = new java.util.concurrent.LinkedBlockingQueue<Runnable>();
|
||||
var output = new CharacterPresentationNativeTest.Output();
|
||||
var holder = java.util.UUID.randomUUID(); var session = java.util.UUID.randomUUID();
|
||||
var player = FantasyStickLifecycleNativeTest.port(org.bukkit.entity.Player.class, (name, args) -> holder);
|
||||
var main = Thread.currentThread();
|
||||
var presentation = new games.dmg.fantasystick.presentation.CharacterPresentation(output, tasks::add,
|
||||
() -> Thread.currentThread() == main, failure -> { throw new AssertionError(failure); });
|
||||
presentation.activate(player, session, original);
|
||||
try (var storage = new CharacterStorage(new YamlCharacterRepository(data), Clock.systemUTC())) {
|
||||
storage.create(original).join();
|
||||
var listener = new CharacterAnvilNames(storage, problems::add,
|
||||
org.bukkit.craftbukkit.inventory.CraftItemFactory.instance(), presentation::acknowledged);
|
||||
var renamed = named(sheet, Component.text("Copy's <red>saved name 雪 🐉"));
|
||||
listener.onTaken(new AnvilTakeResultEvent(anvil.actor.player, anvil.view, renamed));
|
||||
var saved = storage.find(original.id()).join().orElseThrow();
|
||||
assertEquals(original.name(), presentation.name(holder), "Worker may not perform native output");
|
||||
var callback = tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(callback); callback.run();
|
||||
assertEquals(saved.name(), presentation.name(holder)); assertEquals(1, output.renamed.size());
|
||||
assertNotEquals(holder, anvil.actor.id, "An inactive physical copy may rename another holder's active character");
|
||||
try (var channel = java.nio.channels.FileChannel.open(data.resolve("characters/.records.lock"), java.nio.file.StandardOpenOption.WRITE);
|
||||
var lock = channel.lock()) {
|
||||
assertTrue(lock.isValid());
|
||||
listener.onTaken(new AnvilTakeResultEvent(anvil.actor.player, anvil.view, named(sheet, Component.text("failed"))));
|
||||
assertEquals(saved, storage.find(original.id()).join().orElseThrow());
|
||||
assertEquals(1, problems.size()); assertTrue(tasks.isEmpty());
|
||||
assertEquals(saved.name(), presentation.name(holder));
|
||||
}
|
||||
listener.onTaken(new AnvilTakeResultEvent(anvil.actor.player, anvil.view, named(sheet, Component.text("late"))));
|
||||
storage.find(original.id()).join();
|
||||
callback = tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(callback);
|
||||
presentation.withdraw(holder, session); presentation.close(); callback.run();
|
||||
assertNull(presentation.name(holder)); assertEquals(1, output.renamed.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAcceptedNativeResultSavesItsNewNameWithoutTouchingInventoryOrPlayerXp() throws Exception {
|
||||
var original = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
@@ -60,7 +101,8 @@ class CharacterAnvilNamesNativeTest {
|
||||
assertEquals("Tail of Mira of Dawn — 雪", book.getTitle());
|
||||
var text = net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText();
|
||||
assertTrue(text.serialize(book.customName()).contains("Mira of Dawn — 雪"));
|
||||
assertTrue(book.pages().stream().map(text::serialize).anyMatch(page -> page.contains("Mira of Dawn — 雪")));
|
||||
assertTrue(book.pages().stream().map(text::serialize).collect(java.util.stream.Collectors.joining())
|
||||
.replace("\n", "").contains("Mira of Dawn — 雪"), "Readable wrapping must retain the full acknowledged name");
|
||||
assertTrue(problems.isEmpty());
|
||||
// Actor rejects all XP/cursor/inventory mutation calls and all worker-side player access.
|
||||
}
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Actual packaged input/book assembly with native pages/items and explicit client/scheduler ports. */
|
||||
class CharacterBookNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void queuedInspectionCannotOpenForAMovedSheetChangedSlotQuitOrDisabledLifetime() throws Exception {
|
||||
for (int route = 0; route < 4; route++) try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("route-" + route))) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data.resolve("route-" + route));
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
click(f, a); drainReads(f);
|
||||
assertEquals(1, f.tasks.size());
|
||||
switch (route) {
|
||||
case 0 -> { a.core.inventory.setItemInOffHand(null); f.changed(a); }
|
||||
case 1 -> a.core.inventory.getInventory().setSelectedSlot(1);
|
||||
case 2 -> { a.core.online = false; f.dispatcher.accept(new org.bukkit.event.player.PlayerQuitEvent(a.player, net.kyori.adventure.text.Component.empty())); }
|
||||
case 3 -> { f.plugin.setEnabled(false); f.awaitWorkers(); }
|
||||
default -> throw new AssertionError(route);
|
||||
}
|
||||
runQueued(f);
|
||||
assertTrue(a.books.isEmpty(), "Stale book callback opened a UI on route " + route);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void latestRequestWinsAndReloadsNamesWithoutRetainingAnOlderRead() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
click(f, a); drainReads(f);
|
||||
var characters = characters(f);
|
||||
characters.renameCharacter(a.core.record.id(), "Latest book name").get(5, TimeUnit.SECONDS);
|
||||
click(f, a); drainReads(f); runQueued(f);
|
||||
assertEquals(1, a.books.size());
|
||||
assertTrue(text(a.books.getFirst()).contains("Latest book name"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void cappedProgressAndSavedAbilitiesRenderWithoutCappingStatsOrRewritingProgress() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var old = a.core.record;
|
||||
var stats = new java.util.EnumMap<games.dmg.fantasystick.progression.Stat, java.math.BigInteger>(games.dmg.fantasystick.progression.Stat.class);
|
||||
stats.putAll(old.stats());
|
||||
var strength = new java.math.BigInteger("123456789012345678901234567890");
|
||||
stats.put(games.dmg.fantasystick.progression.Stat.STR, strength);
|
||||
var saved = new games.dmg.fantasystick.persistence.CharacterRecord(old.id(), old.name(), old.revision().add(java.math.BigInteger.ONE),
|
||||
stats, 30, java.math.BigInteger.valueOf(2900), java.math.BigInteger.valueOf(9), old.health(),
|
||||
java.util.Set.of("revive", "unavailable_saved_id"), old.loadout(), java.util.Map.of(), false, null, null);
|
||||
new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).replace(saved, old.revision());
|
||||
click(f, a); drainReads(f); runQueued(f);
|
||||
assertEquals(1, a.books.size());
|
||||
String rendered = text(a.books.getFirst()).replace("\n", "");
|
||||
for (String expected : java.util.List.of("Level: 30", "XP: MAX", "Unspent points: 9", "STR: " + strength,
|
||||
"revive", "unavailable_saved_id")) assertTrue(rendered.contains(expected), expected);
|
||||
assertEquals(saved, characters(f).find(old.id()).get(5, TimeUnit.SECONDS).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void nativePagesKeepLargeNumbersUnicodeNamesAndUnknownAbilitiesReadableAndComplete() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var old = a.core.record;
|
||||
var stats = new java.util.EnumMap<games.dmg.fantasystick.progression.Stat, java.math.BigInteger>(games.dmg.fantasystick.progression.Stat.class);
|
||||
stats.putAll(old.stats());
|
||||
String digits = "1234567890".repeat(400);
|
||||
stats.put(games.dmg.fantasystick.progression.Stat.STR, new java.math.BigInteger(digits));
|
||||
String name = "雪🐈".repeat(80);
|
||||
var learned = java.util.stream.IntStream.range(0, 50).mapToObj(i -> "unknown_ability_" + i).collect(java.util.stream.Collectors.toSet());
|
||||
var saved = new games.dmg.fantasystick.persistence.CharacterRecord(old.id(), name, old.revision().add(java.math.BigInteger.ONE),
|
||||
stats, old.level(), old.experience(), old.unspentPoints(), old.health(), learned, old.loadout(), old.cooldowns(), false, null, null);
|
||||
new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).replace(saved, old.revision());
|
||||
var before = a.core.snapshot();
|
||||
click(f, a); drainReads(f); runQueued(f);
|
||||
var content = org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(a.books.getLast())
|
||||
.get(net.minecraft.core.component.DataComponents.WRITTEN_BOOK_CONTENT);
|
||||
assertNotNull(content);
|
||||
for (var page : content.pages()) {
|
||||
String text = page.raw().getString();
|
||||
assertTrue(text.split("\\n", -1).length <= 13, "Native page exceeds visible line count");
|
||||
for (String line : text.split("\\n", -1)) assertTrue(line.codePoints().map(cp -> cp < 128 ? 6 : 9).sum() <= 108,
|
||||
"Native line exceeds conservative visible width: " + line.length());
|
||||
}
|
||||
String complete = text(a.books.getLast()).replace("\n", "");
|
||||
assertTrue(complete.contains(name)); assertTrue(complete.contains(digits));
|
||||
for (String ability : learned) assertTrue(complete.contains(ability), ability);
|
||||
assertArrayEquals(before, a.core.snapshot());
|
||||
assertEquals(saved, characters(f).find(saved.id()).get(5, TimeUnit.SECONDS).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void largeRecordsRemainCompleteThroughBoundedSingleUseNavigation() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
String digits = "1234567890".repeat(4000);
|
||||
var old = a.core.record;
|
||||
var stats = new java.util.EnumMap<games.dmg.fantasystick.progression.Stat, java.math.BigInteger>(games.dmg.fantasystick.progression.Stat.class);
|
||||
stats.putAll(old.stats()); stats.put(games.dmg.fantasystick.progression.Stat.STR, new java.math.BigInteger(digits));
|
||||
var saved = new games.dmg.fantasystick.persistence.CharacterRecord(old.id(), old.name(), old.revision().add(java.math.BigInteger.ONE),
|
||||
stats, old.level(), old.experience(), old.unspentPoints(), old.health(), old.learned(), old.loadout(), old.cooldowns(), false, null, null);
|
||||
new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).replace(saved, old.revision());
|
||||
byte[] bytes = Files.readAllBytes(data.resolve("characters").resolve(saved.id() + ".yml"));
|
||||
click(f, a); drainReads(f); runQueued(f);
|
||||
assertEquals(1, a.books.size(), "Large but supported records still open a native book");
|
||||
StringBuilder all = new StringBuilder();
|
||||
int volumes = 0;
|
||||
while (true) {
|
||||
var content = org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(a.books.getLast())
|
||||
.get(net.minecraft.core.component.DataComponents.WRITTEN_BOOK_CONTENT);
|
||||
assertNotNull(content); assertTrue(content.pages().size() <= 100, "Keep the chosen per-view payload bound (not a signed-book codec page limit)");
|
||||
for (var page : content.pages()) if (!hasClick(page.raw())) all.append(page.raw().getString().replace("\n", ""));
|
||||
if (!text(a.books.getLast()).contains("[Next pages]")) break;
|
||||
assertTrue(++volumes < 10, "Navigation must terminate, not repeat a truncated volume");
|
||||
var next = PartyBookNativeTest.button(a, "[Next pages]");
|
||||
if (volumes == 1) {
|
||||
var stranger = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
PartyBookNativeTest.click(f, stranger, next);
|
||||
for (var payload : java.util.List.of(net.minecraft.nbt.StringTag.valueOf("x".repeat(1000)),
|
||||
net.minecraft.nbt.StringTag.valueOf("not-a-token"), new net.minecraft.nbt.CompoundTag())) {
|
||||
PartyBookNativeTest.click(f, a, new net.minecraft.network.chat.ClickEvent.Custom(next.id(), java.util.Optional.of(payload)));
|
||||
}
|
||||
assertTrue(stranger.books.isEmpty());
|
||||
}
|
||||
PartyBookNativeTest.click(f, a, next); PartyBookNativeTest.click(f, a, next);
|
||||
drainReads(f); runQueued(f);
|
||||
assertEquals(volumes + 1, a.books.size(), "One native action cannot open two volumes");
|
||||
}
|
||||
assertTrue(volumes > 0); assertTrue(all.toString().contains(digits), "Every digit remains reachable in order");
|
||||
var previous = PartyBookNativeTest.button(a, "[Previous pages]");
|
||||
a.core.inventory.getInventory().setSelectedSlot(1);
|
||||
PartyBookNativeTest.click(f, a, previous); drainReads(f); runQueued(f);
|
||||
assertEquals(volumes + 1, a.books.size(), "Stale held-slot navigation has no authority");
|
||||
assertArrayEquals(bytes, Files.readAllBytes(data.resolve("characters").resolve(saved.id() + ".yml")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void acknowledgedRenameTransferAndReloadInspectTheCurrentRecordWithoutCarryingTheFormerHoldersView() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var b = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.players.put(b.core.id, b.player); f.activate(a);
|
||||
click(f, a); drainReads(f); // Old holder has a queued result, not a delivered book.
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
var renamed = characters(f).renameCharacter(a.core.record.id(), "Traded 雪 character").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
runQueued(f); assertTrue(a.books.isEmpty());
|
||||
b.core.inventory.setItemInOffHand(new games.dmg.fantasystick.items.CharacterSheets().create(renamed));
|
||||
f.activate(b); click(f, b); drainReads(f); runQueued(f);
|
||||
assertTrue(text(b.books.getLast()).replace("\n", "").contains(renamed.name()));
|
||||
assertTrue(a.books.isEmpty());
|
||||
f.plugin.setEnabled(false); f.awaitWorkers();
|
||||
f.players.clear(); f.plugin.setEnabled(true);
|
||||
f.players.put(b.core.id, b.player); f.reenter(b);
|
||||
var before = b.core.snapshot();
|
||||
var path = data.resolve("characters").resolve(renamed.id() + ".yml");
|
||||
byte[] saved = Files.readAllBytes(path);
|
||||
click(f, b); drainReads(f); runQueued(f);
|
||||
assertTrue(text(b.books.getLast()).replace("\n", "").contains(renamed.name()));
|
||||
var meta = (org.bukkit.inventory.meta.BookMeta) b.books.getLast().getItemMeta();
|
||||
assertEquals("Character", meta.getTitle()); assertEquals("Fantasy Stick", meta.getAuthor());
|
||||
assertArrayEquals(saved, Files.readAllBytes(path)); assertArrayEquals(before, b.core.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasClick(net.minecraft.network.chat.Component component) {
|
||||
return component.getStyle().getClickEvent() != null || component.getSiblings().stream().anyMatch(CharacterBookNativeTest::hasClick);
|
||||
}
|
||||
|
||||
@Test void malformedRecordReadLeavesDataAndInventoryUntouchedAndCanBeRetriedAfterRepair() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var path = data.resolve("characters").resolve(a.core.record.id() + ".yml");
|
||||
byte[] valid = Files.readAllBytes(path);
|
||||
byte[] invalid = "schema-version: malformed\n".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
var before = a.core.snapshot();
|
||||
Files.write(path, invalid); click(f, a); drainReads(f); runQueued(f);
|
||||
assertTrue(a.books.isEmpty());
|
||||
assertTrue(a.messages.stream().anyMatch(message -> message.contains("could not be loaded")));
|
||||
assertArrayEquals(invalid, Files.readAllBytes(path)); assertArrayEquals(before, a.core.snapshot());
|
||||
Files.write(path, valid); click(f, a); drainReads(f); runQueued(f);
|
||||
assertEquals(1, a.books.size());
|
||||
assertArrayEquals(valid, Files.readAllBytes(path)); assertArrayEquals(before, a.core.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void bookAdapterIgnoresOtherControlsAndNativeItemVetoes() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var vetoed = interaction(a); vetoed.setUseItemInHand(Event.Result.DENY); f.dispatcher.accept(vetoed);
|
||||
a.core.inventory.getInventory().setSelectedSlot(1); click(f, a);
|
||||
a.core.inventory.getInventory().setSelectedSlot(2); click(f, a);
|
||||
drainReads(f); runQueued(f);
|
||||
assertTrue(a.books.isEmpty());
|
||||
assertTrue(a.messages.isEmpty(), "Inert controls do not manufacture book errors or mutate items");
|
||||
}
|
||||
}
|
||||
|
||||
private static String text(org.bukkit.inventory.ItemStack book) {
|
||||
var content = org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(book)
|
||||
.get(net.minecraft.core.component.DataComponents.WRITTEN_BOOK_CONTENT);
|
||||
assertNotNull(content);
|
||||
return content.pages().stream().map(page -> page.raw().getString()).collect(java.util.stream.Collectors.joining("\n"));
|
||||
}
|
||||
private static CharacterStorage characters(FantasyStickLifecycleNativeTest.Fixture f) {
|
||||
return (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
}
|
||||
private static void drainReads(FantasyStickLifecycleNativeTest.Fixture f) throws Exception {
|
||||
characters(f).find(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
private static PlayerInteractEvent interaction(FantasyStickLifecycleNativeTest.Actor a) {
|
||||
return new PlayerInteractEvent(a.player, Action.RIGHT_CLICK_AIR, a.core.inventory.getItemInMainHand(), null,
|
||||
BlockFace.SELF, EquipmentSlot.HAND);
|
||||
}
|
||||
private static void click(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor a) {
|
||||
var event = interaction(a); f.dispatcher.accept(event);
|
||||
assertEquals(Event.Result.DENY, event.useItemInHand());
|
||||
}
|
||||
private static void runQueued(FantasyStickLifecycleNativeTest.Fixture f) {
|
||||
Runnable task;
|
||||
while ((task = f.tasks.poll()) != null) task.run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import games.dmg.fantasystick.presentation.CharacterChatNames;
|
||||
import io.papermc.paper.chat.ChatRenderer;
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.UUID;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.chat.SignedMessage;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CharacterChatNamesNativeTest {
|
||||
@Test void nativeRendererReceivesLiteralSessionNameWithoutReplacingSignedBodyOrRecipients() {
|
||||
UUID id = UUID.randomUUID();
|
||||
Player player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> {
|
||||
assertEquals("getUniqueId", name); return id;
|
||||
});
|
||||
var names = new HashMap<UUID, String>();
|
||||
String name = "<rainbow>雪 🐉 literal name longer than sixteen";
|
||||
names.put(id, name);
|
||||
var listener = new CharacterChatNames(names::get);
|
||||
var body = Component.text("original signed <body>");
|
||||
var signed = SignedMessage.system("original signed <body>", body);
|
||||
var viewers = new HashSet<Audience>(); viewers.add(Audience.empty());
|
||||
ChatRenderer renderer = (sender, display, message, viewer) -> {
|
||||
assertSame(player, sender); assertSame(body, message);
|
||||
assertEquals(Component.text(name), display);
|
||||
return Component.text("prefix ").append(display).append(message);
|
||||
};
|
||||
var event = new AsyncChatEvent(true, player, viewers, renderer, body, body, signed);
|
||||
listener.onChat(event);
|
||||
assertSame(body, event.message()); assertSame(body, event.originalMessage());
|
||||
assertSame(signed, event.signedMessage()); assertEquals(viewers, event.viewers()); assertFalse(event.isCancelled());
|
||||
// The renderer may run after a switch; this accepted event captures its immutable sender name.
|
||||
names.put(id, "replacement");
|
||||
assertEquals(Component.text("prefix ").append(Component.text(name)).append(body),
|
||||
event.renderer().render(player, Component.text("account"), event.message(), Audience.empty()));
|
||||
}
|
||||
|
||||
@Test void cancellationsAndOrdinaryRenderersAreUntouched() {
|
||||
UUID id = UUID.randomUUID();
|
||||
Player player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> id);
|
||||
var listener = new CharacterChatNames(ignored -> "fantasy");
|
||||
var body = Component.text("body"); var renderer = ChatRenderer.defaultRenderer();
|
||||
var event = new AsyncChatEvent(true, player, new HashSet<>(), renderer, body, body, SignedMessage.system("body", body));
|
||||
event.setCancelled(true); listener.onChat(event);
|
||||
assertTrue(event.isCancelled()); assertSame(renderer, event.renderer());
|
||||
event.setCancelled(false); new CharacterChatNames(ignored -> null).onChat(event);
|
||||
assertSame(renderer, event.renderer()); assertSame(body, event.message());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import games.dmg.fantasystick.crafting.CharacterFactory;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation;
|
||||
import games.dmg.fantasystick.progression.ProgressionRules;
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CharacterPresentationNativeTest {
|
||||
@Test void immutableSessionNamesWithdrawBeforeOutputFailureAndRejectOldAcknowledgments() {
|
||||
UUID holder = UUID.randomUUID(); var first = UUID.randomUUID(); var second = UUID.randomUUID();
|
||||
var player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> { assertEquals("getUniqueId", name); return holder; });
|
||||
var record = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
var tasks = new ArrayList<Runnable>(); var failures = new ArrayList<Throwable>();
|
||||
var output = new Output();
|
||||
var presentation = new CharacterPresentation(output, tasks::add, () -> true, failures::add);
|
||||
presentation.activate(player, first, record);
|
||||
assertEquals(record.name(), presentation.name(holder));
|
||||
assertEquals(1, output.shown.size());
|
||||
var snapshot = presentation.snapshot();
|
||||
var renamed = rename(record, "雪 <red>literal 🐉", 1);
|
||||
presentation.acknowledged(renamed);
|
||||
presentation.withdraw(holder, first);
|
||||
presentation.activate(player, second, rename(record, "new authoritative", 2));
|
||||
tasks.forEach(Runnable::run); tasks.clear();
|
||||
assertEquals("new authoritative", presentation.name(holder));
|
||||
assertEquals(record.name(), snapshot.get(holder).name());
|
||||
presentation.withdraw(holder, first); // Old token cannot erase replacement.
|
||||
assertEquals("new authoritative", presentation.name(holder));
|
||||
output.failClear = true;
|
||||
presentation.withdraw(holder, second);
|
||||
assertNull(presentation.name(holder)); assertEquals(1, failures.size());
|
||||
presentation.close(); presentation.acknowledged(rename(record, "late", 3));
|
||||
tasks.forEach(Runnable::run);
|
||||
presentation.activate(player, first, record);
|
||||
assertTrue(presentation.snapshot().isEmpty());
|
||||
}
|
||||
|
||||
@Test void activationClosesTheFreshReadToRenameAcknowledgmentRaceAndNeverAppliesAnOldReadToANewSession() {
|
||||
UUID holder = UUID.randomUUID();
|
||||
Player player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> holder);
|
||||
var record = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
var reads = new ArrayList<java.util.concurrent.CompletableFuture<java.util.Optional<CharacterRecord>>>();
|
||||
var tasks = new ArrayList<Runnable>(); var output = new Output();
|
||||
var presentation = new CharacterPresentation(output, tasks::add, () -> true, failure -> { throw new AssertionError(failure); }, id -> {
|
||||
assertEquals(record.id(), id);
|
||||
var read = new java.util.concurrent.CompletableFuture<java.util.Optional<CharacterRecord>>(); reads.add(read); return read;
|
||||
});
|
||||
// Rename committed after EquipmentSessions' final load but before presentation activation.
|
||||
presentation.acknowledged(rename(record, "already saved while not active", 1));
|
||||
UUID session = UUID.randomUUID();
|
||||
presentation.activate(player, session, record);
|
||||
assertEquals(1, reads.size(), "Resume always rechecks the authoritative record, not a physical-sheet/cache name");
|
||||
reads.getFirst().complete(java.util.Optional.of(rename(record, "already saved while not active", 1)));
|
||||
tasks.forEach(Runnable::run); tasks.clear();
|
||||
assertEquals("already saved while not active", presentation.name(holder));
|
||||
presentation.withdraw(holder, session);
|
||||
UUID replacement = UUID.randomUUID();
|
||||
presentation.activate(player, replacement, record);
|
||||
reads.get(1).complete(java.util.Optional.of(rename(record, "old queued name", 2)));
|
||||
presentation.withdraw(holder, replacement);
|
||||
presentation.activate(player, UUID.randomUUID(), rename(record, "fresh current name", 3));
|
||||
tasks.forEach(Runnable::run); tasks.clear();
|
||||
assertEquals("fresh current name", presentation.name(holder));
|
||||
reads.get(2).complete(java.util.Optional.of(rename(record, "fresh current name", 3)));
|
||||
assertTrue(tasks.isEmpty(), "Equal revision does not enqueue redundant native output");
|
||||
presentation.close();
|
||||
}
|
||||
|
||||
static CharacterRecord rename(CharacterRecord r, String name, int revision) {
|
||||
return new CharacterRecord(r.id(), name, java.math.BigInteger.valueOf(revision), r.stats(), r.level(), r.experience(),
|
||||
r.unspentPoints(), r.health(), r.learned(), r.loadout(), r.cooldowns(), r.dead(), r.deathId(), r.diedAt());
|
||||
}
|
||||
static final class Output implements CharacterPresentation.Output {
|
||||
final ArrayList<CharacterPresentation.View> shown = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> renamed = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> cleared = new ArrayList<>();
|
||||
boolean failClear;
|
||||
@Override public void show(Player player, CharacterPresentation.View view) { shown.add(view); }
|
||||
@Override public void rename(CharacterPresentation.View view) { renamed.add(view); }
|
||||
@Override public void clear(CharacterPresentation.View view) { cleared.add(view); if (failClear) throw new IllegalStateException("native send failed"); }
|
||||
@Override public void close() { }
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,8 @@ class CharacterSheetsNativeTest {
|
||||
assertEquals(1, preview.getAmount());
|
||||
assertTrue(sheets.identify(preview).isEmpty());
|
||||
assertTrue(preview.getItemMeta().getPersistentDataContainer().isEmpty());
|
||||
assertEquals(List.of(Component.text("Character sheet:"), Component.text("Place in off hand"),
|
||||
Component.text("to enter fantasy world.")), preview.getItemMeta().lore());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +106,8 @@ class CharacterSheetsNativeTest {
|
||||
assertEquals(Material.PAPER, sheet.getType());
|
||||
assertEquals(1, sheet.getAmount());
|
||||
assertEquals(Component.text(record.name()), sheet.getItemMeta().displayName());
|
||||
assertEquals(List.of(Component.text("Character sheet: place in off hand to enter fantasy world.")), sheet.getItemMeta().lore());
|
||||
assertEquals(List.of(Component.text("Character sheet:"), Component.text("Place in off hand"),
|
||||
Component.text("to enter fantasy world.")), sheet.getItemMeta().lore());
|
||||
assertEquals(record.id(), sheets.identify(sheet).orElseThrow());
|
||||
assertEquals(Set.of(new NamespacedKey("fantasystick", "sheet_version"), new NamespacedKey("fantasystick", "character_id")),
|
||||
sheet.getItemMeta().getPersistentDataContainer().getKeys(), "No player owner, equipment or progress snapshot belongs on the sheet");
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetHealthPacket;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class DefeatHealthDeliveryNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void zeroHealthDefeatNeverDeliversADeathScreenHealthUpdateAndTailArrivesWithoutReconnect() throws Exception {
|
||||
for (boolean queued : List.of(false, true)) try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("queued-" + queued))) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data.resolve("queued-" + queued));
|
||||
f.players.put(a.core.id, a.player);
|
||||
var sent = nativeHealthDelivery(a);
|
||||
var entry = a.player.getLocation();
|
||||
f.activate(a);
|
||||
a.core.location.add(20, 0, 20);
|
||||
a.core.health = 0; // The real death callback begins after native health reaches zero.
|
||||
sent.clear();
|
||||
a.nativePlayer.queueHealthUpdatePacket = queued;
|
||||
var death = death(a);
|
||||
f.dispatcher.accept(death);
|
||||
if (a.nativePlayer.queuedHealthUpdatePacket != null) sent.add(a.nativePlayer.queuedHealthUpdatePacket);
|
||||
a.nativePlayer.queueHealthUpdatePacket = false;
|
||||
PartyBookNativeTest.drain(f);
|
||||
assertTrue(death.isCancelled());
|
||||
assertEquals(a.maximumHealth.getValue(), a.player.getHealth());
|
||||
assertEquals(entry, a.player.getLocation());
|
||||
assertFalse(a.player.isHealthScaled());
|
||||
var updates = sent.stream().filter(ClientboundSetHealthPacket.class::isInstance)
|
||||
.map(ClientboundSetHealthPacket.class::cast).toList();
|
||||
assertFalse(updates.isEmpty(), "Exercise actual CraftPlayer scale/health delivery, not a mocked setter");
|
||||
assertTrue(updates.stream().allMatch(p -> p.getHealth() > 0),
|
||||
() -> "Cancelled fantasy defeat must never deliver zero health: " + updates.stream().map(ClientboundSetHealthPacket::getHealth).toList());
|
||||
var tail = a.core.inventory.getItemInOffHand().clone();
|
||||
assertEquals(org.bukkit.Material.WRITTEN_BOOK, tail.getType()); assertEquals(1, tail.getAmount());
|
||||
f.dispatcher.accept(death); PartyBookNativeTest.drain(f);
|
||||
assertEquals(tail, a.core.inventory.getItemInOffHand());
|
||||
// A subsequent ordinary death is not protected by a blanket zero-health packet filter.
|
||||
a.core.health = 0;
|
||||
var ordinaryDeath = death(a); f.dispatcher.accept(ordinaryDeath);
|
||||
assertFalse(ordinaryDeath.isCancelled());
|
||||
a.player.sendHealthUpdate();
|
||||
assertEquals(0, ((ClientboundSetHealthPacket) sent.getLast()).getHealth());
|
||||
}
|
||||
}
|
||||
|
||||
private static org.bukkit.event.entity.PlayerDeathEvent death(FantasyStickLifecycleNativeTest.Actor a) {
|
||||
var source = new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.GENERIC)));
|
||||
return new org.bukkit.event.entity.PlayerDeathEvent(a.player, source, new ArrayList<>(), 0,
|
||||
net.kyori.adventure.text.Component.empty(), true);
|
||||
}
|
||||
|
||||
private static List<Packet<?>> nativeHealthDelivery(FantasyStickLifecycleNativeTest.Actor a) {
|
||||
var sent = new ArrayList<Packet<?>>();
|
||||
var connection = mock(net.minecraft.server.network.ServerGamePacketListenerImpl.class);
|
||||
doAnswer(call -> { sent.add(call.getArgument(0)); return null; }).when(connection).send(any(Packet.class));
|
||||
a.nativePlayer.connection = connection;
|
||||
when(a.nativePlayer.getFoodData()).thenReturn(a.food);
|
||||
// Transport and tracked entity storage are explicit ports; scaling and packet creation run natively.
|
||||
when(a.nativePlayer.getEntityData()).thenReturn(mock(net.minecraft.network.syncher.SynchedEntityData.class));
|
||||
doCallRealMethod().when(a.player).setHealthScale(anyDouble());
|
||||
doCallRealMethod().when(a.player).setHealthScaled(anyBoolean());
|
||||
doCallRealMethod().when(a.player).getHealthScale();
|
||||
doCallRealMethod().when(a.player).isHealthScaled();
|
||||
doCallRealMethod().when(a.player).getScaledHealth();
|
||||
doCallRealMethod().when(a.player).getScaledMaxHealth();
|
||||
doCallRealMethod().when(a.player).updateScaledHealth();
|
||||
doCallRealMethod().when(a.player).updateScaledHealth(anyBoolean());
|
||||
doCallRealMethod().when(a.player).sendHealthUpdate();
|
||||
a.player.setHealthScale(20); a.player.setHealthScaled(false);
|
||||
sent.clear(); return sent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Actual packaged PluginCommand permission/dispatch; only the absent console is a port. */
|
||||
class EquipmentAdminCommandNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void adventureConfigurationCommandReadsValidatesPersistsAndReopensWithoutTouchingPlayers() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var sender = new Sender();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"config", "adventure-mode"});
|
||||
assertTrue(sender.messages.getLast().contains("adventure-mode=true"));
|
||||
sender.messages.clear();
|
||||
for (String value : List.of("yes", "1", "TRUE", "")) {
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"config", "adventure-mode", value});
|
||||
assertTrue(sender.messages.getLast().contains("true|false"));
|
||||
}
|
||||
assertTrue(f.tasks.isEmpty());
|
||||
assertFalse(Files.exists(data.resolve("config.yml")));
|
||||
sender.allowed = false;
|
||||
f.command.getExecutor().onCommand(sender.port, f.command, "fantasystick", new String[]{"config", "adventure-mode", "false"});
|
||||
assertFalse(Files.exists(data.resolve("config.yml")));
|
||||
sender.allowed = true; sender.messages.clear();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"config", "adventure-mode", "false"});
|
||||
assertTrue(sender.messages.isEmpty(), "Do not report success before acknowledgment");
|
||||
var reply = f.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(reply); reply.run();
|
||||
assertTrue(sender.messages.getLast().contains("adventure-mode=false"));
|
||||
assertTrue(sender.messages.getLast().contains("new sessions"));
|
||||
assertEquals(0, f.playerLookups);
|
||||
f.plugin.setEnabled(false); f.plugin.setEnabled(true);
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"config", "adventure-mode"});
|
||||
assertTrue(sender.messages.getLast().contains("adventure-mode=false"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void reenableWaitsOffThreadForAcceptedConfigurationWritesBeforeReadingNewPolicy() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var old = FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "adventureSettings");
|
||||
var worker = (java.util.concurrent.ExecutorService) FantasyStickLifecycleNativeTest.Fixture.field(old, "worker");
|
||||
var entered = new java.util.concurrent.CountDownLatch(1);
|
||||
var release = new java.util.concurrent.CountDownLatch(1);
|
||||
worker.execute(() -> {
|
||||
entered.countDown();
|
||||
try { release.await(5, java.util.concurrent.TimeUnit.SECONDS); }
|
||||
catch (InterruptedException error) { Thread.currentThread().interrupt(); }
|
||||
});
|
||||
try {
|
||||
assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
var sender = new Sender();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"config", "adventure-mode", "false"});
|
||||
f.plugin.setEnabled(false); f.plugin.setEnabled(true);
|
||||
assertNull(FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions"), "Do not activate from a stale config snapshot");
|
||||
release.countDown();
|
||||
f.tick();
|
||||
assertNotNull(FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions"));
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"config", "adventure-mode"});
|
||||
assertTrue(sender.messages.getLast().contains("adventure-mode=false"));
|
||||
} finally { release.countDown(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Test void permissionAndStrictShapeRejectBeforePersistenceOrNativeLookup() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
assertNotNull(f.command, "Packaged descriptor must install the actual command");
|
||||
var sender = new Sender();
|
||||
sender.allowed = false;
|
||||
assertTrue(f.command.execute(sender.port, "fantasystick", new String[]{"inspect", UUID.randomUUID().toString()}));
|
||||
// Executor must also defend direct dispatch, not rely solely on PluginCommand.
|
||||
assertTrue(f.command.getExecutor().onCommand(sender.port, f.command, "fantasystick",
|
||||
new String[]{"recover", UUID.randomUUID().toString()}));
|
||||
sender.allowed = true;
|
||||
for (String[] args : List.of(new String[]{}, new String[]{"inspect"},
|
||||
new String[]{"reset", UUID.randomUUID().toString()}, new String[]{"inspect", "1-1-1-1-1"},
|
||||
new String[]{"recover", "not-a-uuid"}, new String[]{"inspect", UUID.randomUUID().toString(), "extra"})) {
|
||||
assertTrue(f.command.execute(sender.port, "fantasystick", args));
|
||||
}
|
||||
assertFalse(Files.exists(data.resolve("sessions")));
|
||||
assertTrue(f.tasks.isEmpty());
|
||||
assertEquals(0, f.playerLookups, "Rejected commands must not inspect native players");
|
||||
assertFalse(sender.messages.isEmpty());
|
||||
}
|
||||
assertFalse(Files.exists(data.resolve("sessions")), "No queued IO after worker drain either");
|
||||
}
|
||||
|
||||
@Test void inspectIsDeferredSanitizedAndReturnsToMainThreadAndCloseDropsResponses() throws Exception {
|
||||
try (var receipts = new games.dmg.fantasystick.persistence.EquipmentSessionStore(data, java.time.Clock.systemUTC());
|
||||
var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
UUID owner = UUID.randomUUID(), session = UUID.randomUUID(), character = UUID.randomUUID();
|
||||
receipts.prepare(owner, session, character).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
receipts.recordExit(owner, session, java.time.Duration.ofSeconds(900)).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
f.plugin.setEnabled(true);
|
||||
var sender = new Sender();
|
||||
assertNotNull(f.command);
|
||||
assertTrue(f.command.execute(sender.port, "fantasystick", new String[]{"inspect", owner.toString()}));
|
||||
assertTrue(sender.messages.isEmpty(), "No response until the server callback");
|
||||
var response = f.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(response);
|
||||
response.run();
|
||||
String text = String.join("\n", sender.messages);
|
||||
assertTrue(text.contains(owner.toString()), text);
|
||||
assertTrue(text.contains(session.toString()), text);
|
||||
assertTrue(text.contains(character.toString()), text);
|
||||
assertTrue(text.contains("pending") && text.contains("deadline") && text.contains("exit"), text);
|
||||
assertFalse(text.contains("schema-version") || text.contains(data.toString()), text);
|
||||
sender.messages.clear();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"inspect", owner.toString()});
|
||||
var stale = f.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(stale);
|
||||
f.plugin.setEnabled(false);
|
||||
f.plugin.setEnabled(true);
|
||||
stale.run();
|
||||
assertTrue(sender.messages.isEmpty(), "Previous lifetime must not reply after re-enable");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void onlineRecoveryUsesNativeProofAndReportsOnlyARequestAndOfflineNeverQueuesIO() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var sender = new Sender(); UUID offline = UUID.randomUUID();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"recover", offline.toString()});
|
||||
assertTrue(sender.messages.getLast().contains("must be online"));
|
||||
assertFalse(Files.exists(data.resolve("sessions"))); assertTrue(f.tasks.isEmpty());
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
|
||||
var original = a.core.snapshot(); UUID session = UUID.randomUUID();
|
||||
f.receipts().prepare(a.core.id, session, a.core.record.id()).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
assertEquals(games.dmg.fantasystick.items.EquipmentStorage.PackResult.PACKED,
|
||||
new games.dmg.fantasystick.items.EquipmentStorage().pack(a.core.inventory, a.core.id, session));
|
||||
a.core.marker(session, "PACKED"); var packed = a.core.snapshot();
|
||||
sender.messages.clear();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"recover", a.core.id.toString()});
|
||||
assertEquals(1, sender.messages.size());
|
||||
assertTrue(sender.messages.getFirst().contains("requested") && sender.messages.getFirst().contains("not confirmation"));
|
||||
assertArrayEquals(packed, a.core.snapshot(), "Request is not premature success");
|
||||
f.tick();
|
||||
assertArrayEquals(original, a.core.snapshot()); assertTrue(a.core.marker().endsWith("|RESTORED"));
|
||||
assertNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow().pending());
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"recover", a.core.id.toString()}); f.tick();
|
||||
assertArrayEquals(original, a.core.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void ambiguousRecoveryRetainsEveryItemAndReceiptAndInspectionNeverPrintsRawMarker() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
|
||||
UUID session = UUID.randomUUID();
|
||||
var saved = f.receipts().prepare(a.core.id, session, a.core.record.id()).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
new games.dmg.fantasystick.items.EquipmentStorage().pack(a.core.inventory, a.core.id, session);
|
||||
a.core.pdc.set(new org.bukkit.NamespacedKey("fantasystick", "equipment_session"),
|
||||
org.bukkit.persistence.PersistentDataType.STRING, "secret-not-a-valid-marker");
|
||||
var before = a.core.snapshot(); var marker = a.core.pdc.serializeToBytes();
|
||||
var sender = new Sender();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"recover", a.core.id.toString()}); f.tick();
|
||||
assertArrayEquals(before, a.core.snapshot()); assertArrayEquals(marker, a.core.pdc.serializeToBytes());
|
||||
assertEquals(saved, f.receipts().find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow());
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"inspect", a.core.id.toString()}); f.tick();
|
||||
var text = String.join("\n", sender.messages);
|
||||
assertTrue(text.contains("malformed (retained)")); assertTrue(text.contains("active=none"));
|
||||
assertFalse(text.contains("secret-not-a-valid-marker"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void inspectObservesCurrentOnlineActiveStateAndPermissionRevocationDropsDeferredResponse() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var sender = new Sender();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"inspect", a.core.id.toString()}); f.tick();
|
||||
assertTrue(sender.messages.stream().anyMatch(message -> message.contains("active=session=")));
|
||||
assertTrue(sender.messages.stream().anyMatch(message -> message.contains("phase=PACKED")));
|
||||
sender.messages.clear();
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"inspect", a.core.id.toString()});
|
||||
var pending = f.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(pending);
|
||||
sender.allowed = false; pending.run(); assertTrue(sender.messages.isEmpty());
|
||||
sender.allowed = true;
|
||||
f.command.execute(sender.port, "fantasystick", new String[]{"inspect", a.core.id.toString()});
|
||||
pending = f.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(pending);
|
||||
((AutoCloseable) f.command.getExecutor()).close(); pending.run(); assertTrue(sender.messages.isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
static final class Sender {
|
||||
final Thread main = Thread.currentThread();
|
||||
final List<String> messages = new ArrayList<>();
|
||||
boolean allowed = true;
|
||||
final CommandSender port = FantasyStickLifecycleNativeTest.port(CommandSender.class, (name, args) -> {
|
||||
assertSame(main, Thread.currentThread(), "Worker accessed command sender: " + name);
|
||||
return switch (name) {
|
||||
case "hasPermission" -> { assertEquals("fantasystick.admin", args[0]); yield allowed; }
|
||||
case "sendMessage" -> { messages.add(String.valueOf(args[0])); yield null; }
|
||||
default -> throw new AssertionError("Unexpected sender call " + name);
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -38,6 +38,114 @@ class EquipmentStorageNativeTest {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void laterClearFailureLeavesEveryOriginalInTheActualNativeBoxWithoutRollback() {
|
||||
var writes = new java.util.concurrent.atomic.AtomicInteger();
|
||||
var armed = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var inventory = new CraftInventoryPlayer(new Inventory(null, new EntityEquipment()) {
|
||||
@Override public InventoryHolder getOwner() { return null; }
|
||||
}) {
|
||||
@Override public void setItem(int slot, ItemStack item) {
|
||||
super.setItem(slot, item);
|
||||
if (armed.get() && writes.incrementAndGet() == 7) throw new IllegalStateException("Later clear failed");
|
||||
}
|
||||
};
|
||||
int[] slots = {0, 1, 2, 3, 4, 5, 6, 7, 8, 36, 37, 38, 39};
|
||||
for (int i = 0; i < slots.length; i++) inventory.setItem(slots[i], new ItemStack(Material.DIAMOND, i + 1));
|
||||
var original = snapshot(inventory);
|
||||
armed.set(true);
|
||||
assertThrows(IllegalStateException.class, () -> new EquipmentStorage().pack(inventory, UUID.randomUUID(), UUID.randomUUID()));
|
||||
var actualBox = inventory.getItem(9);
|
||||
assertNotNull(actualBox, "A real recovery box must exist before any original is cleared");
|
||||
var nativeContents = CraftItemStack.asNMSCopy(actualBox).get(DataComponents.CONTAINER);
|
||||
assertNotNull(nativeContents);
|
||||
var packed = NonNullList.withSize(27, net.minecraft.world.item.ItemStack.EMPTY);
|
||||
nativeContents.copyInto(packed);
|
||||
for (int i = 0; i < slots.length; i++) assertEquals(original[slots[i]], CraftItemStack.asBukkitCopy(packed.get(i)));
|
||||
assertNull(inventory.getItem(0), "No silent rollback of cleared originals");
|
||||
assertEquals(original[8], inventory.getItem(8), "Uncertain duplicates remain in their original slots");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesTheWholeRestoreBeforeReplacingOnlyOwnedControlsAndKeepsOffhandAndHead() {
|
||||
var inventory = inventory();
|
||||
var owner = UUID.randomUUID();
|
||||
var session = UUID.randomUUID();
|
||||
var storage = new EquipmentStorage();
|
||||
var sword = new ItemStack(Material.DIAMOND_SWORD);
|
||||
inventory.setItem(0, sword);
|
||||
var sheet = new ItemStack(Material.PAPER);
|
||||
inventory.setItemInOffHand(sheet);
|
||||
assertEquals(EquipmentStorage.PackResult.PACKED, storage.pack(inventory, owner, session));
|
||||
var control = new ItemStack(Material.STICK);
|
||||
var meta = control.getItemMeta();
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("fantasystick", "test_session"), PersistentDataType.STRING, session.toString());
|
||||
control.setItemMeta(meta);
|
||||
for (int i = 0; i < 9; i++) inventory.setItem(i, control.clone());
|
||||
inventory.setItem(8, new ItemStack(Material.EMERALD));
|
||||
var before = snapshot(inventory);
|
||||
assertEquals(EquipmentStorage.RestoreResult.OCCUPIED_SLOT,
|
||||
storage.restore(inventory, owner, session, control::equals));
|
||||
assertArrayEquals(before, inventory.getContents(), "Refusal must not strip even owned controls first");
|
||||
inventory.setItem(8, control.clone());
|
||||
for (int i = 10; i < 36; i++) inventory.setItem(i, new ItemStack(Material.STONE, 64));
|
||||
var head = new ItemStack(Material.CARVED_PUMPKIN);
|
||||
inventory.setHelmet(head);
|
||||
assertEquals(EquipmentStorage.RestoreResult.RESTORED,
|
||||
storage.restore(inventory, owner, session, control::equals));
|
||||
assertEquals(sword, inventory.getItem(0));
|
||||
for (int i = 1; i < 9; i++) assertTrue(inventory.getItem(i) == null || inventory.getItem(i).isEmpty());
|
||||
assertEquals(sheet, inventory.getItemInOffHand());
|
||||
assertEquals(head, inventory.getItem(9));
|
||||
assertEquals(EquipmentStorage.RestoreResult.NOT_FOUND,
|
||||
storage.restore(inventory, owner, session, control::equals));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBoxLocationRestoresAllThirteenSlotsAndOnlyItsFreedLocationReceivesTheHead() {
|
||||
for (int location : new int[]{35, 40, 41}) for (boolean head : new boolean[]{false, true}) {
|
||||
var inventory = inventory(); var owner = UUID.randomUUID(); var session = UUID.randomUUID();
|
||||
var storage = new EquipmentStorage();
|
||||
int[] slots = {0, 1, 2, 3, 4, 5, 6, 7, 8, 36, 37, 38, 39};
|
||||
for (int i = 0; i < slots.length; i++) inventory.setItem(slots[i], new ItemStack(Material.ARROW, i + 1));
|
||||
var original = snapshot(inventory);
|
||||
assertEquals(EquipmentStorage.PackResult.PACKED, storage.pack(inventory, owner, session));
|
||||
var box = inventory.getItem(9).clone();
|
||||
for (int slot = 9; slot < 36; slot++) inventory.setItem(slot, new ItemStack(Material.STONE, 64));
|
||||
var cursor = new java.util.concurrent.atomic.AtomicReference<>(new ItemStack(Material.DIAMOND, 7));
|
||||
var unrelatedCursor = cursor.get().clone();
|
||||
var offhand = new ItemStack(Material.EMERALD, 3); inventory.setItemInOffHand(offhand);
|
||||
if (location == 41) cursor.set(box); else inventory.setItem(location, box);
|
||||
var displaced = head ? new ItemStack(Material.CARVED_PUMPKIN) : null;
|
||||
inventory.setHelmet(displaced);
|
||||
assertEquals(EquipmentStorage.RestoreResult.RESTORED, storage.restore(inventory, owner, session, cursor.get(), cursor::set));
|
||||
for (int slot : slots) assertEquals(original[slot], inventory.getItem(slot), "Original slot " + slot);
|
||||
for (int slot = 9; slot < 36; slot++) assertEquals(slot == location ? displaced : new ItemStack(Material.STONE, 64), inventory.getItem(slot));
|
||||
if (location == 40 && !head) assertTrue(inventory.getItemInOffHand().isEmpty());
|
||||
else assertEquals(location == 40 ? displaced : offhand, inventory.getItemInOffHand());
|
||||
assertEquals(location == 41 ? displaced : unrelatedCursor, cursor.get());
|
||||
var restored = snapshot(inventory); var restoredCursor = cursor.get();
|
||||
assertEquals(EquipmentStorage.RestoreResult.NOT_FOUND, storage.restore(inventory, owner, session, cursor.get(), cursor::set));
|
||||
assertArrayEquals(restored, inventory.getContents()); assertEquals(restoredCursor, cursor.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicatesAcrossMainOffhandAndCursorAreAmbiguousBeforeAnyWrite() {
|
||||
for (int[] pair : new int[][]{{9, 35}, {9, 40}, {9, 41}, {40, 41}}) {
|
||||
var inventory = inventory(); var owner = UUID.randomUUID(); var session = UUID.randomUUID();
|
||||
var storage = new EquipmentStorage(); inventory.setItem(0, new ItemStack(Material.DIAMOND_SWORD));
|
||||
storage.pack(inventory, owner, session);
|
||||
var box = inventory.getItem(9).clone(); inventory.setItem(9, null);
|
||||
var cursor = new java.util.concurrent.atomic.AtomicReference<>(new ItemStack(Material.EMERALD));
|
||||
for (int location : pair) { if (location == 41) cursor.set(box.clone()); else inventory.setItem(location, box.clone()); }
|
||||
var before = snapshot(inventory); var beforeCursor = cursor.get().clone();
|
||||
assertEquals(EquipmentStorage.RestoreResult.AMBIGUOUS,
|
||||
storage.restore(inventory, owner, session, cursor.get(), ignored -> fail("No cursor writes on refusal")));
|
||||
assertArrayEquals(before, inventory.getContents()); assertEquals(beforeCursor, cursor.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedAmbiguousAndOccupiedRestorationPathsLeaveAllItemsUntouched() {
|
||||
for (int variant = 0; variant < 6; variant++) {
|
||||
@@ -84,6 +192,33 @@ class EquipmentStorageNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cursorAndOffhandRefusalsValidateTheEntireBoxAndDestinationsBeforeMutation() {
|
||||
for (int location : new int[]{40, 41}) for (int invalid = 0; invalid < 4; invalid++) {
|
||||
var inventory = inventory(); var owner = UUID.randomUUID(); var session = UUID.randomUUID();
|
||||
var storage = new EquipmentStorage(); inventory.setItem(0, new ItemStack(Material.DIAMOND_SWORD));
|
||||
storage.pack(inventory, owner, session);
|
||||
var item = inventory.getItem(9).clone(); inventory.setItem(9, null);
|
||||
if (invalid == 0) item.setAmount(2);
|
||||
if (invalid == 1) {
|
||||
var meta = item.getItemMeta();
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("fantasystick", "storage_slots"), PersistentDataType.INTEGER_ARRAY, new int[]{0});
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
if (invalid == 2) {
|
||||
var meta = (BlockStateMeta) item.getItemMeta(); var box = (ShulkerBox) meta.getBlockState();
|
||||
box.getInventory().setItem(26, new ItemStack(Material.EMERALD)); meta.setBlockState(box); item.setItemMeta(meta);
|
||||
}
|
||||
if (invalid == 3) inventory.setItem(8, new ItemStack(Material.EMERALD));
|
||||
var cursor = location == 41 ? item : new ItemStack(Material.DIAMOND);
|
||||
if (location == 40) inventory.setItemInOffHand(item);
|
||||
var before = snapshot(inventory); var beforeCursor = cursor.clone();
|
||||
assertEquals(invalid == 3 ? EquipmentStorage.RestoreResult.OCCUPIED_SLOT : EquipmentStorage.RestoreResult.INVALID_BOX,
|
||||
storage.restore(inventory, owner, session, cursor, ignored -> fail("Refusal cannot write cursor")));
|
||||
assertArrayEquals(before, inventory.getContents()); assertEquals(beforeCursor, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void eligibilityMatchesTheActualVanillaShulkerSlotForEveryNativeItemMaterial() {
|
||||
var nativeSlot = new net.minecraft.world.inventory.ShulkerBoxSlot(new net.minecraft.world.SimpleContainer(27), 0, 0, 0);
|
||||
@@ -118,9 +253,14 @@ class EquipmentStorageNativeTest {
|
||||
inventory.setItemInOffHand(new ItemStack(Material.PAPER));
|
||||
var before = snapshot(inventory);
|
||||
var storage = new EquipmentStorage();
|
||||
assertEquals(EquipmentStorage.PackResult.NO_SPACE, storage.refusal(inventory, UUID.randomUUID(), UUID.randomUUID()).orElseThrow());
|
||||
assertArrayEquals(before, inventory.getContents());
|
||||
assertEquals(EquipmentStorage.PackResult.NO_SPACE, storage.pack(inventory, UUID.randomUUID(), UUID.randomUUID()));
|
||||
assertArrayEquals(before, inventory.getContents());
|
||||
inventory.setItem(35, null);
|
||||
var eligible = snapshot(inventory);
|
||||
assertTrue(storage.refusal(inventory, UUID.randomUUID(), UUID.randomUUID()).isEmpty());
|
||||
assertArrayEquals(eligible, inventory.getContents());
|
||||
assertEquals(EquipmentStorage.PackResult.PACKED, storage.pack(inventory, UUID.randomUUID(), UUID.randomUUID()));
|
||||
assertEquals(Material.SHULKER_BOX, inventory.getItem(35).getType());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class FantasyHealthNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void nativeMaximumIgnoresBonusesPenaltiesAndHealthBoostWhileTheirOrdinaryOwnershipAndExpiryRemainIntact() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player);
|
||||
var bonus = modifier("bonus", 5, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_VALUE);
|
||||
var penalty = modifier("penalty", -0.5, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL);
|
||||
a.maximumHealth.addTransientModifier(bonus); a.maximumHealth.addTransientModifier(penalty);
|
||||
var boost = net.minecraft.world.effect.MobEffects.HEALTH_BOOST.value();
|
||||
boost.addAttributeModifiers(a.healthAttributes, 1);
|
||||
a.player.setHealth(12); a.player.setFoodLevel(7); a.player.setSaturation(2); a.player.setExhaustion(3);
|
||||
f.activate(a);
|
||||
assertEquals(10, a.maximumHealth.getValue());
|
||||
a.player.setHealth(6);
|
||||
a.maximumHealth.setBaseValue(30); // A later legitimate ordinary base change must survive exit.
|
||||
var later = modifier("later", 4, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_VALUE);
|
||||
a.maximumHealth.addPermanentModifier(later);
|
||||
boost.addAttributeModifiers(a.healthAttributes, 2);
|
||||
assertEquals(10, a.maximumHealth.getValue(), "New native potion modifiers cannot change fantasy maximum");
|
||||
boost.removeAttributeModifiers(a.healthAttributes);
|
||||
a.maximumHealth.removeModifier(bonus); a.maximumHealth.removeModifier(penalty);
|
||||
var zero = modifier("zero", -1, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL);
|
||||
a.maximumHealth.addTransientModifier(zero);
|
||||
assertEquals(10, a.maximumHealth.getValue(), "Even a zero multiplier cannot bypass the native effective-value lease");
|
||||
a.maximumHealth.removeModifier(zero);
|
||||
assertEquals(6, a.player.getHealth());
|
||||
var serialized = a.maximumHealth.pack();
|
||||
assertEquals(30, serialized.baseValue()); assertEquals(java.util.List.of(later), serialized.modifiers());
|
||||
var loaded = new net.minecraft.world.entity.ai.attributes.AttributeInstance(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH, ignored -> {});
|
||||
loaded.apply(serialized); assertEquals(34, loaded.getValue(), "Player saves retain ordinary attribute ownership, not the fantasy maximum");
|
||||
a.player.setFoodLevel(2); a.player.setSaturation(0); a.player.setExhaustion(1);
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
assertEquals(34, a.maximumHealth.getValue()); assertEquals(12, a.player.getHealth());
|
||||
assertEquals(java.util.Set.of(later), a.maximumHealth.getModifiers(), "Expired/removed modifiers are not replayed from a snapshot");
|
||||
assertEquals(7, a.player.getFoodLevel()); assertEquals(2, a.player.getSaturation()); assertEquals(3, a.player.getExhaustion());
|
||||
assertFalse(a.player.isHealthScaled()); assertEquals(20, a.player.getHealthScale());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void activeCharacterBookShowsCurrentNativeDamageRatherThanTheLastSavedHealth() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
a.player.setHealth(4);
|
||||
PartyBookNativeTest.open(f, a);
|
||||
assertTrue(PartyBookNativeTest.text(a).contains("Health: 4/10"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void activeBlueMistAndOneRedDefeatBurstUseWorldLocationsAndStopWithTheSession() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var ordinary = new FantasyStickLifecycleNativeTest.Actor(data); ordinary.core.inventory.setItemInOffHand(null);
|
||||
f.players.put(a.core.id, a.player); f.players.put(ordinary.core.id, ordinary.player);
|
||||
var entry = a.player.getLocation(); f.activate(a);
|
||||
f.pulses.forEach(Runnable::run);
|
||||
assertTrue(dust(a, org.bukkit.Color.BLUE) > 0, "Active fantasy mode must have visible public blue particles");
|
||||
assertEquals(0, dust(ordinary, org.bukkit.Color.BLUE));
|
||||
a.core.location.add(20, 0, 20);
|
||||
var defeatLocation = a.player.getLocation().add(0, 1, 0);
|
||||
var source = new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.OUT_OF_WORLD)));
|
||||
var death = new org.bukkit.event.entity.PlayerDeathEvent(a.player, source, new java.util.ArrayList<>(), 0,
|
||||
net.kyori.adventure.text.Component.empty(), true);
|
||||
f.dispatcher.accept(death); assertTrue(death.isCancelled());
|
||||
PartyBookNativeTest.drain(f);
|
||||
assertEquals(1, dust(a, org.bukkit.Color.RED));
|
||||
assertTrue(org.mockito.Mockito.mockingDetails(a.world).getInvocations().stream().anyMatch(call ->
|
||||
call.getMethod().getName().equals("spawnParticle") && java.util.Arrays.asList(call.getArguments()).contains(defeatLocation)));
|
||||
assertEquals(entry, a.player.getLocation()); assertEquals(28, a.player.getHealth());
|
||||
var tail = a.core.inventory.getItemInOffHand().clone();
|
||||
assertEquals(org.bukkit.Material.WRITTEN_BOOK, tail.getType()); assertEquals(1, tail.getAmount());
|
||||
long blue = dust(a, org.bukkit.Color.BLUE);
|
||||
f.pulses.forEach(Runnable::run); f.dispatcher.accept(death);
|
||||
assertEquals(blue, dust(a, org.bukkit.Color.BLUE)); assertEquals(1, dust(a, org.bukkit.Color.RED));
|
||||
assertEquals(tail, a.core.inventory.getItemInOffHand());
|
||||
f.plugin.setEnabled(false); f.awaitWorkers();
|
||||
f.pulses.forEach(Runnable::run);
|
||||
assertEquals(blue, dust(a, org.bukkit.Color.BLUE), "Retired timers cannot emit fantasy effects");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void uncappedConstitutionEntersAtTheNativeCeilingAndPersistsOnlyBoundedRemainingHealth() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player);
|
||||
var old = a.core.record;
|
||||
var con = java.math.BigInteger.TEN.pow(1000);
|
||||
var stats = new java.util.EnumMap<games.dmg.fantasystick.progression.Stat, java.math.BigInteger>(games.dmg.fantasystick.progression.Stat.class);
|
||||
stats.putAll(old.stats()); stats.put(games.dmg.fantasystick.progression.Stat.CON, con);
|
||||
var saved = new games.dmg.fantasystick.persistence.CharacterRecord(old.id(), old.name(), old.revision().add(java.math.BigInteger.ONE),
|
||||
stats, old.level(), old.experience(), old.unspentPoints(), new java.math.BigDecimal(con.add(java.math.BigInteger.TEN)),
|
||||
old.learned(), old.loadout(), old.cooldowns(), false, null, null);
|
||||
new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).replace(saved, old.revision());
|
||||
var ceiling = games.dmg.fantasystick.session.NativeHealthLimit.read();
|
||||
f.activate(a);
|
||||
assertEquals(ceiling.doubleValue(), a.maximumHealth.getValue()); assertEquals(ceiling.doubleValue(), a.player.getHealth());
|
||||
a.player.setHealth(3.25);
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
var suspended = characters.find(old.id()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertEquals(con, suspended.stats().get(games.dmg.fantasystick.progression.Stat.CON));
|
||||
assertEquals(0, suspended.health().compareTo(new java.math.BigDecimal("3.25")));
|
||||
assertEquals(ceiling, games.dmg.fantasystick.session.NativeHealthLimit.read(), "Never mutate global attribute limits");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void serializedInterruptedSessionRecoversOrdinaryVitalsAndRemainingHealthWithoutReplayingExpiredModifiers() throws Exception {
|
||||
FantasyStickLifecycleNativeTest.Actor a;
|
||||
byte[] nativeProof, characterFile, receiptFile;
|
||||
byte[][] items;
|
||||
net.minecraft.world.entity.ai.attributes.AttributeInstance.Packed ordinaryAttributes;
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
|
||||
a.player.setHealth(12); a.player.setFoodLevel(7); a.player.setSaturation(2); a.player.setExhaustion(3);
|
||||
net.minecraft.world.effect.MobEffects.HEALTH_BOOST.value().addAttributeModifiers(a.healthAttributes, 1);
|
||||
f.activate(a); a.player.setHealth(4); a.player.setFoodLevel(2);
|
||||
nativeProof = a.core.pdc.serializeToBytes();
|
||||
items = java.util.Arrays.stream(a.core.snapshot()).map(item -> item == null ? null : item.serializeAsBytes()).toArray(byte[][]::new);
|
||||
ordinaryAttributes = a.maximumHealth.pack();
|
||||
characterFile = java.nio.file.Files.readAllBytes(data.resolve("characters").resolve(a.core.record.id() + ".yml"));
|
||||
receiptFile = java.nio.file.Files.readAllBytes(data.resolve("sessions").resolve(a.core.id + ".yml"));
|
||||
}
|
||||
// Recreate one concrete crash window from native item/PDC/attribute and YAML saves.
|
||||
// Orderly fixture disposal above is not mistaken for an actual server crash.
|
||||
java.nio.file.Files.write(data.resolve("characters").resolve(a.core.record.id() + ".yml"), characterFile);
|
||||
java.nio.file.Files.write(data.resolve("sessions").resolve(a.core.id + ".yml"), receiptFile);
|
||||
a.core.inventory.setContents(java.util.Arrays.stream(items).map(bytes -> bytes == null ? null : org.bukkit.inventory.ItemStack.deserializeBytes(bytes))
|
||||
.toArray(org.bukkit.inventory.ItemStack[]::new));
|
||||
a.core.pdc.readFromBytes(nativeProof, true);
|
||||
a.maximumHealth.removeModifiers(); a.maximumHealth.apply(ordinaryAttributes);
|
||||
// Native potion attributes use permanent storage. Exercise the real expiry/removal
|
||||
// hook after load; plugin recovery must not reintroduce that removed modifier.
|
||||
net.minecraft.world.effect.MobEffects.HEALTH_BOOST.value().removeAttributeModifiers(a.healthAttributes);
|
||||
a.core.health = 4; a.food.setFoodLevel(2); a.healthScaled = true; a.healthScale = 10;
|
||||
a.core.gameMode = org.bukkit.GameMode.ADVENTURE;
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.players.put(a.core.id, a.player); f.plugin.setEnabled(true); f.tick();
|
||||
PartyBookNativeTest.drain(f);
|
||||
var receipt = f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertNull(receipt.pending());
|
||||
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
|
||||
assertEquals(28, a.maximumHealth.getValue()); assertTrue(a.maximumHealth.getModifiers().isEmpty());
|
||||
assertEquals(12, a.player.getHealth()); assertEquals(7, a.player.getFoodLevel());
|
||||
assertEquals(2, a.player.getSaturation()); assertEquals(3, a.player.getExhaustion());
|
||||
assertFalse(a.player.isHealthScaled()); assertEquals(0, a.core.teleports);
|
||||
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
assertEquals(0, characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow().health().compareTo(java.math.BigDecimal.valueOf(4)));
|
||||
// An unrelated later ordinary change cannot be overwritten by a repeated recovery.
|
||||
a.player.setHealth(5); a.player.setFoodLevel(9);
|
||||
((games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions")).recover(a.player);
|
||||
f.tick(); assertEquals(5, a.player.getHealth()); assertEquals(9, a.player.getFoodLevel());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void failedEntrySettersAndMissingExitProofNeverLeaveTheNativeMaximumOverridden() throws Exception {
|
||||
for (int route = 0; route < 6; route++) try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("failure-" + route))) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data.resolve("failure-" + route));
|
||||
f.players.put(a.core.id, a.player);
|
||||
Runnable fail = () -> { a.core.beforeHealth = () -> {}; a.core.healthMutation = () -> {}; throw new IllegalStateException("Native health setter failed"); };
|
||||
if (route == 0) a.core.beforeHealth = fail;
|
||||
if (route == 1) a.core.healthMutation = fail;
|
||||
if (route == 5) a.core.sync = () -> {
|
||||
a.core.sync = () -> {}; a.player.setHealth(3);
|
||||
throw new IllegalStateException("Activation client synchronization failed after native damage");
|
||||
};
|
||||
f.activate(a);
|
||||
if (route >= 2 && route < 5) {
|
||||
a.player.setHealth(4); a.player.setFoodLevel(2);
|
||||
if (route == 2) a.core.pdc.remove(new org.bukkit.NamespacedKey("fantasystick", "vitals_session"));
|
||||
else if (route == 3) org.mockito.Mockito.doThrow(new IllegalStateException("Native equipment update failed")).when(a.nativePlayer).detectEquipmentUpdates();
|
||||
else a.core.beforeMutation = () -> { throw new IllegalStateException("Equipment restoration write failed"); };
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
if (route < 4) {
|
||||
assertEquals(4, a.player.getHealth(), "Missing/uncertain proof cannot authorize a stale ordinary-health replay");
|
||||
assertEquals(2, a.player.getFoodLevel());
|
||||
}
|
||||
}
|
||||
var sessions = (games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions");
|
||||
assertTrue(sessions.active(a.core.id).isEmpty());
|
||||
assertEquals(28, a.maximumHealth.getValue(), "Only the owned maximum hook is safe to remove despite an uncertain setter/proof");
|
||||
assertNotNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
|
||||
if (route < 2) {
|
||||
assertEquals(route == 0 ? 20 : 10, a.player.getHealth(), "Do not blindly heal an uncertain native write");
|
||||
assertFalse(a.player.isHealthScaled()); assertEquals(20, a.player.getHealthScale());
|
||||
}
|
||||
if (route >= 4) {
|
||||
assertEquals(20, a.player.getHealth(), "Proven vitals cleanup is independent of uncertain equipment/client state");
|
||||
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
assertEquals(0, characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow().health()
|
||||
.compareTo(java.math.BigDecimal.valueOf(route == 4 ? 4 : 3)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void failedHealthWriteRestoresOrdinaryGearButRetainsTheReceiptAndCannotResumeStaleHealth() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone(); a.player.setHealth(4);
|
||||
var path = data.resolve("characters").resolve(a.core.record.id() + ".yml");
|
||||
byte[] acknowledged = java.nio.file.Files.readAllBytes(path);
|
||||
try (var channel = java.nio.channels.FileChannel.open(data.resolve("characters/.records.lock"), java.nio.file.StandardOpenOption.WRITE);
|
||||
var lock = channel.lock()) {
|
||||
assertTrue(lock.isValid());
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a); PartyBookNativeTest.drain(f);
|
||||
assertNotNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
|
||||
assertArrayEquals(acknowledged, java.nio.file.Files.readAllBytes(path));
|
||||
}
|
||||
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
|
||||
assertEquals(28, a.maximumHealth.getValue()); assertEquals(20, a.player.getHealth());
|
||||
a.core.inventory.setItemInOffHand(sheet); f.changed(a); f.tick();
|
||||
var sessions = (games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions");
|
||||
assertTrue(sessions.active(a.core.id).isEmpty(), "An unacknowledged health save cannot become a free heal on reentry");
|
||||
assertArrayEquals(acknowledged, java.nio.file.Files.readAllBytes(path));
|
||||
assertTrue(a.messages.stream().anyMatch(message -> message.contains("persistence or recovery is pending")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void delayedRecoveryReadCannotRecreateOwnershipAfterTheHealthSaveAndExitAlreadyCompleted() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone(); a.player.setHealth(4);
|
||||
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
var worker = (java.util.concurrent.ExecutorService) FantasyStickLifecycleNativeTest.Fixture.field(characters, "worker");
|
||||
var entered = new java.util.concurrent.CountDownLatch(1); var release = new java.util.concurrent.CountDownLatch(1);
|
||||
var gate = worker.submit(() -> {
|
||||
entered.countDown();
|
||||
try { assertTrue(release.await(5, TimeUnit.SECONDS)); }
|
||||
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new AssertionError(interrupted); }
|
||||
});
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
assertNotNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
|
||||
var sessions = (games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions");
|
||||
sessions.recover(a.player);
|
||||
var stale = f.tasks.poll(5, TimeUnit.SECONDS); assertNotNull(stale);
|
||||
release.countDown(); gate.get(5, TimeUnit.SECONDS);
|
||||
characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS);
|
||||
assertNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
|
||||
stale.run();
|
||||
a.core.inventory.setItemInOffHand(sheet); f.changed(a); f.tick();
|
||||
assertFalse(a.messages.stream().anyMatch(message -> message.contains("persistence or recovery is pending")),
|
||||
"A delayed old receipt must not manufacture a new ownership blocker after acknowledged exit");
|
||||
f.tick(); f.tick(); assertTrue(sessions.active(a.core.id).isPresent()); assertEquals(4, a.player.getHealth());
|
||||
} finally { release.countDown(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Test void nativeHealthChangesDuringClientScaleDeliveryAreNotOverwrittenByInitialActivation() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
|
||||
a.scaleMutation = () -> {
|
||||
a.scaleMutation = () -> {};
|
||||
a.player.setHealth(Math.min(a.player.getHealth(), a.maximumHealth.getValue()) - 1);
|
||||
};
|
||||
f.activate(a);
|
||||
assertEquals(9, a.player.getHealth(), "Native damage during a reentrant client update must not be replaced with another full-health initialization");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void quitAndDisablePersistDamageAndRestoreOnlyOwnedOrdinaryVitalsAndDisplay() throws Exception {
|
||||
for (boolean quit : new boolean[]{true, false}) try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("lifecycle-" + quit))) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data.resolve("lifecycle-" + quit)); f.players.put(a.core.id, a.player);
|
||||
a.player.setHealth(12); a.player.setFoodLevel(7); a.player.setSaturation(2); a.player.setExhaustion(3);
|
||||
f.activate(a); a.player.setHealth(4); a.player.setFoodLevel(1);
|
||||
a.maximumHealth.setBaseValue(8); // A legitimate later ordinary maximum, below the pre-entry health.
|
||||
a.player.setHealthScale(44); // A later display owner's value is not ours to undo.
|
||||
if (quit) {
|
||||
a.core.online = false;
|
||||
f.dispatcher.accept(new org.bukkit.event.player.PlayerQuitEvent(a.player, net.kyori.adventure.text.Component.empty()));
|
||||
PartyBookNativeTest.drain(f);
|
||||
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
} else { f.plugin.setEnabled(false); f.awaitWorkers(); }
|
||||
assertEquals(8, a.maximumHealth.getValue()); assertEquals(8, a.player.getHealth());
|
||||
assertEquals(7, a.player.getFoodLevel()); assertEquals(2, a.player.getSaturation()); assertEquals(3, a.player.getExhaustion());
|
||||
assertEquals(44, a.player.getHealthScale()); assertTrue(a.player.isHealthScaled());
|
||||
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
|
||||
var saved = new games.dmg.fantasystick.persistence.YamlCharacterRepository(data.resolve("lifecycle-" + quit)).load(a.core.record.id()).orElseThrow();
|
||||
assertFalse(saved.dead()); assertEquals(0, saved.health().compareTo(java.math.BigDecimal.valueOf(4))); assertEquals(0, a.core.teleports);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void aDamagedTransferredCharacterNeverTransfersItsFormerHoldersOrdinaryVitals() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); var b = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.players.put(b.core.id, b.player);
|
||||
a.player.setHealth(12); a.player.setFoodLevel(7);
|
||||
b.player.setHealth(19); b.player.setFoodLevel(3);
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone(); f.activate(a); a.player.setHealth(3);
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a); PartyBookNativeTest.drain(f);
|
||||
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
b.core.inventory.setItemInOffHand(sheet); f.activate(b);
|
||||
assertEquals(3, b.player.getHealth()); assertEquals(12, a.player.getHealth()); assertEquals(7, a.player.getFoodLevel());
|
||||
b.player.setHealth(2); b.core.inventory.setItemInOffHand(null); f.changed(b); PartyBookNativeTest.drain(f);
|
||||
assertEquals(19, b.player.getHealth()); assertEquals(3, b.player.getFoodLevel());
|
||||
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
assertEquals(0, characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow().health().compareTo(java.math.BigDecimal.valueOf(2)));
|
||||
assertEquals(b.core.record, characters.find(b.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void shuttingDownMaximumHooksContinuesAfterAnOriginalNativeObserverThrows() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var throwNow = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var attributes = new java.util.ArrayList<net.minecraft.world.entity.ai.attributes.AttributeInstance>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
|
||||
var attribute = new net.minecraft.world.entity.ai.attributes.AttributeInstance(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH,
|
||||
ignored -> { if (throwNow.get()) throw new IllegalStateException("Native dirty observer failed during cleanup"); });
|
||||
attributes.add(attribute);
|
||||
org.mockito.Mockito.when(a.nativePlayer.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH)).thenReturn(attribute);
|
||||
f.activate(a); assertEquals(10, attribute.getValue());
|
||||
}
|
||||
throwNow.set(true);
|
||||
var vitals = (games.dmg.fantasystick.session.SessionVitals) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "vitals");
|
||||
var failure = assertThrows(IllegalStateException.class, vitals::close);
|
||||
assertEquals(2, failure.getSuppressed().length);
|
||||
for (var attribute : attributes) assertEquals(20, attribute.getValue(), "Every player's hook must be retired despite another cleanup failure");
|
||||
}
|
||||
}
|
||||
|
||||
private static long dust(FantasyStickLifecycleNativeTest.Actor a, org.bukkit.Color color) {
|
||||
return org.mockito.Mockito.mockingDetails(a.world).getInvocations().stream().filter(call ->
|
||||
call.getMethod().getName().equals("spawnParticle") && java.util.Arrays.stream(call.getArguments())
|
||||
.anyMatch(argument -> argument instanceof org.bukkit.Particle.DustOptions dust && dust.getColor().equals(color))).count();
|
||||
}
|
||||
|
||||
private static net.minecraft.world.entity.ai.attributes.AttributeModifier modifier(String name, double amount,
|
||||
net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation operation) {
|
||||
return new net.minecraft.world.entity.ai.attributes.AttributeModifier(net.minecraft.resources.Identifier.fromNamespaceAndPath("test", name), amount, operation);
|
||||
}
|
||||
|
||||
@Test void actualOffhandEntryAppliesFantasyHealthAndExitRestoresOrdinaryHealthWithoutHealingTheCharacter() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player);
|
||||
double ordinaryHealth = a.player.getHealth();
|
||||
double ordinaryMaximum = a.player.getAttribute(Attribute.MAX_HEALTH).getValue();
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone();
|
||||
f.activate(a);
|
||||
assertEquals(10, a.player.getAttribute(Attribute.MAX_HEALTH).getValue());
|
||||
assertEquals(10, a.player.getHealth(), "A fresh character starts full, independently of ordinary health");
|
||||
a.player.setHealth(4);
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
assertEquals(ordinaryMaximum, a.player.getAttribute(Attribute.MAX_HEALTH).getValue());
|
||||
assertEquals(ordinaryHealth, a.player.getHealth());
|
||||
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
var saved = characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertEquals(0, saved.health().compareTo(java.math.BigDecimal.valueOf(4)));
|
||||
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
a.core.inventory.setItemInOffHand(sheet); f.activate(a);
|
||||
assertEquals(4, a.player.getHealth(), "Resuming does not replay a first-activation heal");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,72 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import games.dmg.fantasystick.items.SessionControls;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.nio.file.Path;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.entity.Item;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.inventory.InventoryMoveItemEvent;
|
||||
import org.bukkit.event.player.PlayerDropItemEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerItemConsumeEvent;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Supported offhand entry -> guarded delivered controls -> actual book -> ordinary exit. */
|
||||
class InventoryJourneyNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void allNineDeliveredControlsStayContainedWhileTheActualBookWorksAndTheSheetCanLeave() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player);
|
||||
var ordinary = a.core.snapshot();
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone();
|
||||
f.activate(a);
|
||||
var sessions = (EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions");
|
||||
var active = sessions.active(a.core.id).orElseThrow();
|
||||
var delivered = a.core.snapshot();
|
||||
for (int slot = 0; slot < 9; slot++) {
|
||||
var item = a.core.inventory.getItem(slot);
|
||||
var identity = new SessionControls().identify(item).orElseThrow();
|
||||
assertEquals(slot, identity.slot());
|
||||
assertEquals(active.player(), identity.owner());
|
||||
assertEquals(active.session(), identity.session());
|
||||
assertEquals(slot == 0 ? Material.BOOK : slot == 1 ? Material.STICK : Material.GRAY_DYE, item.getType());
|
||||
var entity = mock(Item.class); when(entity.getItemStack()).thenReturn(item);
|
||||
var drop = new PlayerDropItemEvent(a.player, entity);
|
||||
f.dispatcher.accept(drop); assertTrue(drop.isCancelled());
|
||||
var consume = new PlayerItemConsumeEvent(a.player, item, EquipmentSlot.HAND);
|
||||
f.dispatcher.accept(consume); assertTrue(consume.isCancelled());
|
||||
var transfer = new InventoryMoveItemEvent(a.core.inventory, item, a.core.view.getTopInventory(), true);
|
||||
f.dispatcher.accept(transfer); assertTrue(transfer.isCancelled());
|
||||
a.core.inventory.getInventory().setSelectedSlot(slot);
|
||||
var use = new PlayerInteractEvent(a.player, Action.RIGHT_CLICK_AIR, item, null, BlockFace.SELF, EquipmentSlot.HAND);
|
||||
f.dispatcher.accept(use); assertEquals(Event.Result.DENY, use.useItemInHand());
|
||||
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
|
||||
characters.find(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
|
||||
Runnable task; while ((task = f.tasks.poll()) != null) task.run();
|
||||
assertEquals(1, a.books.size(), "Only slot 1 opens the actual native book; other delivered controls are inert");
|
||||
}
|
||||
assertArrayEquals(delivered, a.core.snapshot(), "Containment and inspection never consume/export inventory");
|
||||
assertEquals(sheet, a.core.inventory.getItemInOffHand());
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
assertTrue(sessions.active(a.core.id).isEmpty(), "Transferable sheet removal exits without a combat lock");
|
||||
ordinary[40] = null;
|
||||
assertArrayEquals(ordinary, a.core.snapshot(), "Ordinary gear is restored without replacing the removed sheet");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.progression.CharacterProgress;
|
||||
import games.dmg.fantasystick.progression.ProgressionRules;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import games.dmg.fantasystick.session.NativeHealthLimit;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.entity.ai.attributes.RangedAttribute;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.craftbukkit.attribute.CraftAttributeInstance;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NativeHealthLimitTest {
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test
|
||||
void invalidNativeRangesFailExplicitlyRatherThanGuessingOrChangingTheRuntime() {
|
||||
var range = (RangedAttribute) Attributes.MAX_HEALTH.value();
|
||||
double original = range.getMaxValue();
|
||||
try {
|
||||
for (double invalid : new double[] {0, -1, Double.NaN, Double.POSITIVE_INFINITY,
|
||||
Double.NEGATIVE_INFINITY, Double.MAX_VALUE, Double.MIN_VALUE}) {
|
||||
range.maxValue = invalid;
|
||||
assertThrows(IllegalStateException.class, NativeHealthLimit::read);
|
||||
assertEquals(invalid, range.getMaxValue());
|
||||
}
|
||||
} finally { range.maxValue = original; }
|
||||
assertEquals(0, BigDecimal.valueOf(original).compareTo(NativeHealthLimit.read()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsTheActualNativeCeilingRatherThanGuessingTheDefaultAndFeedsCappedProgression() {
|
||||
var range = (RangedAttribute) Attributes.MAX_HEALTH.value();
|
||||
double original = range.getMaxValue();
|
||||
try {
|
||||
// Isolated non-listening test runtime only. Never write an operator's config file.
|
||||
for (double ceiling : new double[] {10.5, 1024, 2048}) {
|
||||
range.maxValue = ceiling;
|
||||
BigDecimal limit = NativeHealthLimit.read();
|
||||
assertEquals(0, BigDecimal.valueOf(ceiling).compareTo(limit));
|
||||
assertEquals(ceiling, range.getMaxValue(), "Reading does not modify the native range");
|
||||
var progress = new CharacterProgress(UUID.randomUUID(),
|
||||
new ProgressionRules(BigInteger.valueOf(3000), BigInteger.valueOf(100), 30), limit);
|
||||
progress.recordHealth(new BigDecimal("6.25"));
|
||||
var handle = new net.minecraft.world.entity.ai.attributes.AttributeInstance(Attributes.MAX_HEALTH, ignored -> { });
|
||||
var attribute = new CraftAttributeInstance(handle, Attribute.MAX_HEALTH);
|
||||
for (int index = 0; index < 2100; index++) {
|
||||
var before = progress.snapshot();
|
||||
assertEquals(CharacterProgress.Purchase.APPLIED,
|
||||
progress.buyStat(before.characterId(), before.revision(), Stat.CON));
|
||||
var after = progress.snapshot();
|
||||
attribute.setBaseValue(after.maximumHealth().doubleValue());
|
||||
assertEquals(after.maximumHealth().doubleValue(), attribute.getValue());
|
||||
assertEquals(0, new BigDecimal("3.75").compareTo(after.maximumHealth().subtract(after.currentHealth())));
|
||||
}
|
||||
assertEquals(BigInteger.valueOf(2100), progress.snapshot().stats().get(Stat.CON));
|
||||
assertEquals(0, limit.compareTo(progress.snapshot().maximumHealth()));
|
||||
}
|
||||
} finally { range.maxValue = original; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.session.NativeMaximumHealth;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NativeMaximumHealthNativeTest {
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void startupProbeExercisesPinnedInternalsWithoutChangingTheGlobalRangeOrOrdinaryInstances() {
|
||||
var maximum = games.dmg.fantasystick.session.NativeHealthLimit.read();
|
||||
var ordinary = new AttributeInstance(Attributes.MAX_HEALTH, ignored -> {});
|
||||
double before = ordinary.getValue();
|
||||
NativeMaximumHealth.prepare();
|
||||
assertEquals(maximum, games.dmg.fantasystick.session.NativeHealthLimit.read());
|
||||
assertEquals(before, ordinary.getValue()); assertTrue(ordinary.getModifiers().isEmpty());
|
||||
}
|
||||
|
||||
@Test void nativePlayerHealthClampingAndClientAttributeSnapshotsUseTheLeasedMaximum() {
|
||||
var attributes = new net.minecraft.world.entity.ai.attributes.AttributeMap(
|
||||
net.minecraft.world.entity.ai.attributes.AttributeSupplier.builder().add(Attributes.MAX_HEALTH).build());
|
||||
var maximum = java.util.Objects.requireNonNull(attributes.getInstance(Attributes.MAX_HEALTH));
|
||||
var player = org.mockito.Mockito.mock(org.bukkit.craftbukkit.entity.CraftPlayer.class, org.mockito.Mockito.CALLS_REAL_METHODS);
|
||||
var nativePlayer = org.mockito.Mockito.mock(net.minecraft.server.level.ServerPlayer.class, org.mockito.Mockito.CALLS_REAL_METHODS);
|
||||
org.mockito.Mockito.doReturn(attributes).when(nativePlayer).getAttributes();
|
||||
org.mockito.Mockito.doReturn(player).when(nativePlayer).getBukkitEntity();
|
||||
org.mockito.Mockito.doReturn(nativePlayer).when(player).getHandle();
|
||||
// Network/entity-data delivery is the boundary; run the actual native health methods.
|
||||
org.mockito.Mockito.doNothing().when(player).updateScaledHealth();
|
||||
org.mockito.Mockito.doNothing().when(player).updateScaledHealth(org.mockito.ArgumentMatchers.anyBoolean());
|
||||
try (var lease = new NativeMaximumHealth(maximum, 10)) {
|
||||
assertNotNull(lease);
|
||||
player.setHealthScale(10);
|
||||
nativePlayer.setHealth(100);
|
||||
assertEquals(10, nativePlayer.getMaxHealth()); assertEquals(10, nativePlayer.getHealth());
|
||||
nativePlayer.setHealth(6.25f); assertEquals(6.25, player.getHealth());
|
||||
var packet = new net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket(42, java.util.List.of(player.getScaledMaxHealth()));
|
||||
assertEquals(10, packet.getValues().getFirst().base()); assertTrue(packet.getValues().getFirst().modifiers().isEmpty());
|
||||
assertEquals(20, maximum.getBaseValue(), "Ordinary attribute data is not replaced by the client presentation snapshot");
|
||||
}
|
||||
assertEquals(20, nativePlayer.getMaxHealth());
|
||||
assertEquals(6.25, nativePlayer.getHealth(), "Removing the maximum lease does not itself heal");
|
||||
}
|
||||
|
||||
@Test void failingOriginalNativeDirtyCallbackCannotLeaveAnUnownedMaximumOverride() {
|
||||
var attribute = new AttributeInstance(Attributes.MAX_HEALTH, ignored -> { throw new IllegalStateException("Native observer failed"); });
|
||||
assertEquals(20, attribute.getValue());
|
||||
assertThrows(IllegalStateException.class, () -> new NativeMaximumHealth(attribute, 10));
|
||||
assertEquals(20, attribute.getValue(), "Failed construction must not leave an unreachable effective-value lease");
|
||||
assertThrows(IllegalStateException.class, () -> attribute.setBaseValue(24));
|
||||
assertEquals(24, attribute.getValue(), "Subsequent legitimate native writes must not call a leaked lease");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.google.common.collect.ImmutableMultimap;
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.properties.Property;
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import games.dmg.fantasystick.presentation.NativePresentationPackets;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.time.Instant;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.RemoteChatSession;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Entry;
|
||||
import net.minecraft.world.entity.player.ProfilePublicKey;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import org.bukkit.craftbukkit.CraftRegistry;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NativePresentationPacketsTest {
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
private io.papermc.paper.configuration.GlobalConfiguration previousConfig;
|
||||
|
||||
@org.junit.jupiter.api.BeforeEach
|
||||
void metadataSerializationConfig() throws Exception {
|
||||
// Pinned metadata encoding opens Paper's item-obfuscation scope even for TextDisplay.
|
||||
// Install only this test JVM's default binding, and restore the previous global afterward.
|
||||
previousConfig = io.papermc.paper.configuration.GlobalConfiguration.get();
|
||||
var config = new io.papermc.paper.configuration.GlobalConfiguration();
|
||||
config.anticheat = config.new Anticheat();
|
||||
config.anticheat.obfuscation = config.anticheat.new Obfuscation();
|
||||
config.anticheat.obfuscation.items = config.anticheat.obfuscation.new Items();
|
||||
var binding = allocate(io.papermc.paper.util.sanitizer.ItemObfuscationBinding.class);
|
||||
setField(io.papermc.paper.util.sanitizer.ItemObfuscationBinding.class, binding, "level",
|
||||
io.papermc.paper.util.sanitizer.ItemObfuscationSession.ObfuscationLevel.OVERSIZED);
|
||||
config.anticheat.obfuscation.items.binding = binding;
|
||||
setField(io.papermc.paper.configuration.GlobalConfiguration.class, null, "instance", config);
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.AfterEach
|
||||
void restoreSerializationConfig() throws Exception {
|
||||
setField(io.papermc.paper.configuration.GlobalConfiguration.class, null, "instance", previousConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
void projectsOnlyActiveDisplayNameAndPreservesEveryNativeEntryFieldThroughTheWire() throws Exception {
|
||||
var active = entry("AccountOne", false, 217, GameType.SPECTATOR, false, 43);
|
||||
var ordinary = entry("AccountTwo", true, 7, GameType.CREATIVE, true, 81);
|
||||
var actions = EnumSet.allOf(Action.class);
|
||||
var original = new ClientboundPlayerInfoUpdatePacket(actions, List.of(active, ordinary));
|
||||
String name = "勇者 🧙🏽♀️ e\u0301 <red>literal</red> §a " + "長い名前".repeat(40);
|
||||
|
||||
var projected = NativePresentationPackets.projectPlayerInfo(original, active.profileId(), name);
|
||||
|
||||
assertEquals(Component.literal(name), projected.entries().getFirst().displayName(),
|
||||
"Character names are full literal Unicode components, not account/profile replacements");
|
||||
assertNotSame(original, projected);
|
||||
assertEquals(actions, projected.actions());
|
||||
assertEquals(EnumSet.allOf(Action.class), original.actions());
|
||||
assertSame(active, original.entries().getFirst());
|
||||
assertSame(ordinary, projected.entries().get(1));
|
||||
assertSame(active.profile(), projected.entries().getFirst().profile());
|
||||
assertSame(active.chatSession(), projected.entries().getFirst().chatSession());
|
||||
assertEquals(Component.literal("Ordinary AccountOne"), active.displayName());
|
||||
|
||||
var decoded = roundTrip(projected);
|
||||
assertEquals(actions, decoded.actions());
|
||||
assertEquals(2, decoded.entries().size());
|
||||
assertPreserved(active, decoded.entries().getFirst(), Component.literal(name));
|
||||
assertPreserved(ordinary, decoded.entries().get(1), ordinary.displayName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributesSuppressOnlySelectedNativeSnapshotAndNeverMutateOriginalInstances() {
|
||||
var distance = attribute(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, 57.25);
|
||||
var speed = attribute(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED, 0.37);
|
||||
var original = new net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket(81, List.of(speed, distance));
|
||||
var projected = NativePresentationPackets.projectAttributes(original, 81);
|
||||
var decoded = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC, projected);
|
||||
assertNotSame(original, projected);
|
||||
assertEquals(81, decoded.getEntityId());
|
||||
assertEquals(2, decoded.getValues().size());
|
||||
assertSame(original.getValues().getFirst(), projected.getValues().getFirst());
|
||||
assertEquals(speed.getAttribute(), decoded.getValues().getFirst().attribute());
|
||||
assertEquals(speed.getBaseValue(), decoded.getValues().getFirst().base());
|
||||
assertEquals(speed.getModifiers(), java.util.Set.copyOf(decoded.getValues().getFirst().modifiers()));
|
||||
assertEquals(0, decoded.getValues().get(1).base());
|
||||
assertTrue(decoded.getValues().get(1).modifiers().isEmpty());
|
||||
assertEquals(57.25, original.getValues().get(1).base());
|
||||
assertEquals(3, original.getValues().get(1).modifiers().size());
|
||||
assertEquals(57.25, distance.getBaseValue());
|
||||
assertEquals(3, distance.getModifiers().size());
|
||||
assertSame(original, NativePresentationPackets.projectAttributes(original, 82));
|
||||
var absent = new net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket(81, List.of(speed));
|
||||
assertSame(absent, NativePresentationPackets.projectAttributes(absent, 81));
|
||||
var suppression = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.suppressNameTag(81));
|
||||
assertEquals(81, suppression.getEntityId());
|
||||
assertEquals(1, suppression.getValues().size());
|
||||
assertEquals(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, suppression.getValues().getFirst().attribute());
|
||||
assertEquals(0, suppression.getValues().getFirst().base());
|
||||
assertTrue(suppression.getValues().getFirst().modifiers().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restorationSnapshotsCurrentAuthoritativeAttributeAndRefusesMissingNativeSupport() throws Exception {
|
||||
var player = player();
|
||||
var distance = player.distance;
|
||||
var modifiers = java.util.Set.copyOf(distance.getModifiers());
|
||||
var first = NativePresentationPackets.restoreNameTag(player);
|
||||
distance.setBaseValue(13.75);
|
||||
distance.removeModifiers();
|
||||
var decodedFirst = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC, first);
|
||||
assertEquals(player.getId(), decodedFirst.getEntityId());
|
||||
assertEquals(1, decodedFirst.getValues().size());
|
||||
assertEquals(57.25, decodedFirst.getValues().getFirst().base());
|
||||
assertEquals(modifiers, java.util.Set.copyOf(decodedFirst.getValues().getFirst().modifiers()));
|
||||
var latest = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.restoreNameTag(player));
|
||||
assertEquals(13.75, latest.getValues().getFirst().base());
|
||||
assertTrue(latest.getValues().getFirst().modifiers().isEmpty());
|
||||
assertEquals(13.75, distance.getBaseValue());
|
||||
assertTrue(distance.getModifiers().isEmpty());
|
||||
player.distance = null;
|
||||
assertThrows(IllegalStateException.class, () -> NativePresentationPackets.restoreNameTag(player));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tabRefreshUsesCurrentOrdinaryComponentIncludingNullAndOnlyDisplayAction() throws Exception {
|
||||
var player = player();
|
||||
var id = player.getUUID();
|
||||
player.ordinary = Component.literal("Ordinary 🐈").withStyle(net.minecraft.ChatFormatting.GOLD);
|
||||
var first = NativePresentationPackets.refreshTab(player);
|
||||
player.ordinary = Component.literal("New ordinary");
|
||||
var decoded = roundTrip(first);
|
||||
assertEquals(EnumSet.of(Action.UPDATE_DISPLAY_NAME), decoded.actions());
|
||||
assertEquals(1, decoded.entries().size());
|
||||
assertEquals(id, decoded.entries().getFirst().profileId());
|
||||
assertEquals(Component.literal("Ordinary 🐈").withStyle(net.minecraft.ChatFormatting.GOLD), decoded.entries().getFirst().displayName());
|
||||
assertEquals(player.ordinary, roundTrip(NativePresentationPackets.refreshTab(player)).entries().getFirst().displayName());
|
||||
player.ordinary = null;
|
||||
assertNull(roundTrip(NativePresentationPackets.refreshTab(player)).entries().getFirst().displayName());
|
||||
assertEquals(id, player.getUUID());
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(3, player.distance.getModifiers().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tabProjectionNeverBroadensActionsOrChangesUnrelatedIdentities() throws Exception {
|
||||
var active = entry("Account", true, 9, GameType.SURVIVAL, true, 8);
|
||||
for (var action : Action.values()) {
|
||||
var original = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(action), List.of(active));
|
||||
var projected = NativePresentationPackets.projectPlayerInfo(original, active.profileId(), "角色");
|
||||
if (action == Action.UPDATE_DISPLAY_NAME) {
|
||||
var expected = EnumSet.of(action, Action.UPDATE_DISPLAY_NAME);
|
||||
assertEquals(expected, roundTrip(projected).actions());
|
||||
assertEquals(Component.literal("角色"), roundTrip(projected).entries().getFirst().displayName());
|
||||
} else {
|
||||
assertSame(original, projected, action.name());
|
||||
}
|
||||
assertEquals(EnumSet.of(action), original.actions());
|
||||
assertSame(original, NativePresentationPackets.projectPlayerInfo(original, UUID.randomUUID(), "Other"));
|
||||
}
|
||||
var empty = new ClientboundPlayerInfoUpdatePacket(EnumSet.noneOf(Action.class), List.of(active));
|
||||
assertSame(empty, NativePresentationPackets.projectPlayerInfo(empty, active.profileId(), "Ignored"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixedAddOnlyRetainsOriginalActionsAndEveryEntryField() throws Exception {
|
||||
var active = entry("Account", false, 97, GameType.SPECTATOR, false, 13);
|
||||
var unrelated = entry("Unrelated", true, 42, GameType.CREATIVE, true, 9);
|
||||
var original = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.ADD_PLAYER), List.of(active, unrelated));
|
||||
var projected = NativePresentationPackets.projectPlayerInfo(original, active.profileId(), "Character");
|
||||
assertEquals(EnumSet.of(Action.ADD_PLAYER), roundTrip(projected).actions(),
|
||||
"Adding UPDATE_DISPLAY_NAME would serialize the unrelated entry's currently irrelevant display component");
|
||||
assertSame(original, projected);
|
||||
assertEquals(List.of(active, unrelated), projected.entries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void detachedLabelSpawnsWithNativeIdsAndCompleteTextDisplaySchemaForEveryViewer() throws Exception {
|
||||
var player = player();
|
||||
var level = level();
|
||||
player.world = level;
|
||||
int before = level.getNextEntityId();
|
||||
level.chunks.rejectNext = true; // Exercise the real allocator's existing-ID collision check.
|
||||
String text = "勇者 🧙🏽♀️ e\u0301 <red>literal</red> §a " + "長い名前".repeat(80);
|
||||
var label = NativePresentationPackets.createLabel(player, text, 12.25, 89.125, -3.75);
|
||||
assertTrue(label.id() > before + 1, "Native allocator skips an occupied ID");
|
||||
assertEquals(3, level.chunks.checks);
|
||||
int after = level.getNextEntityId();
|
||||
assertTrue(after > label.id());
|
||||
var spawn = wire(net.minecraft.network.protocol.game.ClientboundAddEntityPacket.STREAM_CODEC, label.spawn());
|
||||
assertEquals(label.id(), spawn.getId());
|
||||
assertEquals(label.uuid(), spawn.getUUID());
|
||||
assertNotEquals(player.getUUID(), label.uuid());
|
||||
assertEquals(net.minecraft.world.entity.EntityTypes.TEXT_DISPLAY, spawn.getType());
|
||||
assertEquals(12.25, spawn.getX());
|
||||
assertEquals(89.125, spawn.getY());
|
||||
assertEquals(-3.75, spawn.getZ());
|
||||
assertEquals(net.minecraft.world.phys.Vec3.ZERO, spawn.getMovement());
|
||||
assertEquals(0, spawn.getData());
|
||||
assertEquals(0, spawn.getXRot());
|
||||
assertEquals(0, spawn.getYRot());
|
||||
assertEquals(0, spawn.getYHeadRot());
|
||||
|
||||
var metadata = wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata());
|
||||
var nextViewer = wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata());
|
||||
assertEquals(label.id(), metadata.id());
|
||||
assertEquals(metadata, nextViewer, "Metadata is a full repeatable snapshot, never packDirty");
|
||||
var receiver = new net.minecraft.world.entity.Display.TextDisplay(net.minecraft.world.entity.EntityTypes.TEXT_DISPLAY, level);
|
||||
assertEquals(receiver.getEntityData().packAll().size(), metadata.packedItems().size());
|
||||
receiver.getEntityData().assignValues(metadata.packedItems());
|
||||
assertEquals(Component.literal(text), receiver.getText());
|
||||
assertEquals(net.minecraft.world.entity.Display.BillboardConstraints.CENTER, receiver.getBillboardConstraints());
|
||||
assertEquals(Integer.MAX_VALUE, receiver.getLineWidth());
|
||||
assertEquals((byte) -1, receiver.getTextOpacity());
|
||||
assertEquals(net.minecraft.world.entity.Display.TextDisplay.FLAG_SHADOW
|
||||
| net.minecraft.world.entity.Display.TextDisplay.FLAG_USE_DEFAULT_BACKGROUND, receiver.getFlags());
|
||||
assertEquals(0, receiver.getFlags() & net.minecraft.world.entity.Display.TextDisplay.FLAG_SEE_THROUGH);
|
||||
assertTrue(receiver.isNoGravity());
|
||||
assertEquals(0, receiver.getShadowRadius());
|
||||
assertEquals(0, receiver.getWidth());
|
||||
assertEquals(0, receiver.getHeight());
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(3, player.distance.getModifiers().size());
|
||||
|
||||
// White-box safety invariant only: the opaque session handle cannot expose/register this entity.
|
||||
var field = label.getClass().getDeclaredField("display");
|
||||
field.setAccessible(true);
|
||||
var detached = (net.minecraft.world.entity.Display.TextDisplay) field.get(label);
|
||||
assertFalse(detached.persist);
|
||||
assertFalse(detached.valid);
|
||||
assertFalse(detached.isRemoved());
|
||||
assertSame(level, detached.level());
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelMoveRenameAndRemoveSerializeWithoutChangingIdentityOrAuthoritativeState() throws Exception {
|
||||
var player = player();
|
||||
player.world = level();
|
||||
var label = NativePresentationPackets.createLabel(player, "Old", 1, 2, 3);
|
||||
var other = NativePresentationPackets.createLabel(player, "Other", 4, 5, 6);
|
||||
assertNotEquals(label.id(), other.id());
|
||||
assertNotEquals(label.uuid(), other.uuid());
|
||||
var id = label.id();
|
||||
var uuid = label.uuid();
|
||||
int allocated = player.world.chunks.checks;
|
||||
var originalMetadata = label.metadata();
|
||||
var move = wire(net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket.STREAM_CODEC,
|
||||
label.move(-17.625, 193.125, 4.5));
|
||||
assertEquals(id, move.id());
|
||||
assertEquals(new net.minecraft.world.phys.Vec3(-17.625, 193.125, 4.5), move.change().position());
|
||||
assertEquals(net.minecraft.world.phys.Vec3.ZERO, move.change().deltaMovement());
|
||||
assertEquals(0, move.change().xRot());
|
||||
assertEquals(0, move.change().yRot());
|
||||
assertTrue(move.relatives().isEmpty());
|
||||
assertFalse(move.onGround());
|
||||
var lateSpawn = wire(net.minecraft.network.protocol.game.ClientboundAddEntityPacket.STREAM_CODEC, label.spawn());
|
||||
assertEquals(-17.625, lateSpawn.getX());
|
||||
assertEquals(193.125, lateSpawn.getY());
|
||||
assertEquals(4.5, lateSpawn.getZ());
|
||||
String name = "改名 🌈 e\u0301 <bold>literal</bold>";
|
||||
var renamed = wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.rename(name));
|
||||
assertEquals(id, renamed.id());
|
||||
assertEquals(renamed, wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata()));
|
||||
var changed = new java.util.ArrayList<net.minecraft.network.syncher.SynchedEntityData.DataValue<?>>();
|
||||
for (int index = 0; index < renamed.packedItems().size(); index++) {
|
||||
var value = renamed.packedItems().get(index);
|
||||
if (!value.equals(originalMetadata.packedItems().get(index))) { changed.add(value); }
|
||||
}
|
||||
assertEquals(1, changed.size(), "Rename changes only literal text, not any other native field");
|
||||
assertSame(net.minecraft.network.syncher.EntityDataSerializers.COMPONENT, changed.getFirst().serializer());
|
||||
assertEquals(Component.literal(name), changed.getFirst().value());
|
||||
assertEquals(Component.literal("Old"), originalMetadata.packedItems().stream()
|
||||
.filter(value -> value.id() == changed.getFirst().id()).findFirst().orElseThrow().value());
|
||||
var removal = wire(net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket.STREAM_CODEC, label.remove());
|
||||
assertArrayEquals(new int[] {id}, removal.getEntityIds().toIntArray());
|
||||
assertArrayEquals(new int[] {id}, label.remove().getEntityIds().toIntArray());
|
||||
assertEquals(id, label.id());
|
||||
assertEquals(uuid, label.uuid());
|
||||
assertEquals(allocated, player.world.chunks.checks, "Updates and removals never allocate replacement IDs");
|
||||
assertEquals(4, other.spawn().getX());
|
||||
assertEquals(5, other.spawn().getY());
|
||||
assertEquals(6, other.spawn().getZ());
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(3, player.distance.getModifiers().size());
|
||||
var field = label.getClass().getDeclaredField("display");
|
||||
field.setAccessible(true);
|
||||
var detached = (net.minecraft.world.entity.Display.TextDisplay) field.get(label);
|
||||
assertFalse(detached.persist);
|
||||
assertFalse(detached.valid);
|
||||
assertFalse(detached.isRemoved(), "Client removal must not invoke native discard/remove");
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidLabelInputsFailBeforeAllocationOrMutationAndMissingWorldIsUnsupported() throws Exception {
|
||||
var player = player();
|
||||
player.world = level();
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", Double.NaN, 1, 2));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", 1, Double.POSITIVE_INFINITY, 2));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", 1, 2, Double.NEGATIVE_INFINITY));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, null, 1, 2, 3));
|
||||
assertEquals(0, player.world.chunks.checks);
|
||||
var label = NativePresentationPackets.createLabel(player, "Unchanged", 1, 2, 3);
|
||||
var metadata = label.metadata();
|
||||
assertThrows(IllegalArgumentException.class, () -> label.move(Double.NaN, 6, 7));
|
||||
assertThrows(IllegalArgumentException.class, () -> label.move(5, Double.NEGATIVE_INFINITY, 7));
|
||||
assertThrows(IllegalArgumentException.class, () -> label.move(5, 6, Double.POSITIVE_INFINITY));
|
||||
assertThrows(IllegalArgumentException.class, () -> label.rename(null));
|
||||
assertEquals(metadata, label.metadata());
|
||||
assertEquals(1, label.spawn().getX());
|
||||
assertEquals(2, label.spawn().getY());
|
||||
assertEquals(3, label.spawn().getZ());
|
||||
assertEquals(1, player.world.chunks.checks);
|
||||
player.world = null;
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", 1, 2, 3));
|
||||
assertDoesNotThrow(() -> wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC,
|
||||
label.rename("")), "Empty literal text is valid; it is not an account-name restriction");
|
||||
}
|
||||
|
||||
@Test
|
||||
void allPresentationOperationsPreserveNativeAccountUuidTeamAndInventoryAcrossWorldChange() throws Exception {
|
||||
var player = player();
|
||||
player.world = level();
|
||||
var oldLevel = player.world;
|
||||
var id = player.getUUID();
|
||||
var entityId = player.getId();
|
||||
var profile = player.getGameProfile();
|
||||
var team = player.board.addPlayerTeam("ordinary-team");
|
||||
team.setPlayerPrefix(Component.literal("[Ordinary]"));
|
||||
team.setNameTagVisibility(net.minecraft.world.scores.Team.Visibility.HIDE_FOR_OTHER_TEAMS);
|
||||
player.board.addPlayerToTeam(profile.name(), team);
|
||||
var members = java.util.Set.copyOf(team.getPlayers());
|
||||
var prefix = team.getPlayerPrefix().copy();
|
||||
var stack = new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.DIAMOND, 23);
|
||||
stack.set(net.minecraft.core.component.DataComponents.CUSTOM_NAME, Component.literal("Do not change 🐈"));
|
||||
player.getInventory().getNonEquipmentItems().set(17, stack);
|
||||
var savedStack = stack.copy();
|
||||
var modifiers = java.util.Set.copyOf(player.distance.getModifiers());
|
||||
player.ordinary = Component.literal("Ordinary Tab");
|
||||
var label = NativePresentationPackets.createLabel(player, "Character", 1, 2, 3);
|
||||
wire(net.minecraft.network.protocol.game.ClientboundAddEntityPacket.STREAM_CODEC, label.spawn());
|
||||
wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata());
|
||||
wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.suppressNameTag(entityId));
|
||||
var info = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.ADD_PLAYER), List.of(
|
||||
new Entry(id, profile, true, 51, GameType.CREATIVE, player.ordinary, true, 11, null)));
|
||||
roundTrip(NativePresentationPackets.projectPlayerInfo(info, id, "Character"));
|
||||
player.world = level();
|
||||
int oldAllocations = oldLevel.chunks.checks;
|
||||
wire(net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket.STREAM_CODEC, label.move(4, 5, 6));
|
||||
wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.rename("New character"));
|
||||
wire(net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket.STREAM_CODEC, label.remove());
|
||||
wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.restoreNameTag(player));
|
||||
roundTrip(NativePresentationPackets.refreshTab(player));
|
||||
assertEquals(oldAllocations, oldLevel.chunks.checks);
|
||||
assertEquals(0, player.world.chunks.checks, "Updating an old handle never silently creates a new-world entity");
|
||||
assertEquals(id, player.getUUID());
|
||||
assertEquals(entityId, player.getId());
|
||||
assertSame(profile, player.getGameProfile());
|
||||
assertEquals("Account", player.getGameProfile().name());
|
||||
assertEquals("skin-payload", player.getGameProfile().properties().get("textures").iterator().next().value());
|
||||
assertSame(team, player.getTeam());
|
||||
assertEquals(members, java.util.Set.copyOf(team.getPlayers()));
|
||||
assertEquals(prefix, team.getPlayerPrefix());
|
||||
assertEquals(net.minecraft.world.scores.Team.Visibility.HIDE_FOR_OTHER_TEAMS, team.getNameTagVisibility());
|
||||
assertEquals(1, player.board.getPlayerTeams().size());
|
||||
assertSame(stack, player.getInventory().getNonEquipmentItems().get(17));
|
||||
assertTrue(net.minecraft.world.item.ItemStack.matches(savedStack, stack));
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(modifiers, player.distance.getModifiers());
|
||||
assertEquals(Component.literal("Ordinary Tab"), player.getTabListDisplayName());
|
||||
}
|
||||
|
||||
/** The real ServerLevel ID allocator runs against an explicit tracking-index read port. */
|
||||
private static final class ReadChunks extends net.minecraft.server.level.ServerChunkCache {
|
||||
private int checks;
|
||||
private boolean rejectNext;
|
||||
private ReadChunks() { super(null, null, null, null, null, null, 0, 0, false, null, null, null); }
|
||||
@Override public boolean hasEntityWithId(int id) {
|
||||
checks++;
|
||||
boolean reject = rejectNext;
|
||||
rejectNext = false;
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ReadLevel extends net.minecraft.server.level.ServerLevel {
|
||||
private io.papermc.paper.configuration.WorldConfiguration config;
|
||||
private ReadChunks chunks;
|
||||
private ReadLevel() { super(null, null, null, null, null, null, false, 0, null, false, null, null, null, null, null, null); }
|
||||
@Override public io.papermc.paper.configuration.WorldConfiguration paperConfig() { return config; }
|
||||
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity entity) { throw new AssertionError("Never insert a label"); }
|
||||
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) {
|
||||
throw new AssertionError("Never insert a label");
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadLevel level() throws Exception {
|
||||
var level = allocate(ReadLevel.class);
|
||||
level.chunks = allocate(ReadChunks.class);
|
||||
setField(net.minecraft.server.level.ServerLevel.class, level, "chunkSource", level.chunks);
|
||||
setField(net.minecraft.world.level.Level.class, level, "spigotConfig", allocate(org.spigotmc.SpigotWorldConfig.class));
|
||||
var purpur = allocate(org.purpurmc.purpur.PurpurWorldConfig.class);
|
||||
purpur.drowningAirTicks = 300;
|
||||
setField(net.minecraft.world.level.Level.class, level, "purpurConfig", purpur);
|
||||
level.config = allocate(io.papermc.paper.configuration.WorldConfiguration.class);
|
||||
level.config.entities = allocate(io.papermc.paper.configuration.WorldConfiguration.Entities.class);
|
||||
level.config.entities.spawning = allocate(io.papermc.paper.configuration.WorldConfiguration.Entities.Spawning.class);
|
||||
level.config.entities.spawning.despawnTime = new it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap<>();
|
||||
return level;
|
||||
}
|
||||
|
||||
private static void setField(Class<?> owner, Object target, String name, Object value) throws Exception {
|
||||
var field = owner.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(target, value);
|
||||
}
|
||||
|
||||
/** Constructor-free read boundary. Native attributes and packet codecs are real. */
|
||||
private static final class ReadPlayer extends net.minecraft.server.level.ServerPlayer {
|
||||
private net.minecraft.world.entity.ai.attributes.AttributeInstance distance;
|
||||
private Component ordinary;
|
||||
private net.minecraft.world.scores.Scoreboard board;
|
||||
private ReadLevel world;
|
||||
@Override public net.minecraft.server.level.ServerLevel level() { return world; }
|
||||
private ReadPlayer() { super(null, null, null, null); throw new AssertionError("Never construct a server player"); }
|
||||
@Override public Component getTabListDisplayName() { return ordinary; }
|
||||
@Override public net.minecraft.world.scores.PlayerTeam getTeam() { return board.getPlayersTeam(getScoreboardName()); }
|
||||
@Override public net.minecraft.world.entity.ai.attributes.AttributeInstance getAttribute(
|
||||
net.minecraft.core.Holder<net.minecraft.world.entity.ai.attributes.Attribute> type) {
|
||||
assertEquals(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, type);
|
||||
return distance;
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadPlayer player() throws Exception {
|
||||
var player = allocate(ReadPlayer.class);
|
||||
player.setId(93);
|
||||
player.setUUID(UUID.randomUUID());
|
||||
player.gameProfile = new GameProfile(player.getUUID(), "Account", new PropertyMap(ImmutableMultimap.of("textures",
|
||||
new Property("textures", "skin-payload", "skin-signature"))));
|
||||
player.board = new net.minecraft.world.scores.Scoreboard();
|
||||
setField(net.minecraft.world.entity.player.Player.class, player, "inventory",
|
||||
new net.minecraft.world.entity.player.Inventory(player, new net.minecraft.world.entity.EntityEquipment()));
|
||||
player.distance = attribute(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, 57.25);
|
||||
return player;
|
||||
}
|
||||
|
||||
private static <T> T allocate(Class<T> type) throws Exception {
|
||||
var unsafe = Class.forName("sun.misc.Unsafe");
|
||||
var field = unsafe.getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
return type.cast(unsafe.getMethod("allocateInstance", Class.class).invoke(field.get(null), type));
|
||||
}
|
||||
|
||||
private static net.minecraft.world.entity.ai.attributes.AttributeInstance attribute(
|
||||
net.minecraft.core.Holder<net.minecraft.world.entity.ai.attributes.Attribute> type, double base) {
|
||||
var instance = new net.minecraft.world.entity.ai.attributes.AttributeInstance(type, ignored -> { });
|
||||
instance.setBaseValue(base);
|
||||
for (var operation : net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.values()) {
|
||||
instance.addTransientModifier(new net.minecraft.world.entity.ai.attributes.AttributeModifier(
|
||||
net.minecraft.resources.Identifier.fromNamespaceAndPath("test", operation.name().toLowerCase(java.util.Locale.ROOT)),
|
||||
0.25, operation));
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static <T> T wire(net.minecraft.network.codec.StreamCodec<? super RegistryFriendlyByteBuf, T> codec, T packet) {
|
||||
var buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), CraftRegistry.getMinecraftRegistry());
|
||||
try {
|
||||
codec.encode(buffer, packet);
|
||||
T decoded = codec.decode(buffer);
|
||||
assertFalse(buffer.isReadable(), "The actual pinned schema consumes every byte");
|
||||
return decoded;
|
||||
} finally { buffer.release(); }
|
||||
}
|
||||
|
||||
private static Entry entry(String account, boolean listed, int latency, GameType gameMode,
|
||||
boolean hat, int order) throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
var profile = new GameProfile(id, account, new PropertyMap(ImmutableMultimap.of("textures",
|
||||
new Property("textures", "skin-payload-" + account, "skin-signature-" + account))));
|
||||
var keyGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyGenerator.initialize(2048);
|
||||
var key = new ProfilePublicKey.Data(Instant.ofEpochSecond(2_000_000_000L),
|
||||
keyGenerator.generateKeyPair().getPublic(), new byte[] {1, 3, 7, 9});
|
||||
return new Entry(id, profile, listed, latency, gameMode, Component.literal("Ordinary " + account),
|
||||
hat, order, new RemoteChatSession.Data(UUID.randomUUID(), key));
|
||||
}
|
||||
|
||||
private static void assertPreserved(Entry before, Entry after, Component expectedDisplay) {
|
||||
assertEquals(before.profileId(), after.profileId());
|
||||
assertEquals(before.profile().id(), after.profile().id());
|
||||
assertEquals(before.profile().name(), after.profile().name());
|
||||
assertEquals(before.profile().properties(), after.profile().properties());
|
||||
assertEquals(before.listed(), after.listed());
|
||||
assertEquals(before.latency(), after.latency());
|
||||
assertEquals(before.gameMode(), after.gameMode());
|
||||
assertEquals(expectedDisplay, after.displayName());
|
||||
assertEquals(before.showHat(), after.showHat());
|
||||
assertEquals(before.listOrder(), after.listOrder());
|
||||
assertEquals(before.chatSession().sessionId(), after.chatSession().sessionId());
|
||||
var beforeKey = before.chatSession().profilePublicKey();
|
||||
var afterKey = after.chatSession().profilePublicKey();
|
||||
assertEquals(beforeKey.expiresAt(), afterKey.expiresAt());
|
||||
assertEquals(beforeKey.key(), afterKey.key());
|
||||
assertArrayEquals(beforeKey.keySignature(), afterKey.keySignature());
|
||||
}
|
||||
|
||||
private static ClientboundPlayerInfoUpdatePacket roundTrip(ClientboundPlayerInfoUpdatePacket packet) {
|
||||
var buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), CraftRegistry.getMinecraftRegistry());
|
||||
try {
|
||||
ClientboundPlayerInfoUpdatePacket.STREAM_CODEC.encode(buffer, packet);
|
||||
var decoded = ClientboundPlayerInfoUpdatePacket.STREAM_CODEC.decode(buffer);
|
||||
assertFalse(buffer.isReadable(), "The actual pinned packet schema consumes every byte");
|
||||
return decoded;
|
||||
} finally { buffer.release(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import java.nio.file.Path;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Native book payloads feed real Paper custom-click events through packaged startup registration. */
|
||||
class PartyBookNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void bookCreatesPlayerOwnedPartyThroughNativeCustomClickWithoutInventoryChanges() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var before = a.core.snapshot();
|
||||
open(f, a);
|
||||
var create = button(a, "[Create party]");
|
||||
click(f, a, create);
|
||||
var party = PartyLifecycleNativeTest.parties(f).partyOf(a.core.id).orElseThrow();
|
||||
assertEquals(a.core.id, party.leader());
|
||||
assertEquals(java.util.List.of(a.core.id), party.members());
|
||||
click(f, a, create); // The old page cannot perform the action twice.
|
||||
assertEquals(party, PartyLifecycleNativeTest.parties(f).partyOf(a.core.id).orElseThrow());
|
||||
assertArrayEquals(before, a.core.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void memberBookLeavePreservesPartyButLeaderBookLeaveDisbandsWithoutSuccession() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
f.activate(leader); f.activate(member);
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
var party = parties.create(leader.core.id).orElseThrow();
|
||||
assertTrue(parties.accept(member.core.id, parties.invite(leader.core.id, party.id(), member.core.id).orElseThrow().id()));
|
||||
open(f, member); click(f, member, button(member, "[Leave party]"));
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
assertEquals(party.id(), parties.partyOf(leader.core.id).orElseThrow().id());
|
||||
assertTrue(parties.accept(member.core.id, parties.invite(leader.core.id, party.id(), member.core.id).orElseThrow().id()));
|
||||
open(f, leader); click(f, leader, button(leader, "[Leave party]"));
|
||||
assertTrue(parties.partyOf(leader.core.id).isEmpty());
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void nativeBookInvitesRequireAcceptanceDisplayCharacterNamesAndAllowLeaderKick() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
f.activate(leader); f.activate(member);
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
open(f, leader); click(f, leader, button(leader, "[Create party]")); drain(f);
|
||||
click(f, leader, button(leader, "[Invite players]"));
|
||||
assertTrue(text(leader).contains(member.core.record.name()));
|
||||
click(f, leader, button(leader, "[Invite]"));
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
assertTrue(member.messages.stream().anyMatch(message -> message.contains("invitation")));
|
||||
open(f, member); click(f, member, button(member, "[Invitations]"));
|
||||
assertTrue(text(member).contains(leader.core.record.name()));
|
||||
click(f, member, button(member, "[Accept]")); drain(f);
|
||||
assertEquals(parties.partyOf(leader.core.id), parties.partyOf(member.core.id));
|
||||
assertTrue(text(member).contains(leader.core.record.name()));
|
||||
assertTrue(text(member).contains(member.core.record.name()));
|
||||
open(f, leader); click(f, leader, button(leader, "[Kick]"));
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
assertEquals(java.util.List.of(leader.core.id), parties.partyOf(leader.core.id).orElseThrow().members());
|
||||
drain(f); click(f, leader, button(leader, "[Disband party]"));
|
||||
assertTrue(parties.partyOf(leader.core.id).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void copiedReplacedMalformedAndWrongNamespaceActionsCannotCreateParties() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var b = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.players.put(b.core.id, b.player);
|
||||
f.activate(a); f.activate(b);
|
||||
open(f, a); var old = button(a, "[Create party]");
|
||||
open(f, b); click(f, b, old);
|
||||
assertTrue(PartyLifecycleNativeTest.parties(f).partyOf(b.core.id).isEmpty());
|
||||
open(f, a); var current = button(a, "[Create party]");
|
||||
click(f, a, old);
|
||||
for (var payload : java.util.List.of(net.minecraft.nbt.StringTag.valueOf("x".repeat(1000)),
|
||||
net.minecraft.nbt.StringTag.valueOf("not-a-token"), new net.minecraft.nbt.CompoundTag())) {
|
||||
click(f, a, new net.minecraft.network.chat.ClickEvent.Custom(current.id(), java.util.Optional.of(payload)));
|
||||
}
|
||||
click(f, a, new net.minecraft.network.chat.ClickEvent.Custom(
|
||||
net.minecraft.resources.Identifier.fromNamespaceAndPath("other", "party_book"), current.payload()));
|
||||
assertTrue(PartyLifecycleNativeTest.parties(f).partyOf(a.core.id).isEmpty());
|
||||
click(f, a, current);
|
||||
assertTrue(PartyLifecycleNativeTest.parties(f).partyOf(a.core.id).isPresent(), "Invalid packets must not consume the legitimate view");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void changedSlotOrEndedCharacterCannotUseOldPartyControlsEvenAfterReturningToBookSlot() throws Exception {
|
||||
for (int route = 0; route < 3; route++) try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("route-" + route))) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data.resolve("route-" + route));
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
open(f, a); var action = button(a, "[Create party]");
|
||||
if (route == 0) a.core.inventory.getInventory().setSelectedSlot(1);
|
||||
else if (route == 1) { a.core.inventory.setItemInOffHand(null); f.changed(a); }
|
||||
else { f.plugin.setEnabled(false); f.awaitWorkers(); }
|
||||
click(f, a, action);
|
||||
a.core.inventory.getInventory().setSelectedSlot(0);
|
||||
click(f, a, action);
|
||||
assertTrue(parties.partyOf(a.core.id).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void managementRechecksPartyIdentityRatherThanDisbandingAReplacementFromAnOldPage() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
var previous = parties.create(a.core.id).orElseThrow();
|
||||
open(f, a); var old = button(a, "[Disband party]");
|
||||
assertTrue(parties.leave(a.core.id, previous.id()));
|
||||
var replacement = parties.create(a.core.id).orElseThrow();
|
||||
click(f, a, old);
|
||||
assertEquals(replacement, parties.partyOf(a.core.id).orElseThrow());
|
||||
assertTrue(a.messages.stream().anyMatch(message -> message.contains("Party action unavailable")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void inviteChoicesArePagedAndMovingPagesRevokesTheOldPagesActions() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var candidates = new java.util.ArrayList<UUID>();
|
||||
for (int i = 0; i < 101; i++) {
|
||||
var id = UUID.randomUUID(); candidates.add(id);
|
||||
var player = mock(org.bukkit.entity.Player.class);
|
||||
when(player.getUniqueId()).thenReturn(id); when(player.isOnline()).thenReturn(true);
|
||||
when(player.getName()).thenReturn("Candidate " + i); f.players.put(id, player);
|
||||
}
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
parties.create(a.core.id).orElseThrow();
|
||||
open(f, a); click(f, a, button(a, "[Invite players]"));
|
||||
var old = button(a, "[Invite]");
|
||||
assertTrue(((org.bukkit.inventory.meta.BookMeta) a.books.getLast().getItemMeta()).getPageCount() <= 100);
|
||||
click(f, a, button(a, "[Next]")); click(f, a, old);
|
||||
assertTrue(candidates.stream().allMatch(id -> parties.invitationsFor(id).isEmpty()));
|
||||
click(f, a, button(a, "[Invite]"));
|
||||
assertEquals(1, candidates.stream().filter(id -> !parties.invitationsFor(id).isEmpty()).count());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void anInvitationAlreadyRenderedInTheBookCannotBeAcceptedAtItsRealTimeDeadline() throws Exception {
|
||||
var now = new java.util.concurrent.atomic.AtomicReference<>(java.time.Instant.EPOCH);
|
||||
var clock = new java.time.Clock() {
|
||||
@Override public java.time.ZoneId getZone() { return java.time.ZoneOffset.UTC; }
|
||||
@Override public java.time.Clock withZone(java.time.ZoneId zone) { return this; }
|
||||
@Override public java.time.Instant instant() { return now.get(); }
|
||||
};
|
||||
try (var clocks = mockStatic(java.time.Clock.class, CALLS_REAL_METHODS)) {
|
||||
clocks.when(java.time.Clock::systemUTC).thenReturn(clock);
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
f.activate(leader); f.activate(member);
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
var group = parties.create(leader.core.id).orElseThrow();
|
||||
parties.invite(leader.core.id, group.id(), member.core.id).orElseThrow();
|
||||
open(f, member); click(f, member, button(member, "[Invitations]"));
|
||||
var accept = button(member, "[Accept]");
|
||||
now.set(java.time.Instant.EPOCH.plusSeconds(60));
|
||||
click(f, member, accept);
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
assertTrue(parties.invitationsFor(member.core.id).isEmpty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void anOpenAcceptancePageCannotOverfillAPartyThatFilledAfterRendering() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
f.activate(leader); f.activate(member);
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
var group = parties.create(leader.core.id).orElseThrow();
|
||||
parties.invite(leader.core.id, group.id(), member.core.id).orElseThrow();
|
||||
open(f, member); click(f, member, button(member, "[Invitations]"));
|
||||
var accept = button(member, "[Accept]");
|
||||
for (int i = 0; i < 5; i++) {
|
||||
UUID id = UUID.randomUUID();
|
||||
var player = mock(org.bukkit.entity.Player.class);
|
||||
when(player.getUniqueId()).thenReturn(id); when(player.isOnline()).thenReturn(true);
|
||||
f.players.put(id, player);
|
||||
assertTrue(parties.accept(id, parties.invite(leader.core.id, group.id(), id).orElseThrow().id()));
|
||||
}
|
||||
click(f, member, accept);
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
assertEquals(6, parties.partyOf(leader.core.id).orElseThrow().members().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void sheetTransferAndCharacterSwitchKeepMembershipOnThePlayerAndInvalidateOldBookActions() throws Exception {
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"), "character-swap-cooldown-seconds: 0\n");
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var b = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player); f.players.put(b.core.id, b.player);
|
||||
var otherSheet = b.core.inventory.getItemInOffHand().clone();
|
||||
f.activate(a);
|
||||
var parties = PartyLifecycleNativeTest.parties(f);
|
||||
var party = parties.create(a.core.id).orElseThrow();
|
||||
open(f, a); var oldDisband = button(a, "[Disband party]");
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone();
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
b.core.inventory.setItemInOffHand(sheet); f.activate(b);
|
||||
open(f, b);
|
||||
assertTrue(text(b).contains(a.core.record.name()));
|
||||
assertTrue(parties.partyOf(b.core.id).isEmpty(), "A traded sheet must not transfer party membership");
|
||||
click(f, b, oldDisband);
|
||||
a.core.inventory.setItemInOffHand(otherSheet); f.activate(a);
|
||||
open(f, a);
|
||||
assertTrue(text(a).contains(b.core.record.name()));
|
||||
assertEquals(party.id(), parties.partyOf(a.core.id).orElseThrow().id());
|
||||
click(f, a, oldDisband);
|
||||
assertEquals(party.id(), parties.partyOf(a.core.id).orElseThrow().id());
|
||||
}
|
||||
}
|
||||
|
||||
static String text(FantasyStickLifecycleNativeTest.Actor a) {
|
||||
return org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(a.books.getLast())
|
||||
.get(net.minecraft.core.component.DataComponents.WRITTEN_BOOK_CONTENT).pages().stream()
|
||||
.map(page -> page.raw().getString()).collect(java.util.stream.Collectors.joining("\n"));
|
||||
}
|
||||
|
||||
static void open(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor a) throws Exception {
|
||||
f.dispatcher.accept(new PlayerInteractEvent(a.player, Action.RIGHT_CLICK_AIR, a.core.inventory.getItemInMainHand(),
|
||||
null, BlockFace.SELF, EquipmentSlot.HAND));
|
||||
drain(f);
|
||||
}
|
||||
static void drain(FantasyStickLifecycleNativeTest.Fixture f) throws Exception {
|
||||
((CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters"))
|
||||
.find(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
|
||||
Runnable task;
|
||||
while ((task = f.tasks.poll()) != null) task.run();
|
||||
}
|
||||
static net.minecraft.network.chat.ClickEvent.Custom button(FantasyStickLifecycleNativeTest.Actor a, String label) {
|
||||
var book = org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(a.books.getLast())
|
||||
.get(net.minecraft.core.component.DataComponents.WRITTEN_BOOK_CONTENT);
|
||||
assertNotNull(book);
|
||||
for (var page : book.pages()) {
|
||||
var click = find(page.raw(), label);
|
||||
if (click != null) return click;
|
||||
}
|
||||
throw new AssertionError("Missing native book action " + label);
|
||||
}
|
||||
static net.minecraft.network.chat.ClickEvent.Custom find(net.minecraft.network.chat.Component component, String label) {
|
||||
if (component.getString().equals(label) && component.getStyle().getClickEvent() instanceof net.minecraft.network.chat.ClickEvent.Custom custom) return custom;
|
||||
for (var child : component.getSiblings()) {
|
||||
var found = find(child, label);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
static void click(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor a,
|
||||
net.minecraft.network.chat.ClickEvent.Custom click) {
|
||||
var connection = mock(io.papermc.paper.connection.PlayerGameConnection.class);
|
||||
when(connection.getPlayer()).thenReturn(a.player);
|
||||
f.dispatcher.accept(new io.papermc.paper.event.player.PaperPlayerCustomClickEvent(
|
||||
net.kyori.adventure.key.Key.key(click.id().toString()), connection, click.payload().orElse(null)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import org.bukkit.damage.DamageSource;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Actual packaged listeners and book clicks; native damage events have explicit world/source ports. */
|
||||
class PartyCombatNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
private static final java.util.Map<org.bukkit.entity.Player, java.util.Map<org.bukkit.potion.PotionEffectType, net.minecraft.world.effect.MobEffectInstance>> effects = new java.util.WeakHashMap<>();
|
||||
private static final java.util.Map<org.bukkit.entity.Player, Integer> fires = new java.util.WeakHashMap<>();
|
||||
|
||||
@Test void bookConsentProtectsCombatAndBookLeaveKickDisbandImmediatelyRemoveProtection() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f);
|
||||
f.activate(a); f.activate(b);
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled(), "Non-party fantasy combat remains available");
|
||||
createAndInvite(f, a, b);
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled(), "An invitation is not membership");
|
||||
accept(f, b);
|
||||
assertTrue(hit(f, a.player, b.player).isCancelled(), "Book acceptance must protect native combat");
|
||||
assertTrue(hit(f, b.player, a.player).isCancelled());
|
||||
PartyBookNativeTest.open(f, b); action(f, b, "Leave party");
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled());
|
||||
invite(f, a); accept(f, b);
|
||||
PartyBookNativeTest.open(f, a); action(f, a, "Kick");
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled());
|
||||
invite(f, a); accept(f, b);
|
||||
PartyBookNativeTest.open(f, a); action(f, a, "Disband party");
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void mixedModesAreProtectedBothWaysButOrdinaryCombatMobsSelfDamageAndPriorVetoesAreUnchanged() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f);
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled());
|
||||
f.activate(a);
|
||||
assertTrue(hit(f, a.player, b.player).isCancelled());
|
||||
assertTrue(hit(f, b.player, a.player).isCancelled());
|
||||
assertFalse(hit(f, entity(org.bukkit.entity.Zombie.class), a.player).isCancelled());
|
||||
assertFalse(hit(f, a.player, entity(org.bukkit.entity.Zombie.class)).isCancelled());
|
||||
assertFalse(hit(f, a.player, a.player).isCancelled());
|
||||
var environmental = new org.bukkit.event.entity.EntityDamageEvent(a.player, DamageCause.FALL, mock(DamageSource.class), 4);
|
||||
f.dispatcher.accept(environmental); assertFalse(environmental.isCancelled());
|
||||
f.activate(b);
|
||||
var damage = mock(DamageSource.class);
|
||||
when(damage.getCausingEntity()).thenReturn(a.player);
|
||||
var veto = new EntityDamageByEntityEvent(a.player, b.player, DamageCause.ENTITY_ATTACK, damage, 4);
|
||||
veto.setCancelled(true); f.dispatcher.accept(veto);
|
||||
assertTrue(veto.isCancelled()); assertEquals(4, veto.getDamage());
|
||||
var group = PartyLifecycleNativeTest.parties(f).create(a.core.id).orElseThrow();
|
||||
assertTrue(PartyLifecycleNativeTest.parties(f).accept(b.core.id,
|
||||
PartyLifecycleNativeTest.parties(f).invite(a.core.id, group.id(), b.core.id).orElseThrow().id()));
|
||||
exit(f, a); exit(f, b);
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled(), "Retained membership is not ordinary PvP immunity");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void projectilesRecheckPartyAtImpactAndCannotBorrowANewSessionAfterExitOrSwitch() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f);
|
||||
f.activate(a); f.activate(b);
|
||||
var arrow = projectile(f, a.player);
|
||||
assertFalse(hit(f, arrow, b.player).isCancelled());
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertTrue(hit(f, arrow, b.player).isCancelled(), "Native indirect attribution must use current party");
|
||||
PartyBookNativeTest.open(f, b); action(f, b, "Leave party");
|
||||
assertFalse(hit(f, arrow, b.player).isCancelled());
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone();
|
||||
exit(f, a);
|
||||
assertTrue(hit(f, arrow, b.player).isCancelled(), "Fantasy projectile loses authority on exit");
|
||||
a.core.inventory.setItemInOffHand(sheet); f.activate(a);
|
||||
assertTrue(hit(f, arrow, b.player).isCancelled(), "Same character reentry is still a different session");
|
||||
assertFalse(hit(f, projectile(f, a.player), b.player).isCancelled());
|
||||
var stranger = actor(f);
|
||||
var ordinaryArrow = projectile(f, stranger.player);
|
||||
assertTrue(hit(f, ordinaryArrow, b.player).isCancelled());
|
||||
f.activate(stranger);
|
||||
assertTrue(hit(f, ordinaryArrow, b.player).isCancelled(), "Old ordinary projectile must not become fantasy damage");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void explosiveFangsCloudPetAndFireworkSourcesRespectPartiesAndCapturedSessions() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
var tnt = entity(org.bukkit.entity.TNTPrimed.class); when(tnt.getSource()).thenReturn(a.player);
|
||||
var fangs = entity(org.bukkit.entity.EvokerFangs.class); when(fangs.getOwner()).thenReturn(a.player);
|
||||
var cloud = entity(org.bukkit.entity.AreaEffectCloud.class); when(cloud.getSource()).thenReturn(a.player);
|
||||
var pet = entity(org.bukkit.entity.Wolf.class); when(pet.getOwnerUniqueId()).thenReturn(a.core.id);
|
||||
var firework = entity(org.bukkit.entity.Firework.class); when(firework.getSpawningEntity()).thenReturn(a.core.id);
|
||||
for (var source : java.util.List.of(tnt, fangs, cloud, firework)) f.dispatcher.accept(new org.bukkit.event.entity.EntitySpawnEvent(source));
|
||||
for (var source : java.util.List.of(tnt, fangs, cloud, pet, firework)) {
|
||||
assertTrue(hit(f, source, b.player).isCancelled(), source.getClass().toString());
|
||||
}
|
||||
PartyBookNativeTest.open(f, b); action(f, b, "Leave party");
|
||||
for (var source : java.util.List.of(tnt, fangs, cloud, pet, firework)) assertFalse(hit(f, source, b.player).isCancelled());
|
||||
exit(f, a);
|
||||
for (var source : java.util.List.of(tnt, fangs, cloud, pet, firework)) assertTrue(hit(f, source, b.player).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void lingeringCloudInheritsTheOriginalThrownPotionSessionRatherThanItsOwnersReplacement() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var potion = entity(org.bukkit.entity.ThrownPotion.class); when(potion.getShooter()).thenReturn(a.player);
|
||||
f.dispatcher.accept(new org.bukkit.event.entity.ProjectileLaunchEvent(potion));
|
||||
var cloud = entity(org.bukkit.entity.AreaEffectCloud.class); when(cloud.getSource()).thenReturn(a.player);
|
||||
var splash = new org.bukkit.event.entity.LingeringPotionSplashEvent(potion, cloud);
|
||||
f.dispatcher.accept(splash); assertFalse(splash.isCancelled());
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone(); exit(f, a);
|
||||
a.core.inventory.setItemInOffHand(sheet); f.activate(a);
|
||||
f.dispatcher.accept(new org.bukkit.event.entity.EntitySpawnEvent(cloud));
|
||||
assertTrue(hit(f, cloud, b.player).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void poisonAndWitherRevalidateEachTickAndClearOnRemovalReplacementWithoutTouchingHealing() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
for (var type : java.util.List.of(org.bukkit.potion.PotionEffectType.POISON, org.bukkit.potion.PotionEffectType.WITHER)) {
|
||||
var effect = new org.bukkit.potion.PotionEffect(type, 200, 0);
|
||||
var cause = type.equals(org.bukkit.potion.PotionEffectType.POISON) ? DamageCause.POISON : DamageCause.WITHER;
|
||||
assertFalse(apply(f, b, null, effect, a.player).isCancelled());
|
||||
assertFalse(tickDamage(f, b, cause).isCancelled());
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertTrue(tickDamage(f, b, cause).isCancelled(), "Tick loses native attacker but not our application provenance");
|
||||
var heal = new org.bukkit.potion.PotionEffect(org.bukkit.potion.PotionEffectType.REGENERATION, 200, 0);
|
||||
assertFalse(apply(f, b, null, heal, a.player).isCancelled());
|
||||
assertTrue(apply(f, b, effect, new org.bukkit.potion.PotionEffect(type, 300, 1), a.player).isCancelled());
|
||||
var remove = new org.bukkit.event.entity.EntityPotionEffectEvent(b.player, effect, null, null,
|
||||
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.MILK, org.bukkit.event.entity.EntityPotionEffectEvent.Action.REMOVED, false);
|
||||
f.dispatcher.accept(remove); effects.get(b.player).remove(type);
|
||||
assertFalse(tickDamage(f, b, cause).isCancelled(), "Removed attribution must not protect unrelated later damage");
|
||||
PartyBookNativeTest.open(f, a); action(f, a, "Disband party");
|
||||
assertFalse(apply(f, b, null, effect, a.player).isCancelled());
|
||||
// An unrelated mob/environmental replacement clears only this effect's provenance.
|
||||
assertFalse(apply(f, b, effect, new org.bukkit.potion.PotionEffect(type, 300, 1), null).isCancelled());
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertFalse(tickDamage(f, b, cause).isCancelled());
|
||||
PartyBookNativeTest.open(f, a); action(f, a, "Disband party");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void ongoingDamageCannotMoveToANewSourceOrTargetSessionAndCancelledChangesDoNotEraseProvenance() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var effect = new org.bukkit.potion.PotionEffect(org.bukkit.potion.PotionEffectType.POISON, 200, 0);
|
||||
apply(f, b, null, effect, a.player);
|
||||
var replacement = new org.bukkit.event.entity.EntityPotionEffectEvent(b.player, effect, null, null,
|
||||
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.MILK, org.bukkit.event.entity.EntityPotionEffectEvent.Action.REMOVED, false);
|
||||
replacement.setCancelled(true); f.dispatcher.accept(replacement);
|
||||
var sheet = b.core.inventory.getItemInOffHand().clone(); exit(f, b);
|
||||
assertTrue(tickDamage(f, b, DamageCause.POISON).isCancelled());
|
||||
b.core.inventory.setItemInOffHand(sheet); f.activate(b);
|
||||
assertTrue(tickDamage(f, b, DamageCause.POISON).isCancelled(), "An old poison cannot attack a replacement target session");
|
||||
apply(f, b, effect, new org.bukkit.potion.PotionEffect(effect.getType(), 300, 1), a.player);
|
||||
assertFalse(tickDamage(f, b, DamageCause.POISON).isCancelled());
|
||||
exit(f, a);
|
||||
assertTrue(tickDamage(f, b, DamageCause.POISON).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void burningChecksPartyEveryTickAndCancelledOrEnvironmentalIgnitionCannotStealAttribution() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var arrow = projectile(f, a.player);
|
||||
var fire = new org.bukkit.event.entity.EntityCombustByEntityEvent(arrow, b.player, 10.0f);
|
||||
f.dispatcher.accept(fire); assertFalse(fire.isCancelled()); fires.put(b.player, 200);
|
||||
assertFalse(tickDamage(f, b, DamageCause.FIRE_TICK).isCancelled());
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertTrue(tickDamage(f, b, DamageCause.FIRE_TICK).isCancelled());
|
||||
var refused = new org.bukkit.event.entity.EntityCombustByEntityEvent(arrow, b.player, 15.0f);
|
||||
f.dispatcher.accept(refused); assertTrue(refused.isCancelled());
|
||||
var cancelledEnvironmental = new org.bukkit.event.entity.EntityCombustEvent(b.player, 5.0f);
|
||||
cancelledEnvironmental.setCancelled(true); f.dispatcher.accept(cancelledEnvironmental);
|
||||
assertTrue(tickDamage(f, b, DamageCause.FIRE_TICK).isCancelled());
|
||||
f.dispatcher.accept(new org.bukkit.event.entity.EntityCombustEvent(b.player, 15.0f));
|
||||
assertFalse(tickDamage(f, b, DamageCause.FIRE_TICK).isCancelled());
|
||||
assertFalse(tickDamage(f, b, DamageCause.LAVA).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void expiredAndHiddenPotionLayersKeepOnlyTheirOwnSourceAndFireExpiryIsCleaned() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var type = org.bukkit.potion.PotionEffectType.POISON;
|
||||
var poison = new org.bukkit.potion.PotionEffect(type, 200, 0);
|
||||
apply(f, b, null, poison, a.player);
|
||||
// A shorter, stronger environmental layer temporarily covers the attributable one.
|
||||
apply(f, b, poison, new org.bukkit.potion.PotionEffect(type, 40, 1), null);
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertFalse(tickDamage(f, b, DamageCause.POISON).isCancelled(), "Environmental top layer must not inherit old source");
|
||||
var nativeEffect = effects.get(b.player).get(type);
|
||||
assertNotNull(nativeEffect.hiddenEffect);
|
||||
effects.get(b.player).put(type, nativeEffect.hiddenEffect);
|
||||
assertTrue(tickDamage(f, b, DamageCause.POISON).isCancelled(), "Native hidden-layer restoration retains its own source");
|
||||
effects.get(b.player).clear();
|
||||
for (var pulse : f.pulses) pulse.run();
|
||||
assertFalse(b.core.pdc.getKeys().stream().anyMatch(key -> key.getKey().startsWith("combat_dot_")));
|
||||
assertFalse(tickDamage(f, b, DamageCause.POISON).isCancelled());
|
||||
PartyBookNativeTest.open(f, a); action(f, a, "Disband party");
|
||||
f.dispatcher.accept(new org.bukkit.event.entity.EntityCombustByEntityEvent(a.player, b.player, 2.0f));
|
||||
fires.put(b.player, 40);
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertTrue(tickDamage(f, b, DamageCause.FIRE_TICK).isCancelled());
|
||||
fires.put(b.player, 0);
|
||||
for (var pulse : f.pulses) pulse.run();
|
||||
assertFalse(b.core.pdc.getKeys().stream().anyMatch(key -> key.getKey().startsWith("combat_dot_")));
|
||||
fires.put(b.player, 20); // Later unrelated fire must not borrow a stale player source.
|
||||
assertFalse(tickDamage(f, b, DamageCause.FIRE_TICK).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void staleNativeSplashIsCancelledBeforeOwnerOnlyEffectAttributionAndValidHealingIsUntouched() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var potion = entity(org.bukkit.entity.ThrownPotion.class); when(potion.getShooter()).thenReturn(a.player);
|
||||
f.dispatcher.accept(new org.bukkit.event.entity.ProjectileLaunchEvent(potion));
|
||||
var splash = new org.bukkit.event.entity.PotionSplashEvent(potion, new java.util.HashMap<>(java.util.Map.of(b.player, 1.0)));
|
||||
f.dispatcher.accept(splash); assertFalse(splash.isCancelled());
|
||||
assertEquals(1.0, splash.getIntensity(b.player));
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone(); exit(f, a);
|
||||
a.core.inventory.setItemInOffHand(sheet); f.activate(a);
|
||||
var stale = new org.bukkit.event.entity.PotionSplashEvent(potion, new java.util.HashMap<>(java.util.Map.of(b.player, 1.0)));
|
||||
f.dispatcher.accept(stale);
|
||||
assertTrue(stale.isCancelled(), "Native splash passes only owner to addEffect: stop stale continuation before attribution is lost");
|
||||
var arrow = projectile(f, a.player);
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
var impact = new org.bukkit.event.entity.ProjectileHitEvent(arrow, b.player);
|
||||
f.dispatcher.accept(impact); assertTrue(impact.isCancelled());
|
||||
var heal = new org.bukkit.potion.PotionEffect(org.bukkit.potion.PotionEffectType.REGENERATION, 100, 0);
|
||||
assertFalse(apply(f, b, null, heal, a.player).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void cancelledApplicationsAndLaunchesRetainUnrelatedDataAndCleanupStopsOnDisable() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var arrow = entity(org.bukkit.entity.Arrow.class); when(arrow.getShooter()).thenReturn(a.player);
|
||||
var launch = new org.bukkit.event.entity.ProjectileLaunchEvent(arrow); launch.setCancelled(true);
|
||||
var unrelated = new org.bukkit.NamespacedKey("other", "state");
|
||||
arrow.getPersistentDataContainer().set(unrelated, org.bukkit.persistence.PersistentDataType.STRING, "retained");
|
||||
f.dispatcher.accept(launch);
|
||||
assertEquals(java.util.Set.of(unrelated), arrow.getPersistentDataContainer().getKeys());
|
||||
var effect = new org.bukkit.potion.PotionEffect(org.bukkit.potion.PotionEffectType.POISON, 200, 0);
|
||||
var veto = new org.bukkit.event.entity.EntityPotionEffectEvent(b.player, null, effect, a.player,
|
||||
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_SPLASH,
|
||||
org.bukkit.event.entity.EntityPotionEffectEvent.Action.ADDED, false);
|
||||
veto.setCancelled(true); f.dispatcher.accept(veto);
|
||||
assertTrue(veto.isCancelled());
|
||||
assertFalse(b.core.pdc.getKeys().stream().anyMatch(key -> key.getKey().startsWith("combat_dot_")));
|
||||
var before = new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(a.core.record.id());
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertEquals(before, new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(a.core.record.id()), "Party proximity does not grant progress or XP");
|
||||
f.plugin.setEnabled(false); f.awaitWorkers();
|
||||
for (var timer : f.timers) verify(timer, atLeastOnce()).cancel();
|
||||
for (var pulse : f.pulses) pulse.run();
|
||||
}
|
||||
}
|
||||
|
||||
@Test void aCapturedFantasySourceRequiresCurrentOffhandCustodyAndConnectionNotJustRegistryPresence() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var arrow = projectile(f, a.player);
|
||||
a.core.online = false;
|
||||
assertTrue(hit(f, arrow, b.player).isCancelled());
|
||||
a.core.online = true;
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone();
|
||||
a.core.inventory.setItemInOffHand(null); // Before the slot-change/recovery callback.
|
||||
assertTrue(hit(f, arrow, b.player).isCancelled());
|
||||
a.core.inventory.setItemInOffHand(sheet);
|
||||
assertFalse(hit(f, arrow, b.player).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void nativeSerializationAndRestartKeepStaleDamageProvenanceButNeverRestorePartiesOrXp() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var arrow = projectile(f, a.player);
|
||||
var restoredArrow = entity(org.bukkit.entity.Arrow.class); when(restoredArrow.getShooter()).thenReturn(a.player);
|
||||
restoredArrow.getPersistentDataContainer().readFromBytes(arrow.getPersistentDataContainer().serializeToBytes(), true);
|
||||
var poison = new org.bukkit.potion.PotionEffect(org.bukkit.potion.PotionEffectType.POISON, 200, 0);
|
||||
apply(f, b, null, poison, a.player);
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
f.plugin.setEnabled(false); f.awaitWorkers();
|
||||
b.core.pdc.readFromBytes(b.core.pdc.serializeToBytes(), true);
|
||||
f.plugin.setEnabled(true);
|
||||
assertTrue(PartyLifecycleNativeTest.parties(f).partyOf(a.core.id).isEmpty());
|
||||
assertTrue(hit(f, restoredArrow, b.player).isCancelled());
|
||||
assertTrue(tickDamage(f, b, DamageCause.POISON).isCancelled());
|
||||
assertFalse(hit(f, a.player, b.player).isCancelled());
|
||||
assertFalse(tickDamage(f, b, DamageCause.LAVA).isCancelled());
|
||||
// Malformed plugin-owned provenance cannot confer immunity or erase other namespaces.
|
||||
var key = b.core.pdc.getKeys().stream().filter(k -> k.getKey().startsWith("combat_dot_")).findFirst().orElseThrow();
|
||||
var other = new org.bukkit.NamespacedKey("other", "state");
|
||||
b.core.pdc.set(other, org.bukkit.persistence.PersistentDataType.STRING, "preserved");
|
||||
b.core.pdc.set(key, org.bukkit.persistence.PersistentDataType.STRING, "malformed");
|
||||
assertFalse(tickDamage(f, b, DamageCause.POISON).isCancelled());
|
||||
assertFalse(b.core.pdc.has(key));
|
||||
assertEquals("preserved", b.core.pdc.get(other, org.bukkit.persistence.PersistentDataType.STRING));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void weakerHiddenEffectsAndInfiniteDurationsMatchNativeReplacementSemantics() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = actor(f); var b = actor(f); f.activate(a); f.activate(b);
|
||||
var type = org.bukkit.potion.PotionEffectType.WITHER;
|
||||
var strong = new org.bukkit.potion.PotionEffect(type, 40, 2);
|
||||
apply(f, b, null, strong, null);
|
||||
var weaker = new org.bukkit.potion.PotionEffect(type, -1, 0);
|
||||
var hidden = new org.bukkit.event.entity.EntityPotionEffectEvent(b.player, strong, weaker, a.player,
|
||||
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_SPLASH,
|
||||
org.bukkit.event.entity.EntityPotionEffectEvent.Action.CHANGED, false);
|
||||
f.dispatcher.accept(hidden); assertFalse(hidden.isCancelled());
|
||||
var nativeEffect = effects.get(b.player).get(type);
|
||||
nativeEffect.update(new net.minecraft.world.effect.MobEffectInstance(
|
||||
org.bukkit.craftbukkit.potion.CraftPotionEffectType.bukkitToMinecraftHolder(type), -1, 0));
|
||||
createAndInvite(f, a, b); accept(f, b);
|
||||
assertFalse(tickDamage(f, b, DamageCause.WITHER).isCancelled());
|
||||
effects.get(b.player).put(type, nativeEffect.hiddenEffect);
|
||||
assertTrue(tickDamage(f, b, DamageCause.WITHER).isCancelled());
|
||||
// An infinite active effect is not replaced by a shorter same-strength application.
|
||||
assertFalse(apply(f, b, weaker, new org.bukkit.potion.PotionEffect(type, 20, 0), null).isCancelled());
|
||||
assertTrue(tickDamage(f, b, DamageCause.WITHER).isCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
static org.bukkit.event.entity.EntityPotionEffectEvent apply(FantasyStickLifecycleNativeTest.Fixture f,
|
||||
FantasyStickLifecycleNativeTest.Actor target, org.bukkit.potion.PotionEffect old,
|
||||
org.bukkit.potion.PotionEffect effect, Entity source) {
|
||||
var event = new org.bukkit.event.entity.EntityPotionEffectEvent(target.player, old, effect, source,
|
||||
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_SPLASH,
|
||||
old == null ? org.bukkit.event.entity.EntityPotionEffectEvent.Action.ADDED : org.bukkit.event.entity.EntityPotionEffectEvent.Action.CHANGED, true);
|
||||
f.dispatcher.accept(event);
|
||||
if (!event.isCancelled()) {
|
||||
var nativeEffect = new net.minecraft.world.effect.MobEffectInstance(
|
||||
org.bukkit.craftbukkit.potion.CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()), effect.getDuration(), effect.getAmplifier());
|
||||
var current = effects.get(target.player).get(effect.getType());
|
||||
if (current == null) effects.get(target.player).put(effect.getType(), nativeEffect);
|
||||
else if (event.isOverride() || current.getAmplifier() > nativeEffect.getAmplifier()
|
||||
&& current.isShorterDurationThan(nativeEffect)) current.update(nativeEffect);
|
||||
}
|
||||
return event;
|
||||
}
|
||||
static org.bukkit.event.entity.EntityDamageEvent tickDamage(FantasyStickLifecycleNativeTest.Fixture f,
|
||||
FantasyStickLifecycleNativeTest.Actor target, DamageCause cause) {
|
||||
var event = new org.bukkit.event.entity.EntityDamageEvent(target.player, cause, mock(DamageSource.class), 1);
|
||||
f.dispatcher.accept(event); return event;
|
||||
}
|
||||
|
||||
static org.bukkit.entity.Arrow projectile(FantasyStickLifecycleNativeTest.Fixture f, org.bukkit.entity.Player owner) {
|
||||
var arrow = entity(org.bukkit.entity.Arrow.class);
|
||||
when(arrow.getShooter()).thenReturn(owner);
|
||||
f.dispatcher.accept(new org.bukkit.event.entity.ProjectileLaunchEvent(arrow));
|
||||
return arrow;
|
||||
}
|
||||
static <T extends Entity> T entity(Class<T> type) {
|
||||
var entity = mock(type);
|
||||
when(entity.getUniqueId()).thenReturn(java.util.UUID.randomUUID());
|
||||
when(entity.getPersistentDataContainer()).thenReturn(new org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer(
|
||||
new org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
static void exit(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor a) throws Exception {
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
PartyBookNativeTest.drain(f); // Health acknowledgment precedes clearing the equipment receipt.
|
||||
f.receipts().find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private FantasyStickLifecycleNativeTest.Actor actor(FantasyStickLifecycleNativeTest.Fixture f) throws Exception {
|
||||
var a = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(a.core.id, a.player);
|
||||
var active = new java.util.HashMap<org.bukkit.potion.PotionEffectType, net.minecraft.world.effect.MobEffectInstance>();
|
||||
effects.put(a.player, active); fires.put(a.player, 0);
|
||||
doAnswer(call -> {
|
||||
var effect = active.get(call.getArgument(0));
|
||||
return effect == null ? null : new org.bukkit.potion.PotionEffect(call.getArgument(0), effect.getDuration(), effect.getAmplifier());
|
||||
}).when(a.player).getPotionEffect(any());
|
||||
doAnswer(call -> fires.get(a.player)).when(a.player).getFireTicks();
|
||||
return a;
|
||||
}
|
||||
static void createAndInvite(FantasyStickLifecycleNativeTest.Fixture f,
|
||||
FantasyStickLifecycleNativeTest.Actor a, FantasyStickLifecycleNativeTest.Actor b) throws Exception {
|
||||
PartyBookNativeTest.open(f, a); action(f, a, "Create party"); invite(f, a);
|
||||
}
|
||||
static void invite(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor a) throws Exception {
|
||||
PartyBookNativeTest.open(f, a); action(f, a, "Invite players"); action(f, a, "Invite");
|
||||
}
|
||||
static void accept(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor b) throws Exception {
|
||||
PartyBookNativeTest.open(f, b); action(f, b, "Invitations"); action(f, b, "Accept");
|
||||
}
|
||||
static void action(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor a, String label) throws Exception {
|
||||
PartyBookNativeTest.click(f, a, PartyBookNativeTest.button(a, "[" + label + "]"));
|
||||
PartyBookNativeTest.drain(f);
|
||||
}
|
||||
static EntityDamageByEntityEvent hit(FantasyStickLifecycleNativeTest.Fixture f, Entity source, Entity target) {
|
||||
var damage = mock(DamageSource.class);
|
||||
when(damage.getCausingEntity()).thenReturn(source);
|
||||
when(damage.getDirectEntity()).thenReturn(source);
|
||||
var event = new EntityDamageByEntityEvent(source, target, DamageCause.ENTITY_ATTACK, damage, 4);
|
||||
f.dispatcher.accept(event);
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.party.PartyRoster;
|
||||
import java.nio.file.Path;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Packaged plugin startup and registered native lifecycle events; not proof of book/effect controls. */
|
||||
class PartyLifecycleNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void registeredQuitHandlesLastMemberEvenWhileNativeOnlineFlagIsStillTrue() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
var parties = parties(f);
|
||||
var party = parties.create(leader.core.id).orElseThrow();
|
||||
assertTrue(parties.accept(member.core.id, parties.invite(leader.core.id, party.id(), member.core.id).orElseThrow().id()));
|
||||
f.dispatcher.accept(new PlayerQuitEvent(leader.player, Component.empty()));
|
||||
leader.core.online = false;
|
||||
assertEquals(leader.core.id, parties.partyOf(member.core.id).orElseThrow().leader());
|
||||
f.dispatcher.accept(new PlayerQuitEvent(member.player, Component.empty()));
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
assertTrue(parties.partyOf(leader.core.id).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void disablingAndReenablingDisbandsAndCannotReuseOldInvitationsOrServices() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
var old = parties(f);
|
||||
var party = old.create(leader.core.id).orElseThrow();
|
||||
var invitation = old.invite(leader.core.id, party.id(), member.core.id).orElseThrow();
|
||||
f.plugin.setEnabled(false); f.awaitWorkers();
|
||||
assertTrue(old.partyOf(leader.core.id).isEmpty());
|
||||
assertFalse(old.accept(member.core.id, invitation.id()));
|
||||
assertTrue(old.create(leader.core.id).isEmpty());
|
||||
f.plugin.setEnabled(true);
|
||||
var fresh = parties(f);
|
||||
assertNotSame(old, fresh);
|
||||
assertTrue(fresh.partyOf(leader.core.id).isEmpty());
|
||||
assertFalse(fresh.accept(member.core.id, invitation.id()));
|
||||
assertNotEquals(party.id(), fresh.create(leader.core.id).orElseThrow().id());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void consecutiveQuitEventsAreAuthoritativeEvenIfBothOnlineFlagsLag() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
var parties = parties(f);
|
||||
var party = parties.create(leader.core.id).orElseThrow();
|
||||
assertTrue(parties.accept(member.core.id, parties.invite(leader.core.id, party.id(), member.core.id).orElseThrow().id()));
|
||||
f.dispatcher.accept(new PlayerQuitEvent(leader.player, Component.empty()));
|
||||
assertEquals(leader.core.id, parties.partyOf(member.core.id).orElseThrow().leader());
|
||||
f.dispatcher.accept(new PlayerQuitEvent(member.player, Component.empty()));
|
||||
assertTrue(parties.partyOf(leader.core.id).isEmpty());
|
||||
assertTrue(parties.partyOf(member.core.id).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void rejoiningBeforeTheOtherMemberQuitsRetainsTheSamePartyAndLeader() throws Exception {
|
||||
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var leader = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var member = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
f.players.put(leader.core.id, leader.player); f.players.put(member.core.id, member.player);
|
||||
var parties = parties(f);
|
||||
var party = parties.create(leader.core.id).orElseThrow();
|
||||
assertTrue(parties.accept(member.core.id, parties.invite(leader.core.id, party.id(), member.core.id).orElseThrow().id()));
|
||||
f.dispatcher.accept(new PlayerQuitEvent(leader.player, Component.empty()));
|
||||
f.dispatcher.accept(new org.bukkit.event.player.PlayerJoinEvent(leader.player, Component.empty()));
|
||||
f.dispatcher.accept(new PlayerQuitEvent(member.player, Component.empty()));
|
||||
assertEquals(party.id(), parties.partyOf(leader.core.id).orElseThrow().id());
|
||||
assertEquals(leader.core.id, parties.partyOf(leader.core.id).orElseThrow().leader());
|
||||
}
|
||||
}
|
||||
|
||||
static PartyRoster parties(FantasyStickLifecycleNativeTest.Fixture f) {
|
||||
return (PartyRoster) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "parties");
|
||||
}
|
||||
}
|
||||
@@ -179,6 +179,88 @@ class PlayerSheetDropsNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceStacksKeepIdentityAndUseOneDetachedEntityAtNativeCapacity() {
|
||||
for (int amount : new int[]{1, 3, 64, 2}) {
|
||||
var fixture = new WorldFixture();
|
||||
var references = sheet();
|
||||
if (amount == 2) {
|
||||
var meta = references.getItemMeta(); meta.setMaxStackSize(2); references.setItemMeta(meta);
|
||||
}
|
||||
references.setAmount(amount);
|
||||
var before = references.clone();
|
||||
var identity = new CharacterSheets().identify(references).orElseThrow();
|
||||
var events = new AtomicInteger();
|
||||
var drops = new PlayerSheetDrops(fixture.player, event -> {
|
||||
events.incrementAndGet();
|
||||
assertEquals(before, event.getItemDrop().getItemStack());
|
||||
assertFalse(event.getItemDrop().isInWorld());
|
||||
assertEquals(0, fixture.spawnCalls);
|
||||
});
|
||||
assertEquals(Status.COMPLETE, drops.dropReferences(references, () -> true));
|
||||
assertEquals(before, references, "Adapter never debits its caller's source");
|
||||
assertEquals(before, fixture.stack);
|
||||
assertEquals(identity, new CharacterSheets().identify(fixture.stack).orElseThrow());
|
||||
assertEquals(1, events.get()); assertEquals(1, fixture.creates);
|
||||
assertEquals(1, fixture.spawnCalls); assertEquals(1, fixture.spawnEvents);
|
||||
assertEquals(40, fixture.pickupDelay); assertEquals(fixture.playerId, fixture.thrower);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceStackValidationPrecedesAllCallbacksAndCraftContractStaysSingle() {
|
||||
var oversized = sheet(); oversized.setAmount(oversized.getMaxStackSize() + 1);
|
||||
var limited = sheet(); var meta = limited.getItemMeta(); meta.setMaxStackSize(2); limited.setItemMeta(meta); limited.setAmount(3);
|
||||
var empty = sheet(); empty.setAmount(0);
|
||||
var negative = sheet(); negative.setAmount(-1);
|
||||
for (var invalid : java.util.Arrays.asList(null, new ItemStack(org.bukkit.Material.PAPER),
|
||||
new ItemStack(org.bukkit.Material.DIAMOND), empty, negative, oversized, limited)) {
|
||||
var fixture = new WorldFixture();
|
||||
var drops = new PlayerSheetDrops(fixture.player, event -> fail("Invalid references reached the public callback"));
|
||||
assertThrows(IllegalArgumentException.class, () -> drops.dropReferences(invalid, () -> {
|
||||
fail("Validate before even consulting context"); return true;
|
||||
}));
|
||||
assertEquals(0, fixture.creates); assertEquals(0, fixture.spawnCalls);
|
||||
}
|
||||
var fixture = new WorldFixture();
|
||||
games.dmg.fantasystick.crafting.ManualDropDelivery.DropTarget strict = new PlayerSheetDrops(fixture.player,
|
||||
event -> fail("Crafting DropTarget must remain exactly one sheet"));
|
||||
var references = sheet(); references.setAmount(3);
|
||||
assertThrows(IllegalArgumentException.class, () -> strict.drop(references, () -> {
|
||||
fail("Reject multiple crafting sheets before any callback"); return true;
|
||||
}));
|
||||
assertEquals(0, fixture.creates);
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceStacksRetainSingleSheetStalenessAndUncertaintySemantics() {
|
||||
for (int scenario = 0; scenario < 9; scenario++) {
|
||||
var fixture = new WorldFixture(); var references = sheet(); references.setAmount(3);
|
||||
var before = references.clone();
|
||||
var current = new java.util.concurrent.atomic.AtomicBoolean(scenario != 0);
|
||||
var events = new AtomicInteger();
|
||||
int change = scenario;
|
||||
var drops = new PlayerSheetDrops(fixture.player, event -> {
|
||||
events.incrementAndGet();
|
||||
if (change == 1) event.setCancelled(true);
|
||||
if (change == 2) current.set(false);
|
||||
if (change == 3) fixture.stack.setAmount(1);
|
||||
if (change == 4) fixture.removed = true;
|
||||
if (change == 5) { fixture.inWorld = true; event.setCancelled(true); }
|
||||
});
|
||||
if (scenario == 6) fixture.onSpawn = event -> event.setCancelled(true);
|
||||
if (scenario == 7) fixture.onAdded = () -> fixture.stack.setAmount(1);
|
||||
if (scenario == 8) fixture.onAdded = () -> fixture.removed = true;
|
||||
assertEquals(scenario == 0 || scenario == 2 ? Status.STALE : scenario == 1 ? Status.CANCELLED : Status.UNCONFIRMED,
|
||||
drops.dropReferences(references, current::get), "Scenario " + scenario);
|
||||
assertEquals(before, references);
|
||||
assertEquals(scenario == 0 ? 0 : 1, events.get());
|
||||
assertEquals(scenario >= 6 ? 1 : 0, fixture.spawnCalls);
|
||||
assertEquals(scenario >= 6 ? 1 : 0, fixture.spawnEvents);
|
||||
if (scenario != 0) assertEquals(new CharacterSheets().identify(before), new CharacterSheets().identify(fixture.stack));
|
||||
}
|
||||
}
|
||||
|
||||
private static ItemStack sheet() {
|
||||
return new CharacterSheets().create(new CharacterFactory().create(ProgressionRules.defaults()));
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,252 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.items.SessionControls;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.function.Consumer;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.minecraft.nbt.NbtOps;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.craftbukkit.CraftRegistry;
|
||||
import org.bukkit.craftbukkit.inventory.CraftItemStack;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SessionControlsNativeTest {
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
private final SessionControls controls = new SessionControls();
|
||||
private final UUID owner = UUID.randomUUID();
|
||||
private final UUID session = UUID.randomUUID();
|
||||
|
||||
@Test
|
||||
void defaultHotbarHasNineDistinctSingleControlsWithNativeCodecIdentity() {
|
||||
var items = controls.create(character(Collections.nCopies(7, "")), owner, session);
|
||||
assertEquals(9, items.length);
|
||||
for (int slot = 0; slot < 9; slot++) {
|
||||
var item = items[slot];
|
||||
assertEquals(slot == 0 ? Material.BOOK : slot == 1 ? Material.STICK : Material.GRAY_DYE, item.getType());
|
||||
assertEquals(Component.text(slot == 0 ? "Character book" : slot == 1 ? "Basic attack" : "No Ability"),
|
||||
item.getItemMeta().displayName());
|
||||
assertEquals(1, item.getAmount());
|
||||
assertEquals(1, item.getMaxStackSize());
|
||||
var expected = new SessionControls.Identity(owner, session, slot);
|
||||
assertEquals(expected, controls.identify(item).orElseThrow());
|
||||
assertTrue(controls.owned(item, owner, session));
|
||||
var reloaded = roundTrip(item);
|
||||
assertEquals(item, reloaded);
|
||||
assertEquals(expected, controls.identify(reloaded).orElseThrow());
|
||||
for (int other = 0; other < slot; other++) {
|
||||
assertNotSame(items[other], item);
|
||||
assertFalse(items[other].isSimilar(item), "Slot identity must distinguish even empty controls");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyApprovedSavedAbilityUsesItsOwnStableIdAndCataloguePresentation() {
|
||||
var ids = List.of("fireball", "great_sword", "frost_shard", "longbow", "quickstep", "second_wind",
|
||||
"stone_skin", "shield_bash", "hex", "inspire", "mending_light", "purify", "guardian_bond",
|
||||
"rallying_cry", "frost_nova", "chain_lightning", "sanctuary", "war_banner", "meteor", "revive");
|
||||
var names = List.of("Fireball", "Great Sword", "Frost Shard", "Longbow", "Quickstep", "Second Wind",
|
||||
"Stone Skin", "Shield Bash", "Hex", "Inspire", "Mending Light", "Purify", "Guardian Bond",
|
||||
"Rallying Cry", "Frost Nova", "Chain Lightning", "Sanctuary", "War Banner", "Meteor", "Revive");
|
||||
var materials = List.of(Material.SNOWBALL, Material.WOODEN_SWORD, Material.PRISMARINE_SHARD,
|
||||
Material.BOW, Material.RABBIT_FOOT, Material.GHAST_TEAR, Material.BRICK, Material.SHIELD,
|
||||
Material.SPIDER_EYE, Material.AMETHYST_SHARD, Material.GHAST_TEAR, Material.HONEY_BOTTLE,
|
||||
Material.IRON_CHESTPLATE, Material.GOAT_HORN, Material.SNOWBALL, Material.LIGHTNING_ROD,
|
||||
Material.SEA_LANTERN, Material.RED_BANNER, Material.FIRE_CHARGE, Material.ECHO_SHARD);
|
||||
for (int index = 0; index < ids.size(); index++) {
|
||||
var loadout = new ArrayList<>(Collections.nCopies(7, ""));
|
||||
int abilitySlot = index % 7;
|
||||
loadout.set(abilitySlot, ids.get(index));
|
||||
var items = controls.create(character(loadout), owner, session);
|
||||
var item = roundTrip(items[abilitySlot + 2]);
|
||||
assertEquals(materials.get(index), item.getType(), ids.get(index));
|
||||
assertEquals(Component.text(names.get(index)), item.getItemMeta().displayName());
|
||||
assertEquals(ids.get(index), item.getItemMeta().getPersistentDataContainer()
|
||||
.get(key("control_ability_id"), PersistentDataType.STRING));
|
||||
assertEquals(1, item.getAmount());
|
||||
assertEquals(1, item.getMaxStackSize());
|
||||
assertEquals(java.util.Optional.of(new SessionControls.Identity(owner, session, abilitySlot + 2)),
|
||||
controls.identify(item), ids.get(index));
|
||||
for (int slot = 2; slot < 9; slot++) {
|
||||
if (slot != abilitySlot + 2) assertEquals(Material.GRAY_DYE, items[slot].getType());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownSavedAbilitiesRemainUnavailableWithoutChangingTheRecordOrCallerLoadout() {
|
||||
var loadout = new ArrayList<>(List.of("fireball", "removed_spell", "", "revive", "", "", ""));
|
||||
var originalLoadout = List.copyOf(loadout);
|
||||
var record = character(loadout);
|
||||
var before = new CharacterRecord(record.id(), record.name(), record.revision(), record.stats(), record.level(),
|
||||
record.experience(), record.unspentPoints(), record.health(), record.learned(), record.loadout(),
|
||||
record.cooldowns(), record.dead(), record.deathId(), record.diedAt());
|
||||
var first = controls.create(record, owner, session);
|
||||
var second = controls.create(record, owner, session);
|
||||
var unknown = roundTrip(first[3]);
|
||||
assertEquals(Material.PAPER, unknown.getType());
|
||||
assertEquals(Component.text("Unavailable ability: removed_spell"), unknown.getItemMeta().displayName());
|
||||
var data = unknown.getItemMeta().getPersistentDataContainer();
|
||||
assertEquals("unavailable", data.get(key("control_kind"), PersistentDataType.STRING));
|
||||
assertEquals("removed_spell", data.get(key("control_ability_id"), PersistentDataType.STRING));
|
||||
assertEquals(new SessionControls.Identity(owner, session, 3), controls.identify(unknown).orElseThrow());
|
||||
assertEquals(1, unknown.getMaxStackSize());
|
||||
assertNotSame(first, second);
|
||||
for (int slot = 0; slot < 9; slot++) assertNotSame(first[slot], second[slot]);
|
||||
first[3].setAmount(2);
|
||||
assertEquals(1, second[3].getAmount());
|
||||
assertEquals(before, record, "Factory must not grant stats/abilities or rewrite saved state");
|
||||
assertEquals(originalLoadout, loadout);
|
||||
assertEquals(originalLoadout, record.loadout());
|
||||
assertThrows(NullPointerException.class, () -> controls.create(record, null, session));
|
||||
assertThrows(NullPointerException.class, () -> controls.create(record, owner, null));
|
||||
assertThrows(NullPointerException.class, () -> controls.create(null, owner, session));
|
||||
assertEquals(before, record);
|
||||
}
|
||||
|
||||
@Test
|
||||
void identitySurvivesRenamingButNeverMatchesAnotherOwnerOrSession() {
|
||||
var record = character(List.of("fireball", "frost_nova", "second_wind", "mending_light", "revive", "removed_spell", ""));
|
||||
var items = controls.create(record, owner, session);
|
||||
var otherOwner = UUID.randomUUID();
|
||||
var otherSession = UUID.randomUUID();
|
||||
var transferred = controls.create(record, otherOwner, otherSession);
|
||||
for (int slot = 0; slot < 9; slot++) {
|
||||
var meta = items[slot].getItemMeta();
|
||||
meta.displayName(Component.text("Renamed presentation"));
|
||||
meta.lore(List.of(Component.text("Not identity")));
|
||||
items[slot].setItemMeta(meta);
|
||||
assertEquals(new SessionControls.Identity(owner, session, slot), controls.identify(roundTrip(items[slot])).orElseThrow());
|
||||
assertTrue(controls.owned(items[slot], owner, session));
|
||||
assertFalse(controls.owned(items[slot], otherOwner, session));
|
||||
assertFalse(controls.owned(items[slot], owner, otherSession));
|
||||
assertFalse(controls.owned(items[slot], null, session));
|
||||
assertFalse(controls.owned(items[slot], owner, null));
|
||||
assertEquals(new SessionControls.Identity(otherOwner, otherSession, slot), controls.identify(transferred[slot]).orElseThrow());
|
||||
assertFalse(controls.owned(transferred[slot], owner, session));
|
||||
}
|
||||
// The same material in the same slot still needs distinct stable ability IDs.
|
||||
var fireball = controls.create(character(Collections.nCopies(7, "fireball")), owner, session)[2];
|
||||
var nova = controls.create(character(Collections.nCopies(7, "frost_nova")), owner, session)[2];
|
||||
assertFalse(fireball.isSimilar(nova));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameOnlyLookalikesWrongMaterialsQuantitiesAndStackLimitsAreRefused() {
|
||||
assertRejected(null);
|
||||
assertRejected(new ItemStack(Material.AIR));
|
||||
var items = controls.create(character(List.of("fireball", "great_sword", "purify", "guardian_bond", "revive", "removed_spell", "")), owner, session);
|
||||
for (var item : items) {
|
||||
var fake = new ItemStack(item.getType());
|
||||
var meta = fake.getItemMeta();
|
||||
meta.displayName(item.getItemMeta().displayName());
|
||||
meta.setMaxStackSize(1);
|
||||
fake.setItemMeta(meta);
|
||||
assertRejected(fake);
|
||||
for (int amount : new int[]{0, -1, 2, 64}) {
|
||||
var wrongAmount = item.clone();
|
||||
wrongAmount.setAmount(amount);
|
||||
assertRejected(wrongAmount);
|
||||
}
|
||||
var wrongMaterial = new ItemStack(Material.DIRT);
|
||||
wrongMaterial.setItemMeta(item.getItemMeta());
|
||||
assertRejected(wrongMaterial);
|
||||
}
|
||||
for (Integer limit : new Integer[]{null, 2}) {
|
||||
var wrongLimit = items[0].clone();
|
||||
var meta = wrongLimit.getItemMeta();
|
||||
meta.setMaxStackSize(limit);
|
||||
wrongLimit.setItemMeta(meta);
|
||||
assertRejected(wrongLimit);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedFutureNoncanonicalAndInconsistentPdcCannotIdentifyAControl() {
|
||||
var items = controls.create(character(List.of("fireball", "removed_spell", "", "", "", "", "")), owner, session);
|
||||
var invalid = new LinkedHashMap<String, ItemStack>();
|
||||
for (String field : List.of("control_version", "control_owner_id", "control_session_id", "control_slot", "control_kind", "control_ability_id")) {
|
||||
invalid.put("missing " + field, tamper(items[2], data -> data.remove(key(field))));
|
||||
invalid.put("wrong type " + field, tamper(items[2], data -> data.set(key(field), PersistentDataType.BYTE_ARRAY, new byte[]{1})));
|
||||
}
|
||||
for (int version : new int[]{-1, 0, 2, Integer.MAX_VALUE}) {
|
||||
invalid.put("version " + version, tamper(items[2], data -> data.set(key("control_version"), PersistentDataType.INTEGER, version)));
|
||||
}
|
||||
for (String field : List.of("control_owner_id", "control_session_id")) {
|
||||
for (String value : List.of("", "not-a-uuid", "1-1-1-1-1", " " + owner,
|
||||
"abcdefab-cdef-abcd-efab-cdefabcdefab".toUpperCase(Locale.ROOT), owner + "\n")) {
|
||||
invalid.put(field + ": " + value, tamper(items[2], data -> data.set(key(field), PersistentDataType.STRING, value)));
|
||||
}
|
||||
}
|
||||
for (int slot : new int[]{-1, 0, 1, 9, Integer.MAX_VALUE}) {
|
||||
invalid.put("ability slot " + slot, tamper(items[2], data -> data.set(key("control_slot"), PersistentDataType.INTEGER, slot)));
|
||||
}
|
||||
for (String kind : List.of("", "book", "basic_attack", "empty", "unavailable", "future")) {
|
||||
invalid.put("ability kind " + kind, tamper(items[2], data -> data.set(key("control_kind"), PersistentDataType.STRING, kind)));
|
||||
}
|
||||
for (String ability : List.of("", " ", "FIREBALL", "removed_spell", "revive")) {
|
||||
invalid.put("ability ID " + ability, tamper(items[2], data -> data.set(key("control_ability_id"), PersistentDataType.STRING, ability)));
|
||||
}
|
||||
invalid.put("book in basic slot", tamper(items[0], data -> data.set(key("control_slot"), PersistentDataType.INTEGER, 1)));
|
||||
invalid.put("basic in book slot", tamper(items[1], data -> data.set(key("control_slot"), PersistentDataType.INTEGER, 0)));
|
||||
invalid.put("book ability tag", tamper(items[0], data -> data.set(key("control_ability_id"), PersistentDataType.STRING, "fireball")));
|
||||
invalid.put("empty ability tag", tamper(items[4], data -> data.set(key("control_ability_id"), PersistentDataType.STRING, "")));
|
||||
invalid.put("unavailable known ability", tamper(items[3], data -> data.set(key("control_ability_id"), PersistentDataType.STRING, "fireball")));
|
||||
invalid.put("unavailable blank ability", tamper(items[3], data -> data.set(key("control_ability_id"), PersistentDataType.STRING, " ")));
|
||||
assertAll(invalid.entrySet().stream().map(entry -> () -> {
|
||||
assertTrue(controls.identify(entry.getValue()).isEmpty(), entry.getKey());
|
||||
assertFalse(controls.owned(entry.getValue(), owner, session), entry.getKey());
|
||||
}));
|
||||
}
|
||||
|
||||
private void assertRejected(ItemStack item) {
|
||||
assertTrue(controls.identify(item).isEmpty());
|
||||
assertFalse(controls.owned(item, owner, session));
|
||||
}
|
||||
|
||||
private static ItemStack tamper(ItemStack original, Consumer<PersistentDataContainer> mutation) {
|
||||
var copy = original.clone();
|
||||
var meta = copy.getItemMeta();
|
||||
mutation.accept(meta.getPersistentDataContainer());
|
||||
copy.setItemMeta(meta);
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static NamespacedKey key(String name) { return new NamespacedKey("fantasystick", name); }
|
||||
|
||||
private static CharacterRecord character(List<String> loadout) {
|
||||
var stats = new EnumMap<Stat, BigInteger>(Stat.class);
|
||||
for (Stat stat : Stat.values()) stats.put(stat, BigInteger.ZERO);
|
||||
return new CharacterRecord(UUID.randomUUID(), "Ari of Ash", BigInteger.ZERO, stats, 1,
|
||||
BigInteger.ZERO, BigInteger.valueOf(40), BigDecimal.TEN,
|
||||
loadout.stream().filter(id -> !id.isEmpty()).collect(Collectors.toSet()), loadout,
|
||||
Map.of(), false, null, null);
|
||||
}
|
||||
|
||||
private static ItemStack roundTrip(ItemStack item) {
|
||||
var ops = RegistryOps.create(NbtOps.INSTANCE, CraftRegistry.getMinecraftRegistry());
|
||||
var encoded = net.minecraft.world.item.ItemStack.CODEC.encodeStart(ops, CraftItemStack.asNMSCopy(item)).getOrThrow();
|
||||
return CraftItemStack.asBukkitCopy(net.minecraft.world.item.ItemStack.CODEC.parse(ops, encoded).getOrThrow());
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,86 @@ class TailBooksNativeTest {
|
||||
assertTrue(meta.getTitle().length() <= 32);
|
||||
assertFalse(Character.isHighSurrogate(meta.getTitle().charAt(meta.getTitle().length() - 1)));
|
||||
assertEquals(Component.text("Tail of " + name), meta.displayName());
|
||||
assertTrue(meta.pages().contains(Component.text("Tail of " + name)));
|
||||
String text = meta.pages().stream().map(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText()::serialize)
|
||||
.collect(java.util.stream.Collectors.joining()).replace("\n", "");
|
||||
assertTrue(text.contains("Tail of " + name), "Readable wrapping must retain every character of the full name");
|
||||
}
|
||||
|
||||
@Test void giantStatsRemainReadableInOneSignedKeepsakeThroughTheActualNativeCodec() {
|
||||
var old = fallen();
|
||||
var stats = new EnumMap<Stat, BigInteger>(Stat.class); stats.putAll(old.stats());
|
||||
String digits = "1234567890".repeat(4000);
|
||||
stats.put(Stat.STR, new BigInteger(digits));
|
||||
var saved = new CharacterRecord(old.id(), "雪🐈".repeat(80), old.revision(), stats, old.level(), old.experience(),
|
||||
old.unspentPoints(), old.health(), old.learned(), old.loadout(), old.cooldowns(), true, old.deathId(), old.diedAt());
|
||||
var book = new TailBooks().create(saved);
|
||||
var ops = RegistryOps.create(NbtOps.INSTANCE, CraftRegistry.getMinecraftRegistry());
|
||||
var encoded = net.minecraft.world.item.ItemStack.CODEC.encodeStart(ops, CraftItemStack.asNMSCopy(book)).getOrThrow();
|
||||
var decoded = net.minecraft.world.item.ItemStack.CODEC.parse(ops, encoded).getOrThrow();
|
||||
var content = decoded.get(DataComponents.WRITTEN_BOOK_CONTENT); assertNotNull(content);
|
||||
assertTrue(content.pages().size() > 100, "Signed books are not subject to the writable-book 100-page cap");
|
||||
var text = new StringBuilder();
|
||||
for (var page : content.pages()) {
|
||||
String value = page.raw().getString();
|
||||
assertTrue(value.split("\\n", -1).length <= 13);
|
||||
for (String line : value.split("\\n", -1)) assertTrue(line.codePoints().map(cp -> cp < 128 ? 6 : 9).sum() <= 108);
|
||||
text.append(value.replace("\n", ""));
|
||||
}
|
||||
assertTrue(text.toString().contains(saved.name())); assertTrue(text.toString().contains(digits));
|
||||
assertEquals(1, book.getAmount());
|
||||
assertEquals(new TailBooks.Identity(saved.id(), saved.deathId()), new TailBooks().identify(CraftItemStack.asBukkitCopy(decoded)).orElseThrow());
|
||||
}
|
||||
|
||||
@Test void ordinaryStatsShareOneSummaryAndEachSavedAbilityHasItsOwnReadableSection() {
|
||||
var old = fallen();
|
||||
var expiry = old.diedAt().plusSeconds(3600);
|
||||
var saved = new CharacterRecord(old.id(), old.name(), old.revision(), old.stats(), old.level(), old.experience(),
|
||||
old.unspentPoints(), old.health(), Set.of("second_wind", "unknown:雪"),
|
||||
List.of("second_wind", "unknown:雪", "second_wind", "", "", "", ""),
|
||||
Map.of("second_wind", expiry, "retired_ability", expiry.plusSeconds(60)), true, old.deathId(), old.diedAt());
|
||||
var book = new TailBooks().create(saved);
|
||||
var pages = nativePages(book);
|
||||
String summary = pages.getFirst().replace("\n", "");
|
||||
for (String expected : List.of("Tail of Ari", "Level: 2", "XP: 100", "Unspent points: 30",
|
||||
"STR: 0", "DEX: 0", "CON: 10", "INT: 0", "WIS: 0", "CHR: 0")) assertTrue(summary.contains(expected), expected);
|
||||
String wind = pages.stream().map(p -> p.replace("\n", "")).filter(p -> p.contains("Ability: second_wind")).findFirst().orElseThrow();
|
||||
assertTrue(wind.contains("Slots: 1, 3")); assertTrue(wind.contains(expiry.toString()));
|
||||
assertFalse(wind.contains("unknown:雪"), "Each learned ability starts its own page/section");
|
||||
String unknown = pages.stream().map(p -> p.replace("\n", "")).filter(p -> p.contains("Ability: unknown:雪")).findFirst().orElseThrow();
|
||||
assertTrue(unknown.contains("Slots: 2")); assertTrue(unknown.contains("Cooldown: none"));
|
||||
String all = String.join("", pages).replace("\n", "");
|
||||
assertTrue(all.contains("Saved cooldown")); assertTrue(all.contains("retired_ability"));
|
||||
assertTrue(all.contains(expiry.plusSeconds(60).toString())); assertTrue(all.contains(old.diedAt().toString()));
|
||||
assertEquals(new TailBooks.Identity(saved.id(), saved.deathId()), new TailBooks().identify(book).orElseThrow());
|
||||
}
|
||||
|
||||
@Test void emptyAbilitiesAreExplicitAndLongUnknownAbilityPagesRetainEveryCodePoint() {
|
||||
var old = fallen();
|
||||
var empty = new CharacterRecord(old.id(), old.name(), old.revision(), old.stats(), old.level(), old.experience(),
|
||||
old.unspentPoints(), old.health(), Set.of(), List.of("", "", "", "", "", "", ""), Map.of(), true, old.deathId(), old.diedAt());
|
||||
var legacyBook = new TailBooks().create(empty);
|
||||
var original = legacyBook.clone();
|
||||
assertTrue(nativePages(legacyBook).stream().anyMatch(p -> p.replace("\n", "").contains("Abilities: None")));
|
||||
String id = "unknown:雪🐈".repeat(4000);
|
||||
var longAbility = new CharacterRecord(old.id(), old.name(), old.revision(), old.stats(), old.level(), old.experience(),
|
||||
old.unspentPoints(), old.health(), Set.of(id), List.of("", "", "", "", "", "", ""), Map.of(), true, old.deathId(), old.diedAt());
|
||||
var pages = nativePages(new TailBooks().create(longAbility));
|
||||
assertTrue(pages.size() > 100);
|
||||
assertTrue(String.join("", pages).replace("\n", "").contains("Ability: " + id));
|
||||
assertTrue(String.join("", pages).replace("\n", "").contains("Slots: none"));
|
||||
for (String page : pages) {
|
||||
assertTrue(page.split("\n", -1).length <= 13);
|
||||
for (String line : page.split("\n", -1)) assertTrue(line.codePoints().map(cp -> cp < 128 ? 6 : 9).sum() <= 108);
|
||||
}
|
||||
assertEquals(original, legacyBook, "Rendering another record must not rewrite any existing signed keepsake");
|
||||
}
|
||||
|
||||
private static List<String> nativePages(ItemStack book) {
|
||||
var ops = RegistryOps.create(NbtOps.INSTANCE, CraftRegistry.getMinecraftRegistry());
|
||||
var encoded = net.minecraft.world.item.ItemStack.CODEC.encodeStart(ops, CraftItemStack.asNMSCopy(book)).getOrThrow();
|
||||
var decoded = net.minecraft.world.item.ItemStack.CODEC.parse(ops, encoded).getOrThrow();
|
||||
return java.util.Objects.requireNonNull(decoded.get(DataComponents.WRITTEN_BOOK_CONTENT)).pages().stream()
|
||||
.map(p -> p.raw().getString()).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -95,7 +174,7 @@ class TailBooksNativeTest {
|
||||
assertTrue(pages.contains("Level: 2"));
|
||||
assertTrue(pages.contains("XP: 100"));
|
||||
assertTrue(pages.contains("CON: 10"));
|
||||
assertTrue(pages.contains("second_wind"));
|
||||
assertTrue(pages.replace("\n", "").contains("second_wind"), "Labeled ability IDs remain complete across readable line wrapping");
|
||||
assertEquals(new TailBooks.Identity(saved.id(), saved.deathId()), books.identify(CraftItemStack.asBukkitCopy(restored)).orElseThrow());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.items.EquipmentStorage;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Equipment-session composition, not a fantasy health/nutrition engine or live display test. */
|
||||
@SuppressWarnings("try")
|
||||
class WholeCharacterTransferNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void completeCharacterTransfersWhileGearVitalsLocationsDeadlinesAndOrdinaryIdentityStayWithHolders() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Original sheet name");
|
||||
var a = h.holder(record, "AccountA", Material.DIAMOND_SWORD, 13.5, 7, 1.5f, 2.75f);
|
||||
var b = h.holder(record, "AccountB", Material.IRON_AXE, 6.25, 18, 8.5f, 0.25f);
|
||||
a.actor.location = new Location(null, 11, 71, -8, 30, 10);
|
||||
b.actor.location = new Location(null, -90, 65, 123, -45, 20);
|
||||
var aEntry = a.actor.location.clone(); var bEntry = b.actor.location.clone();
|
||||
var aBefore = a.actor.snapshot(); var bBefore = b.actor.snapshot();
|
||||
var aOrdinary = a.ordinary(); var bOrdinary = b.ordinary();
|
||||
// Physical sheets are now stale. Activation must read the complete authoritative YAML record.
|
||||
var current = h.f.characters.renameCharacter(record.id(), "雪 <red>Literal transferred character 🐉")
|
||||
.get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.activate(a);
|
||||
var aSession = h.f.sessions.active(a.actor.id).orElseThrow();
|
||||
assertEquals(current.name(), h.presentation.name(a.actor.id));
|
||||
assertEquals(current.revision(), h.output.shown.getLast().revision());
|
||||
assertEquals(current.id(), h.output.shown.getLast().character());
|
||||
assertEquals(aOrdinary, a.ordinary()); assertEquals(bOrdinary, b.ordinary());
|
||||
assertEquals(current, h.saved(record.id()));
|
||||
a.actor.location = new Location(null, 222, 80, -333);
|
||||
var aExitLocation = a.actor.location.clone();
|
||||
assertEquals(EquipmentStorage.RestoreResult.RESTORED, h.f.sessions.exit(a.player));
|
||||
var aExit = h.f.state(a.actor);
|
||||
assertArrayEquals(aBefore, a.actor.snapshot());
|
||||
assertEquals(aExitLocation, a.actor.location, "Voluntary exit does not use the entry return location");
|
||||
assertEquals(0, a.actor.teleports);
|
||||
assertNull(h.presentation.name(a.actor.id));
|
||||
assertEquals(aSession.session(), h.output.cleared.getLast().session());
|
||||
|
||||
var transferred = a.actor.inventory.getItemInOffHand().clone();
|
||||
a.actor.inventory.setItemInOffHand(null);
|
||||
b.actor.inventory.setItemInOffHand(transferred);
|
||||
h.activate(b);
|
||||
var bSession = h.f.sessions.active(b.actor.id).orElseThrow();
|
||||
assertEquals(current.id(), bSession.character()); assertNotEquals(aSession.session(), bSession.session());
|
||||
assertEquals(current.name(), h.presentation.name(b.actor.id));
|
||||
assertNull(h.presentation.name(a.actor.id));
|
||||
assertNull(h.f.state(b.actor).lastExit(), "A's switch deadline is not a character property");
|
||||
assertEquals(aExit, h.f.state(a.actor));
|
||||
assertEquals(bEntry, b.actor.location); assertNotEquals(aEntry, b.actor.location);
|
||||
assertEquals(aOrdinary, a.ordinary()); assertEquals(bOrdinary, b.ordinary());
|
||||
assertEquals(current, h.saved(record.id()), "Transfer preserves stats, XP, points, health, learned/loadout and cooldowns");
|
||||
assertEquals(current, new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(record.id()).orElseThrow());
|
||||
assertEquals(EquipmentStorage.RestoreResult.RESTORED, h.f.sessions.exit(b.player));
|
||||
assertNull(h.f.state(b.actor).pending());
|
||||
assertArrayEquals(bBefore, b.actor.snapshot(), "B restores B's real native gear, never A's");
|
||||
assertEquals(Material.DIAMOND_SWORD, a.actor.inventory.getItem(0).getType());
|
||||
assertEquals(aOrdinary, a.ordinary()); assertEquals(bOrdinary, b.ordinary());
|
||||
assertEquals(bEntry, b.actor.location); assertEquals(0, b.actor.teleports);
|
||||
assertEquals(aExit, h.f.state(a.actor)); assertEquals(current, h.saved(record.id()));
|
||||
assertTrue(h.presentation.snapshot().isEmpty());
|
||||
assertEquals(List.of(a.actor.id, b.actor.id), h.output.cleared.stream().map(CharacterPresentation.View::holder).toList());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void pendingAndActiveCopiesAreBusyCounterfeitsAndDeadRecordsRefuseButConsumeOnceBackendRevivalEnters() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("One transferable life");
|
||||
var a = h.holder(record); var b = h.holder(record);
|
||||
var beforeB = b.actor.snapshot();
|
||||
h.f.sessions.enter(a.player); var loadA = h.f.next();
|
||||
h.f.sessions.enter(b.player); var loadB = h.f.next();
|
||||
loadA.run(); loadB.run(); // Both reads were pending before either player acquired the character.
|
||||
assertEquals("CHARACTER_BUSY", h.f.notices.getLast().code());
|
||||
assertArrayEquals(beforeB, b.actor.snapshot());
|
||||
assertTrue(h.f.sessions.active(b.actor.id).isEmpty());
|
||||
assertTrue(h.presentation.snapshot().isEmpty(), "No presentation before native activation");
|
||||
h.f.tick();
|
||||
assertTrue(h.f.sessions.active(a.actor.id).isPresent());
|
||||
h.f.sessions.enter(b.player); h.f.tick();
|
||||
assertEquals("CHARACTER_BUSY", h.f.notices.getLast().code());
|
||||
assertArrayEquals(beforeB, b.actor.snapshot()); assertNull(h.presentation.name(b.actor.id));
|
||||
assertEquals(record, h.saved(record.id()));
|
||||
assertTrue(h.f.receipts.find(b.actor.id).toCompletableFuture().get(5, TimeUnit.SECONDS).isEmpty());
|
||||
h.f.sessions.exit(a.player); var exit = h.f.state(a.actor);
|
||||
|
||||
var fake = b.actor.inventory.getItemInOffHand().clone();
|
||||
var meta = fake.getItemMeta();
|
||||
meta.getPersistentDataContainer().remove(new org.bukkit.NamespacedKey("fantasystick", "character_id"));
|
||||
fake.setItemMeta(meta); b.actor.inventory.setItemInOffHand(fake);
|
||||
var counterfeitState = b.actor.snapshot();
|
||||
h.f.sessions.enter(b.player);
|
||||
assertEquals("INVALID_SHEET", h.f.notices.getLast().code());
|
||||
assertArrayEquals(counterfeitState, b.actor.snapshot()); assertNull(h.presentation.name(b.actor.id));
|
||||
assertEquals(record, h.saved(record.id())); assertTrue(h.f.tasks.isEmpty());
|
||||
|
||||
var dead = h.f.characters.recordDeath(record.id()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
var beforeA = a.actor.snapshot();
|
||||
h.f.sessions.enter(a.player); h.f.tick();
|
||||
assertEquals("UNAVAILABLE_CHARACTER", h.f.notices.getLast().code());
|
||||
assertArrayEquals(beforeA, a.actor.snapshot()); assertEquals(exit, h.f.state(a.actor));
|
||||
assertTrue(h.f.sessions.active(a.actor.id).isEmpty()); assertNull(h.presentation.name(a.actor.id));
|
||||
assertEquals(dead, h.saved(record.id()));
|
||||
assertTrue(h.f.characters.restoreDeathRecord(dead.id(), UUID.randomUUID()).get(5, TimeUnit.SECONDS).isEmpty());
|
||||
assertEquals(dead, h.saved(record.id()));
|
||||
var revived = h.f.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertProgress(record, revived); assertFalse(revived.dead());
|
||||
assertEquals(0, record.maximumHealth().compareTo(revived.health()));
|
||||
assertTrue(h.f.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, TimeUnit.SECONDS).isEmpty());
|
||||
a.actor.inventory.setItemInOffHand(new CharacterSheets().create(revived));
|
||||
h.activate(a); // Real session, despite the still-running player delay: exact stable ID exception.
|
||||
assertEquals(revived.id(), h.f.sessions.active(a.actor.id).orElseThrow().character());
|
||||
assertEquals(revived.revision(), h.presentation.snapshot().get(a.actor.id).revision());
|
||||
assertEquals(exit.lastExit(), h.f.state(a.actor).lastExit());
|
||||
b.actor.inventory.setItemInOffHand(beforeB[40]); // Old copied native reference still cannot create a second life.
|
||||
h.f.sessions.enter(b.player); h.f.tick();
|
||||
assertEquals("CHARACTER_BUSY", h.f.notices.getLast().code());
|
||||
assertTrue(h.f.sessions.active(b.actor.id).isEmpty()); assertNull(h.presentation.name(b.actor.id));
|
||||
assertEquals(revived, h.saved(record.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void directSheetReplacementExitsBeforeDelayCheckSameIdResumesAndDifferentIdEntersOnlyAtExactDeadline() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var first = h.saveCharacter("Identical name"); var second = h.saveCharacter("Identical name");
|
||||
var holder = h.holder(first); var ordinaryGear = holder.actor.inventory.getItem(0).clone();
|
||||
h.activate(holder);
|
||||
var firstSession = h.f.sessions.active(holder.actor.id).orElseThrow().session();
|
||||
holder.actor.inventory.setItemInOffHand(new CharacterSheets().create(second));
|
||||
h.changed(holder); // Actual event bridge must perform orderly exit before deferred entry.
|
||||
assertTrue(h.f.sessions.active(holder.actor.id).isEmpty()); assertNull(h.presentation.name(holder.actor.id));
|
||||
assertEquals(ordinaryGear, holder.actor.inventory.getItem(0));
|
||||
var exit = h.f.state(holder.actor);
|
||||
assertEquals(first.id(), exit.lastExit().characterId());
|
||||
assertEquals(firstSession, exit.lastExit().sessionId());
|
||||
h.eventTasks.remove().run(); h.f.tick();
|
||||
assertEquals("COOLDOWN", h.f.notices.getLast().code());
|
||||
assertEquals(exit, h.f.state(holder.actor)); assertEquals(1, h.output.shown.size());
|
||||
|
||||
h.clock.advance(Duration.ofSeconds(20));
|
||||
var renamed = h.f.characters.renameCharacter(first.id(), "Same ID, different name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
holder.actor.inventory.setItemInOffHand(new CharacterSheets().create(renamed).clone());
|
||||
h.changed(holder); h.eventTasks.remove().run(); h.f.tick(); h.f.tick();
|
||||
assertEquals(first.id(), h.f.sessions.active(holder.actor.id).orElseThrow().character());
|
||||
assertEquals(renamed.name(), h.presentation.name(holder.actor.id));
|
||||
assertEquals(exit.lastExit(), h.f.state(holder.actor).lastExit(), "Resume does not extend the deadline");
|
||||
h.clock.advance(Duration.ofSeconds(10));
|
||||
h.f.sessions.exit(holder.player); var nextExit = h.f.state(holder.actor);
|
||||
assertEquals(exit.lastExit().deadline().plusSeconds(30), nextExit.lastExit().deadline());
|
||||
holder.actor.inventory.setItemInOffHand(new CharacterSheets().create(second));
|
||||
var before = holder.actor.snapshot();
|
||||
h.clock.now = nextExit.lastExit().deadline().minusNanos(1);
|
||||
h.f.sessions.enter(holder.player); h.f.tick();
|
||||
assertEquals("COOLDOWN", h.f.notices.getLast().code());
|
||||
assertArrayEquals(before, holder.actor.snapshot()); assertEquals(nextExit, h.f.state(holder.actor));
|
||||
assertNull(h.presentation.name(holder.actor.id));
|
||||
h.clock.now = nextExit.lastExit().deadline(); h.activate(holder);
|
||||
assertEquals(second.id(), h.f.sessions.active(holder.actor.id).orElseThrow().character());
|
||||
assertEquals(second.id(), h.output.shown.getLast().character());
|
||||
assertEquals(second.name(), h.presentation.name(holder.actor.id));
|
||||
assertEquals(nextExit.lastExit(), h.f.state(holder.actor).lastExit());
|
||||
assertEquals(renamed, h.saved(first.id())); assertEquals(second, h.saved(second.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void acknowledgedNamesUseImmutableViewsAndLateCallbacksCannotRenameOrWithdrawTransferredReplacementSessions() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Before accepted rename");
|
||||
var a = h.holder(record); var b = h.holder(record); h.activate(a);
|
||||
var oldSnapshot = h.presentation.snapshot();
|
||||
var firstView = oldSnapshot.get(a.actor.id);
|
||||
assertThrows(UnsupportedOperationException.class, oldSnapshot::clear);
|
||||
var renamed = h.f.characters.renameCharacter(record.id(), "Acknowledged 雪 🐉").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(renamed);
|
||||
assertEquals(record.name(), h.presentation.name(a.actor.id), "Acknowledgment queues native output, never writes it inline");
|
||||
h.displayTasks.remove().run();
|
||||
assertEquals(renamed.name(), h.presentation.name(a.actor.id));
|
||||
assertEquals(renamed.revision(), h.output.renamed.getLast().revision());
|
||||
assertEquals(record.name(), oldSnapshot.get(a.actor.id).name());
|
||||
assertEquals(firstView.session(), h.output.renamed.getLast().session());
|
||||
var latest = h.f.characters.renameCharacter(record.id(), "Transferred authoritative name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(latest); var stale = h.displayTasks.remove();
|
||||
h.f.sessions.exit(a.player); h.f.state(a.actor);
|
||||
var sheet = a.actor.inventory.getItemInOffHand().clone(); a.actor.inventory.setItemInOffHand(null);
|
||||
b.actor.inventory.setItemInOffHand(sheet); h.activate(b);
|
||||
var bView = h.presentation.snapshot().get(b.actor.id);
|
||||
assertEquals(latest.name(), bView.name());
|
||||
stale.run(); stale.run(); h.presentation.withdraw(a.actor.id, firstView.session());
|
||||
assertEquals(Map.of(b.actor.id, bView), h.presentation.snapshot());
|
||||
assertEquals(1, h.output.renamed.size(), "A's delayed acknowledgment does not become B's callback");
|
||||
h.f.sessions.exit(b.player); h.f.state(b.actor); h.activate(b);
|
||||
var replacement = h.presentation.snapshot().get(b.actor.id);
|
||||
assertNotEquals(bView.session(), replacement.session());
|
||||
h.presentation.withdraw(b.actor.id, bView.session()); stale.run();
|
||||
assertEquals(Map.of(b.actor.id, replacement), h.presentation.snapshot());
|
||||
assertEquals(latest, h.saved(record.id()));
|
||||
}
|
||||
}
|
||||
|
||||
private enum Ending { EXIT, QUIT, DISABLE, DEFEAT }
|
||||
private enum Restoration { SUCCESS, MISSING_BOX, WRITE_FAILURE }
|
||||
|
||||
static java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments> lifecycleCases() {
|
||||
return java.util.Arrays.stream(Ending.values()).flatMap(ending -> java.util.Arrays.stream(Restoration.values())
|
||||
.map(restoration -> org.junit.jupiter.params.provider.Arguments.of(ending, restoration)));
|
||||
}
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest(name = "{0} / {1}")
|
||||
@org.junit.jupiter.params.provider.MethodSource("lifecycleCases")
|
||||
void lifecycleWithdrawsBeforeRestorationEvenOnRefusalOrExceptionAndLateNamesCannotResurrectDisplay(
|
||||
Ending ending, Restoration restoration) throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Lifecycle character"); var holder = h.holder(record);
|
||||
var original = holder.actor.snapshot(); var ordinary = holder.ordinary();
|
||||
h.activate(holder);
|
||||
var view = h.presentation.snapshot().get(holder.actor.id);
|
||||
var renamed = h.f.characters.renameCharacter(record.id(), "Late lifecycle name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(renamed); var lateName = h.displayTasks.remove();
|
||||
if (restoration == Restoration.MISSING_BOX) holder.actor.inventory.setItem(9, null);
|
||||
if (restoration == Restoration.WRITE_FAILURE) {
|
||||
h.f.expectedFailure = IllegalStateException.class;
|
||||
holder.actor.beforeMutation = () -> {
|
||||
holder.actor.beforeMutation = () -> {};
|
||||
throw new IllegalStateException("Interrupted equipment restoration before first slot write");
|
||||
};
|
||||
}
|
||||
var beforeExit = holder.actor.snapshot();
|
||||
h.output.onClear = cleared -> {
|
||||
assertEquals(view.session(), cleared.session());
|
||||
assertNull(h.presentation.name(holder.actor.id), "Invalidate the view before native output cleanup");
|
||||
assertArrayEquals(beforeExit, holder.actor.snapshot(), "Display withdrawal precedes equipment writes");
|
||||
};
|
||||
org.bukkit.event.entity.PlayerDeathEvent death = null;
|
||||
switch (ending) {
|
||||
case EXIT -> h.f.sessions.exit(holder.player);
|
||||
case QUIT -> {
|
||||
h.events.quit(new org.bukkit.event.player.PlayerQuitEvent(holder.player, Component.empty()));
|
||||
holder.actor.online = false;
|
||||
}
|
||||
case DISABLE -> { h.events.close(); h.f.sessions.close(); }
|
||||
case DEFEAT -> {
|
||||
death = death(holder); h.events.death(death); assertTrue(death.isCancelled());
|
||||
}
|
||||
}
|
||||
assertTrue(h.f.sessions.active(holder.actor.id).isEmpty());
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(List.of(view), h.output.cleared);
|
||||
lateName.run(); lateName.run();
|
||||
assertTrue(h.output.renamed.isEmpty()); assertTrue(h.presentation.snapshot().isEmpty());
|
||||
var state = h.f.state(holder.actor);
|
||||
assertNotNull(state.lastExit()); assertEquals(record.id(), state.lastExit().characterId());
|
||||
if (restoration == Restoration.SUCCESS) {
|
||||
assertNull(state.pending()); assertArrayEquals(original, holder.actor.snapshot());
|
||||
} else {
|
||||
assertNotNull(state.pending()); assertArrayEquals(beforeExit, holder.actor.snapshot());
|
||||
assertTrue(holder.actor.marker().endsWith(restoration == Restoration.MISSING_BOX ? "|PACKED" : "|RESTORING"));
|
||||
}
|
||||
if (ending == Ending.DEFEAT) {
|
||||
if (restoration != Restoration.SUCCESS) h.f.expectedFailure = IllegalStateException.class;
|
||||
h.f.tick(); // Actual asynchronous death acknowledgment / one-use Tail attempt.
|
||||
var dead = h.saved(record.id()); assertTrue(dead.dead()); assertProgress(renamed, dead);
|
||||
assertEquals(0, dead.health().signum());
|
||||
assertEquals(restoration == Restoration.SUCCESS ? Material.WRITTEN_BOOK : Material.PAPER,
|
||||
holder.actor.inventory.getItemInOffHand().getType());
|
||||
assertEquals(holder.actor.normalMaximum, death.getReviveHealth());
|
||||
assertEquals(holder.actor.normalMaximum, holder.actor.health, "Existing minimal defeat healing, not a fantasy health engine");
|
||||
assertEquals(ordinary.food(), holder.player.getFoodLevel());
|
||||
assertEquals(ordinary.saturation(), holder.player.getSaturation());
|
||||
assertEquals(ordinary.exhaustion(), holder.player.getExhaustion());
|
||||
} else {
|
||||
assertEquals(renamed, h.saved(record.id())); assertEquals(ordinary, holder.ordinary());
|
||||
}
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(1, h.output.cleared.size());
|
||||
h.f.sessions.exit(holder.player); // Repeated cleanup cannot output a second stale withdrawal.
|
||||
assertEquals(1, h.output.cleared.size()); assertEquals(state, h.f.state(holder.actor));
|
||||
}
|
||||
}
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest(name = "disable={0}")
|
||||
@org.junit.jupiter.params.provider.ValueSource(booleans = {false, true})
|
||||
void quitOrDisableBeforeAcknowledgedNativeEntryCannotInstallPresentationFromStaleCallback(boolean disable) throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Never activated"); var holder = h.holder(record);
|
||||
var before = holder.actor.snapshot();
|
||||
h.f.sessions.enter(holder.player); h.f.tick(); var callback = h.f.next();
|
||||
assertNotNull(h.f.state(holder.actor).pending()); assertTrue(h.presentation.snapshot().isEmpty());
|
||||
if (disable) { h.events.close(); h.f.sessions.close(); }
|
||||
else h.events.quit(new org.bukkit.event.player.PlayerQuitEvent(holder.player, Component.empty()));
|
||||
assertNull(h.f.state(holder.actor).pending());
|
||||
callback.run(); callback.run();
|
||||
assertArrayEquals(before, holder.actor.snapshot()); assertNull(holder.actor.marker());
|
||||
assertTrue(h.f.sessions.active(holder.actor.id).isEmpty()); assertTrue(h.presentation.snapshot().isEmpty());
|
||||
assertTrue(h.output.shown.isEmpty()); assertTrue(h.output.cleared.isEmpty());
|
||||
assertEquals(record, h.saved(record.id()));
|
||||
if (!disable) {
|
||||
h.activate(holder); var replacement = h.presentation.snapshot().get(holder.actor.id);
|
||||
callback.run(); assertEquals(Map.of(holder.actor.id, replacement), h.presentation.snapshot());
|
||||
assertEquals(1, h.output.shown.size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void refusedThenSuccessfulRecoveryNeverReinstallsOldPresentationOrReplaysItsDelayedCallbacks() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Recoverable character"); var holder = h.holder(record);
|
||||
var original = holder.actor.snapshot(); h.activate(holder);
|
||||
var oldView = h.presentation.snapshot().get(holder.actor.id);
|
||||
var renamed = h.f.characters.renameCharacter(record.id(), "Recovered current name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(renamed); var oldName = h.displayTasks.remove();
|
||||
var control = holder.actor.inventory.getItem(0).clone();
|
||||
holder.actor.inventory.setItem(0, new ItemStack(Material.EMERALD));
|
||||
var refused = holder.actor.snapshot();
|
||||
assertEquals(EquipmentStorage.RestoreResult.OCCUPIED_SLOT, h.f.sessions.exit(holder.player));
|
||||
var exited = h.f.state(holder.actor);
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(List.of(oldView), h.output.cleared);
|
||||
h.f.sessions.recover(holder.player); h.f.tick();
|
||||
assertArrayEquals(refused, holder.actor.snapshot()); assertEquals(exited, h.f.state(holder.actor));
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(1, h.output.shown.size());
|
||||
holder.actor.inventory.setItem(0, control);
|
||||
h.f.sessions.recover(holder.player); var staleRecovery = h.f.next();
|
||||
h.f.sessions.cancelEntry(holder.actor.id);
|
||||
h.f.sessions.recover(holder.player); h.f.tick();
|
||||
assertArrayEquals(original, holder.actor.snapshot()); assertNull(h.f.state(holder.actor).pending());
|
||||
assertEquals(exited.lastExit(), h.f.state(holder.actor).lastExit());
|
||||
oldName.run(); staleRecovery.run();
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertTrue(h.output.renamed.isEmpty());
|
||||
assertEquals(1, h.output.shown.size()); assertEquals(1, h.output.cleared.size());
|
||||
h.activate(holder); var replacement = h.presentation.snapshot().get(holder.actor.id);
|
||||
assertNotEquals(oldView.session(), replacement.session()); assertEquals(renamed.name(), replacement.name());
|
||||
oldName.run(); staleRecovery.run(); h.presentation.withdraw(holder.actor.id, oldView.session());
|
||||
assertEquals(Map.of(holder.actor.id, replacement), h.presentation.snapshot());
|
||||
assertEquals(replacement.session(), h.f.state(holder.actor).pending().sessionId());
|
||||
assertEquals(renamed, h.saved(record.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void defeatAfterTransferReturnsOnlyTheNewHolderToTheirOwnEntryAndLeavesTheFormerHolderUntouched() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Transferred then defeated"); var a = h.holder(record); var b = h.holder(record);
|
||||
a.actor.location = new Location(null, 100, 70, 100);
|
||||
b.actor.location = new Location(null, -500, 80, -600);
|
||||
var bEntry = b.actor.location.clone(); var bGear = b.actor.inventory.getItem(0).clone();
|
||||
h.activate(a); h.f.sessions.exit(a.player); var aExit = h.f.state(a.actor);
|
||||
b.actor.inventory.setItemInOffHand(a.actor.inventory.getItemInOffHand().clone()); a.actor.inventory.setItemInOffHand(null);
|
||||
var aItems = a.actor.snapshot(); var aOrdinary = a.ordinary(); var aLocation = a.actor.location.clone();
|
||||
h.activate(b); b.actor.location = new Location(null, 999, 64, 888);
|
||||
var event = death(b); h.events.death(event);
|
||||
assertTrue(event.isCancelled()); assertEquals(bEntry, b.actor.teleported); assertEquals(bEntry, b.actor.location);
|
||||
assertEquals(1, b.actor.teleports); assertEquals(0, a.actor.teleports);
|
||||
assertEquals(bGear, b.actor.inventory.getItem(0));
|
||||
assertNull(h.presentation.name(b.actor.id)); assertNull(h.f.state(b.actor).pending());
|
||||
h.f.tick();
|
||||
assertEquals(Material.WRITTEN_BOOK, b.actor.inventory.getItemInOffHand().getType());
|
||||
assertTrue(h.saved(record.id()).dead()); assertProgress(record, h.saved(record.id()));
|
||||
assertArrayEquals(aItems, a.actor.snapshot()); assertEquals(aOrdinary, a.ordinary());
|
||||
assertEquals(aLocation, a.actor.location); assertEquals(aExit, h.f.state(a.actor));
|
||||
assertTrue(h.presentation.snapshot().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
private static org.bukkit.event.entity.PlayerDeathEvent death(Holder holder) {
|
||||
var source = new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.GENERIC)));
|
||||
return new org.bukkit.event.entity.PlayerDeathEvent(holder.player, source, new ArrayList<>(), 7,
|
||||
Component.text("ordinary death"), true);
|
||||
}
|
||||
|
||||
private static void assertProgress(CharacterRecord expected, CharacterRecord actual) {
|
||||
assertEquals(expected.id(), actual.id()); assertEquals(expected.name(), actual.name());
|
||||
assertEquals(expected.stats(), actual.stats()); assertEquals(expected.level(), actual.level());
|
||||
assertEquals(expected.experience(), actual.experience()); assertEquals(expected.unspentPoints(), actual.unspentPoints());
|
||||
assertEquals(expected.learned(), actual.learned()); assertEquals(expected.loadout(), actual.loadout());
|
||||
assertEquals(expected.cooldowns(), actual.cooldowns());
|
||||
}
|
||||
|
||||
private final class Harness implements AutoCloseable {
|
||||
final EquipmentSessionsNativeTest.MutableClock clock = new EquipmentSessionsNativeTest.MutableClock();
|
||||
final EquipmentSessionsNativeTest.Fixture f;
|
||||
final ArrayDeque<Runnable> displayTasks = new ArrayDeque<>();
|
||||
final ArrayDeque<Runnable> eventTasks = new ArrayDeque<>();
|
||||
final games.dmg.fantasystick.session.EquipmentSessionEvents events;
|
||||
final ArrayList<Throwable> displayFailures = new ArrayList<>();
|
||||
final RecordingOutput output = new RecordingOutput();
|
||||
final CharacterPresentation presentation;
|
||||
Harness() throws Exception {
|
||||
var owner = new EquipmentSessionsNativeTest(); owner.data = data;
|
||||
f = owner.new Fixture(Duration.ofSeconds(900), clock);
|
||||
presentation = new CharacterPresentation(output, displayTasks::add,
|
||||
() -> Thread.currentThread() == f.main, displayFailures::add);
|
||||
f.presentation = presentation;
|
||||
f.sessions = f.coordinator(Duration.ofSeconds(900));
|
||||
events = new games.dmg.fantasystick.session.EquipmentSessionEvents(f.sessions, eventTasks::add, f.failures::add);
|
||||
}
|
||||
void changed(Holder holder) {
|
||||
events.changed(new io.papermc.paper.event.player.PlayerInventorySlotChangeEvent(holder.player, 40,
|
||||
new ItemStack(Material.AIR), holder.actor.inventory.getItemInOffHand()));
|
||||
}
|
||||
CharacterRecord saveCharacter(String name) throws Exception {
|
||||
var stats = new EnumMap<Stat, BigInteger>(Stat.class);
|
||||
for (var stat : Stat.values()) stats.put(stat, BigInteger.valueOf(10L + stat.ordinal()));
|
||||
var record = new CharacterRecord(UUID.randomUUID(), name, BigInteger.ZERO, stats, 7,
|
||||
BigInteger.valueOf(643), BigInteger.valueOf(9), new BigDecimal("12.25"),
|
||||
Set.of("fireball", "heal", "revive"), List.of("fireball", "", "heal", "", "revive", "", ""),
|
||||
Map.of("fireball", clock.instant().plusSeconds(30), "revive", clock.instant().plusSeconds(86400)),
|
||||
false, null, null);
|
||||
f.characters.create(record).get(5, TimeUnit.SECONDS);
|
||||
return record;
|
||||
}
|
||||
Holder holder(CharacterRecord record, String account, Material gear, double health, int food, float saturation, float exhaustion) {
|
||||
return new Holder(f.actor(record), account, gear, health, food, saturation, exhaustion);
|
||||
}
|
||||
Holder holder(CharacterRecord record) { return holder(record, "Account-" + UUID.randomUUID(), Material.IRON_AXE, 8.25, 9, 2.5f, 1.25f); }
|
||||
void activate(Holder holder) throws Exception {
|
||||
f.sessions.enter(holder.player); f.tick(); f.tick();
|
||||
assertTrue(f.sessions.active(holder.actor.id).isPresent());
|
||||
}
|
||||
CharacterRecord saved(UUID id) throws Exception { return f.characters.find(id).get(5, TimeUnit.SECONDS).orElseThrow(); }
|
||||
@Override public void close() throws Exception {
|
||||
events.close();
|
||||
try { f.close(); }
|
||||
finally { presentation.close(); }
|
||||
assertTrue(displayFailures.isEmpty(), displayFailures::toString);
|
||||
}
|
||||
}
|
||||
|
||||
private record Ordinary(UUID id, String account, double health, double maximum,
|
||||
int food, float saturation, float exhaustion, Component chat, Component tab) { }
|
||||
|
||||
/** Strict Player port adds observable ordinary nutrition/identity to the existing native-inventory actor. */
|
||||
private static final class Holder {
|
||||
final EquipmentSessionsNativeTest.Actor actor;
|
||||
final Player player;
|
||||
final String account;
|
||||
final Component chat;
|
||||
final Component tab;
|
||||
int food;
|
||||
float saturation;
|
||||
float exhaustion;
|
||||
Holder(EquipmentSessionsNativeTest.Actor actor, String account, Material gear,
|
||||
double health, int food, float saturation, float exhaustion) {
|
||||
this.actor = actor; this.account = account; this.food = food;
|
||||
this.saturation = saturation; this.exhaustion = exhaustion;
|
||||
chat = Component.text("ordinary chat " + account); tab = Component.text("ordinary tab " + account);
|
||||
actor.health = health; actor.inventory.setItem(0, new ItemStack(gear));
|
||||
player = (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class<?>[]{Player.class}, (proxy, method, args) -> {
|
||||
assertSame(actor.main, Thread.currentThread(), "Ordinary Player access stays on the server thread");
|
||||
return switch (method.getName()) {
|
||||
case "getName" -> account;
|
||||
case "displayName" -> { assertEquals(0, method.getParameterCount()); yield chat; }
|
||||
case "playerListName" -> { assertEquals(0, method.getParameterCount()); yield tab; }
|
||||
case "getFoodLevel" -> this.food;
|
||||
case "setFoodLevel" -> { this.food = (Integer) args[0]; yield null; }
|
||||
case "getSaturation" -> this.saturation;
|
||||
case "setSaturation" -> { this.saturation = (Float) args[0]; yield null; }
|
||||
case "getExhaustion" -> this.exhaustion;
|
||||
case "setExhaustion" -> { this.exhaustion = (Float) args[0]; yield null; }
|
||||
default -> {
|
||||
try { yield method.invoke(actor.player, args); }
|
||||
catch (InvocationTargetException failure) { throw failure.getCause(); }
|
||||
}
|
||||
};
|
||||
});
|
||||
var grid = new ManualCraftPlanNativeTest.Fixture(2, 1).grid;
|
||||
actor.view = new org.bukkit.craftbukkit.inventory.CraftAbstractInventoryView() {
|
||||
@Override public org.bukkit.inventory.Inventory getTopInventory() { return grid; }
|
||||
@Override public org.bukkit.inventory.PlayerInventory getBottomInventory() { return actor.inventory; }
|
||||
@Override public org.bukkit.entity.HumanEntity getPlayer() { return player; }
|
||||
@Override public org.bukkit.event.inventory.InventoryType getType() { return org.bukkit.event.inventory.InventoryType.CRAFTING; }
|
||||
@Override public ItemStack getCursor() { return actor.cursor; }
|
||||
@Override public void setCursor(ItemStack item) { actor.cursor = item; }
|
||||
@Override public String getTitle() { return "Whole-character native fixture"; }
|
||||
@Override public String getOriginalTitle() { return getTitle(); }
|
||||
@Override public void setTitle(String title) { throw new AssertionError("Unexpected title mutation"); }
|
||||
@Override public org.bukkit.inventory.MenuType getMenuType() { return null; }
|
||||
};
|
||||
}
|
||||
Ordinary ordinary() {
|
||||
return new Ordinary(player.getUniqueId(), player.getName(), player.getHealth(),
|
||||
player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH).getValue(),
|
||||
player.getFoodLevel(), player.getSaturation(), player.getExhaustion(), player.displayName(), player.playerListName());
|
||||
}
|
||||
}
|
||||
|
||||
/** Output boundary only: native overhead/chat/tab adapters have separate tests owned by the parent. */
|
||||
private static final class RecordingOutput implements CharacterPresentation.Output {
|
||||
final Thread main = Thread.currentThread();
|
||||
final ArrayList<CharacterPresentation.View> shown = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> renamed = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> cleared = new ArrayList<>();
|
||||
java.util.function.Consumer<CharacterPresentation.View> onClear = ignored -> {};
|
||||
@Override public void show(Player player, CharacterPresentation.View view) {
|
||||
assertSame(main, Thread.currentThread()); assertEquals(player.getUniqueId(), view.holder()); shown.add(view);
|
||||
}
|
||||
@Override public void rename(CharacterPresentation.View view) { assertSame(main, Thread.currentThread()); renamed.add(view); }
|
||||
@Override public void clear(CharacterPresentation.View view) {
|
||||
assertSame(main, Thread.currentThread()); onClear.accept(view); cleared.add(view);
|
||||
}
|
||||
@Override public void close() { assertSame(main, Thread.currentThread()); }
|
||||
}
|
||||
}
|
||||
@@ -27,8 +27,12 @@ class DistributionTest {
|
||||
assertFalse(metadata.getVersion().contains("${"));
|
||||
assertEquals("games.dmg.fantasystick.FantasyStickPlugin", metadata.getMain());
|
||||
assertNotNull(metadata.getAPIVersion(), "Declare the native API compatibility contract");
|
||||
assertTrue(metadata.getCommands().isEmpty(), "Admin commands are not yet approved");
|
||||
assertTrue(metadata.getPermissions().isEmpty());
|
||||
assertEquals(java.util.List.of("ProtocolLib"), metadata.getDepend());
|
||||
assertEquals(java.util.Set.of("fantasystick"), metadata.getCommands().keySet());
|
||||
assertEquals("fantasystick.admin", metadata.getCommands().get("fantasystick").get("permission"));
|
||||
assertEquals(1, metadata.getPermissions().size());
|
||||
assertEquals("fantasystick.admin", metadata.getPermissions().getFirst().getName());
|
||||
assertEquals(org.bukkit.permissions.PermissionDefault.OP, metadata.getPermissions().getFirst().getDefault());
|
||||
assertTrue(JavaPlugin.class.isAssignableFrom(FantasyStickPlugin.class));
|
||||
var entrypoint = jar.getJarEntry(metadata.getMain().replace('.', '/') + ".class");
|
||||
assertNotNull(entrypoint);
|
||||
@@ -37,7 +41,7 @@ class DistributionTest {
|
||||
bytecode.readUnsignedShort();
|
||||
assertEquals(69, bytecode.readUnsignedShort(), "Java 25 bytecode");
|
||||
}
|
||||
assertFalse(jar.stream().anyMatch(entry -> entry.getName().startsWith("org/")
|
||||
assertFalse(jar.stream().anyMatch(entry -> entry.getName().startsWith("com/comphenix/") || entry.getName().startsWith("org/")
|
||||
|| entry.getName().startsWith("net/") || entry.getName().endsWith("Test.class")),
|
||||
"Server API and test dependencies must not ship in the plugin");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package games.dmg.fantasystick.party;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PartyRosterTest {
|
||||
final MutableClock clock = new MutableClock();
|
||||
final Set<UUID> online = new HashSet<>();
|
||||
final PartyRoster parties = new PartyRoster(clock, online::contains);
|
||||
|
||||
@Test void creatorLeadsExactlyOnePlayerOwnedPartyAndSnapshotsCannotMutateMembership() {
|
||||
UUID leader = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
assertEquals(leader, party.leader());
|
||||
assertEquals(List.of(leader), party.members());
|
||||
assertEquals(party, parties.partyOf(leader).orElseThrow());
|
||||
assertTrue(parties.create(leader).isEmpty());
|
||||
assertThrows(UnsupportedOperationException.class, () -> party.members().clear());
|
||||
assertTrue(parties.create(UUID.randomUUID()).isEmpty());
|
||||
}
|
||||
|
||||
@Test void invitationsRequireLeaderAuthorityAndRecipientConsentAndCannotBeReplayed() {
|
||||
UUID leader = player(), member = player(), stranger = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
assertTrue(parties.invite(stranger, party.id(), member).isEmpty());
|
||||
assertTrue(parties.invite(leader, UUID.randomUUID(), member).isEmpty());
|
||||
var invitation = parties.invite(leader, party.id(), member).orElseThrow();
|
||||
assertEquals(invitation, parties.invite(leader, party.id(), member).orElseThrow());
|
||||
assertTrue(parties.partyOf(member).isEmpty(), "Inviting must not force membership");
|
||||
assertFalse(parties.accept(stranger, invitation.id()));
|
||||
assertTrue(parties.accept(member, invitation.id()));
|
||||
assertFalse(parties.accept(member, invitation.id()));
|
||||
assertEquals(List.of(leader, member), parties.partyOf(leader).orElseThrow().members());
|
||||
assertEquals(parties.partyOf(leader), parties.partyOf(member));
|
||||
assertEquals(List.of(leader), party.members(), "Old snapshots stay immutable");
|
||||
assertTrue(parties.invite(member, party.id(), stranger).isEmpty());
|
||||
}
|
||||
|
||||
@Test void leaderDisconnectRetainsLeadershipUntilTheLastOnlineMemberDisconnects() {
|
||||
UUID leader = player(), member = player(), invited = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
assertTrue(parties.accept(member, parties.invite(leader, party.id(), member).orElseThrow().id()));
|
||||
var outstanding = parties.invite(leader, party.id(), invited).orElseThrow();
|
||||
parties.disconnect(leader); // Bukkit may still report the departing player as online inside QuitEvent.
|
||||
online.remove(leader);
|
||||
assertEquals(leader, parties.partyOf(member).orElseThrow().leader());
|
||||
assertEquals(List.of(leader, member), parties.partyOf(member).orElseThrow().members());
|
||||
parties.disconnect(member); // The invited non-member does not keep the party alive.
|
||||
assertTrue(parties.partyOf(leader).isEmpty());
|
||||
assertTrue(parties.partyOf(member).isEmpty());
|
||||
assertFalse(parties.accept(invited, outstanding.id()));
|
||||
online.add(leader);
|
||||
assertNotEquals(party.id(), parties.create(leader).orElseThrow().id());
|
||||
}
|
||||
|
||||
@Test void explicitLeaderLeaveDisbandsWithoutSuccessionAndStaleActionsCannotTouchANewParty() {
|
||||
UUID leader = player(), member = player(), invited = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
assertTrue(parties.accept(member, parties.invite(leader, party.id(), member).orElseThrow().id()));
|
||||
var offer = parties.invite(leader, party.id(), invited).orElseThrow();
|
||||
assertFalse(parties.leave(member, UUID.randomUUID()));
|
||||
assertTrue(parties.leave(leader, party.id()));
|
||||
assertTrue(parties.partyOf(member).isEmpty());
|
||||
assertTrue(parties.partyOf(leader).isEmpty());
|
||||
var replacement = parties.create(leader).orElseThrow();
|
||||
assertFalse(parties.leave(leader, party.id()));
|
||||
assertFalse(parties.accept(invited, offer.id()));
|
||||
assertEquals(replacement, parties.partyOf(leader).orElseThrow());
|
||||
}
|
||||
|
||||
@Test void invitationsExpireAtExactlySixtyRealSecondsAndNewInvitesDoNotReviveOldTokens() {
|
||||
UUID leader = player(), before = player(), at = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
var beforeOffer = parties.invite(leader, party.id(), before).orElseThrow();
|
||||
var atOffer = parties.invite(leader, party.id(), at).orElseThrow();
|
||||
clock.now = Instant.EPOCH.plusSeconds(60).minusNanos(1);
|
||||
assertTrue(parties.accept(before, beforeOffer.id()));
|
||||
clock.now = Instant.EPOCH.plusSeconds(60);
|
||||
assertFalse(parties.accept(at, atOffer.id()));
|
||||
var fresh = parties.invite(leader, party.id(), at).orElseThrow();
|
||||
assertNotEquals(atOffer.id(), fresh.id());
|
||||
assertFalse(parties.accept(at, atOffer.id()));
|
||||
assertTrue(parties.accept(at, fresh.id()));
|
||||
}
|
||||
|
||||
@Test void invitationsDoNotReserveSlotsAndAcceptanceRechecksTheSixPlayerCapacity() {
|
||||
UUID leader = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
var offers = new java.util.ArrayList<PartyRoster.Invitation>();
|
||||
for (int i = 0; i < 7; i++) offers.add(parties.invite(leader, party.id(), player()).orElseThrow());
|
||||
assertEquals(1, parties.partyOf(leader).orElseThrow().members().size());
|
||||
for (int i = 0; i < 5; i++) assertTrue(parties.accept(offers.get(i).invitee(), offers.get(i).id()));
|
||||
assertFalse(parties.accept(offers.get(5).invitee(), offers.get(5).id()));
|
||||
assertFalse(parties.accept(offers.get(6).invitee(), offers.get(6).id()));
|
||||
assertEquals(6, parties.partyOf(leader).orElseThrow().members().size());
|
||||
assertTrue(parties.invite(leader, party.id(), player()).isEmpty());
|
||||
assertTrue(parties.leave(offers.getFirst().invitee(), party.id()));
|
||||
assertTrue(parties.accept(offers.get(5).invitee(), offers.get(5).id()));
|
||||
assertEquals(6, parties.partyOf(leader).orElseThrow().members().size());
|
||||
}
|
||||
|
||||
@Test void onlyTheCurrentOnlineLeaderCanKickOrDisbandTheMatchingParty() {
|
||||
UUID leader = player(), member = player(), stranger = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
assertTrue(parties.accept(member, parties.invite(leader, party.id(), member).orElseThrow().id()));
|
||||
assertFalse(parties.kick(member, party.id(), leader));
|
||||
assertFalse(parties.disband(member, party.id()));
|
||||
assertFalse(parties.disband(stranger, party.id()));
|
||||
assertFalse(parties.kick(leader, UUID.randomUUID(), member));
|
||||
assertFalse(parties.kick(leader, party.id(), stranger));
|
||||
online.remove(leader);
|
||||
assertFalse(parties.kick(leader, party.id(), member));
|
||||
assertFalse(parties.disband(leader, party.id()));
|
||||
online.add(leader);
|
||||
assertTrue(parties.kick(leader, party.id(), member));
|
||||
assertTrue(parties.partyOf(member).isEmpty());
|
||||
assertEquals(List.of(leader), parties.partyOf(leader).orElseThrow().members());
|
||||
assertTrue(parties.disband(leader, party.id()));
|
||||
assertTrue(parties.partyOf(leader).isEmpty());
|
||||
assertFalse(parties.disband(leader, party.id()));
|
||||
}
|
||||
|
||||
@Test void shutdownRevokesAllPartiesInvitationsAndOldServiceAuthorityWithoutRestartPersistence() {
|
||||
UUID leader = player(), member = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
var offer = parties.invite(leader, party.id(), member).orElseThrow();
|
||||
parties.close(); parties.close();
|
||||
assertTrue(parties.partyOf(leader).isEmpty());
|
||||
assertFalse(parties.accept(member, offer.id()));
|
||||
assertTrue(parties.create(leader).isEmpty());
|
||||
assertTrue(parties.invite(leader, party.id(), member).isEmpty());
|
||||
try (var restarted = new PartyRoster(clock, online::contains)) {
|
||||
assertTrue(restarted.partyOf(leader).isEmpty());
|
||||
assertFalse(restarted.accept(member, offer.id()));
|
||||
assertNotEquals(party.id(), restarted.create(leader).orElseThrow().id());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void quitImmediatelyRevokesManagementDespiteALaggingOnlineFlagAndJoinRestoresIt() {
|
||||
UUID leader = player(), member = player(), target = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
assertTrue(parties.accept(member, parties.invite(leader, party.id(), member).orElseThrow().id()));
|
||||
parties.disconnect(leader);
|
||||
assertTrue(parties.invite(leader, party.id(), target).isEmpty());
|
||||
assertFalse(parties.kick(leader, party.id(), member));
|
||||
assertFalse(parties.disband(leader, party.id()));
|
||||
assertFalse(parties.leave(leader, party.id()));
|
||||
parties.arrive(leader);
|
||||
assertTrue(parties.invite(leader, party.id(), target).isPresent());
|
||||
assertTrue(parties.leave(member, party.id()));
|
||||
assertEquals(List.of(leader), parties.partyOf(leader).orElseThrow().members());
|
||||
}
|
||||
|
||||
@Test void lastOnlineMemberLeavingAlsoDisbandsRatherThanStrandingOfflineMembers() {
|
||||
UUID leader = player(), member = player();
|
||||
var party = parties.create(leader).orElseThrow();
|
||||
assertTrue(parties.accept(member, parties.invite(leader, party.id(), member).orElseThrow().id()));
|
||||
parties.disconnect(leader);
|
||||
assertTrue(parties.leave(member, party.id()));
|
||||
assertTrue(parties.partyOf(leader).isEmpty());
|
||||
assertTrue(parties.partyOf(member).isEmpty());
|
||||
}
|
||||
|
||||
UUID player() { UUID id = UUID.randomUUID(); online.add(id); return id; }
|
||||
static final class MutableClock extends Clock {
|
||||
Instant now = Instant.EPOCH;
|
||||
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return now; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class AdventureSettingsTest {
|
||||
@org.junit.jupiter.api.io.TempDir java.nio.file.Path directory;
|
||||
|
||||
@Test void acknowledgesDurableUpdateWithoutDiscardingOtherConfiguration() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
java.nio.file.Files.writeString(file, "starting-points: 73\nother:\n enabled: true\n");
|
||||
try (var settings = new AdventureSettings(directory, true)) {
|
||||
assertFalse(settings.set(false).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertFalse(settings.enabled());
|
||||
var saved = new org.yaml.snakeyaml.Yaml().<java.util.Map<String, Object>>load(java.nio.file.Files.readString(file));
|
||||
assertEquals(false, saved.get("adventure-mode"));
|
||||
assertEquals(73, saved.get("starting-points"));
|
||||
assertEquals(java.util.Map.of("enabled", true), saved.get("other"));
|
||||
assertFalse(AdventureSettings.validate(saved.get("adventure-mode")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void acknowledgmentsAreWorkerOwnedOrderedAndSurviveObserverCancellationAndClose() throws Exception {
|
||||
var entered = new java.util.concurrent.CountDownLatch(1);
|
||||
var release = new java.util.concurrent.CountDownLatch(1);
|
||||
var caller = Thread.currentThread();
|
||||
var settings = new AdventureSettings(directory, true, (from, to) -> {
|
||||
assertNotSame(caller, Thread.currentThread());
|
||||
entered.countDown();
|
||||
try { assertTrue(release.await(5, java.util.concurrent.TimeUnit.SECONDS)); }
|
||||
catch (InterruptedException interrupted) { throw new java.io.IOException(interrupted); }
|
||||
java.nio.file.Files.move(from, to, java.nio.file.StandardCopyOption.ATOMIC_MOVE,
|
||||
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
});
|
||||
try {
|
||||
var first = settings.set(false);
|
||||
assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(settings.enabled());
|
||||
first.toCompletableFuture().cancel(false);
|
||||
var second = settings.set(true);
|
||||
settings.close();
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> settings.set(false).toCompletableFuture().get());
|
||||
release.countDown();
|
||||
assertFalse(first.toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(second.toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(settings.enabled());
|
||||
var saved = new org.yaml.snakeyaml.Yaml().<java.util.Map<String, Object>>load(
|
||||
java.nio.file.Files.readString(directory.resolve("config.yml")));
|
||||
assertEquals(true, saved.get("adventure-mode"));
|
||||
} finally { release.countDown(); settings.close(); }
|
||||
}
|
||||
|
||||
@Test void failedSavePreservesEffectiveValueAndUnrelatedOriginalBytes() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
String original = "other: 17\nadventure-mode: true\n";
|
||||
java.nio.file.Files.writeString(file, original);
|
||||
try (var settings = new AdventureSettings(directory, true, (from, to) -> { throw new java.io.IOException("no write"); })) {
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> settings.set(false).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(settings.enabled());
|
||||
assertEquals(original, java.nio.file.Files.readString(file));
|
||||
}
|
||||
try (var files = java.nio.file.Files.list(directory)) {
|
||||
assertFalse(files.anyMatch(path -> path.toString().endsWith(".tmp")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void corruptDuplicateOversizedOrSymlinkedConfigurationIsRetained() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
for (String invalid : java.util.List.of("a: [broken", "other: 1\nother: 2\n", "[1, 2]", "#".repeat(1_048_577))) {
|
||||
java.nio.file.Files.writeString(file, invalid);
|
||||
try (var settings = new AdventureSettings(directory, true)) {
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> settings.set(false).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(settings.enabled()); assertEquals(invalid, java.nio.file.Files.readString(file));
|
||||
}
|
||||
}
|
||||
java.nio.file.Files.delete(file);
|
||||
var outside = directory.resolve("outside.yml");
|
||||
java.nio.file.Files.writeString(outside, "keep: me\n");
|
||||
java.nio.file.Files.createSymbolicLink(file, outside);
|
||||
try (var settings = new AdventureSettings(directory, true)) {
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> settings.set(false).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(settings.enabled()); assertEquals("keep: me\n", java.nio.file.Files.readString(outside));
|
||||
assertTrue(java.nio.file.Files.isSymbolicLink(file));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void defaultsToTrueAndAcceptsOnlyActualBooleanValues() {
|
||||
assertTrue(AdventureSettings.validate(null));
|
||||
assertTrue(AdventureSettings.validate(Boolean.TRUE));
|
||||
assertFalse(AdventureSettings.validate(Boolean.FALSE));
|
||||
for (Object invalid : new Object[]{"true", "false", "yes", 0, 1, java.util.List.of(), java.util.Map.of()}) {
|
||||
assertThrows(IllegalArgumentException.class, () -> AdventureSettings.validate(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,96 @@ class CharacterStorageTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestDeathPreservesQueuedRenameAndProgressAndAcknowledgesOnlyOneDeath() throws Exception {
|
||||
var template = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var live = new CharacterRecord(template.id(), template.name(), BigInteger.ZERO, template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), template.maximumHealth(),
|
||||
template.learned(), template.loadout(), template.cooldowns(), false, null, null);
|
||||
var now = template.diedAt().plusSeconds(60);
|
||||
try (var storage = new CharacterStorage(new YamlCharacterRepository(data), Clock.fixed(now, ZoneOffset.UTC))) {
|
||||
storage.create(live).join();
|
||||
var rename = storage.renameCharacter(live.id(), "Newest anvil name");
|
||||
// This is one worker operation, not a caller-side find -> expected-revision write.
|
||||
var death = storage.recordDeath(live.id());
|
||||
var duplicate = storage.recordDeath(live.id());
|
||||
var latest = rename.join().orElseThrow();
|
||||
var dead = death.join().orElseThrow();
|
||||
assertEquals(latest.name(), dead.name());
|
||||
assertEquals(latest.revision().add(BigInteger.ONE), dead.revision());
|
||||
assertEquals(latest.stats(), dead.stats()); assertEquals(latest.cooldowns(), dead.cooldowns());
|
||||
assertEquals(latest.experience(), dead.experience()); assertEquals(latest.loadout(), dead.loadout());
|
||||
assertEquals(latest.level(), dead.level()); assertEquals(latest.unspentPoints(), dead.unspentPoints());
|
||||
assertEquals(latest.learned(), dead.learned()); assertEquals(java.math.BigDecimal.ZERO, dead.health());
|
||||
assertEquals(now, dead.diedAt()); assertNotNull(dead.deathId()); assertTrue(dead.dead());
|
||||
assertTrue(duplicate.join().isEmpty());
|
||||
assertEquals(dead, storage.find(live.id()).join().orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deathCapturesRequestTimeAndDoesNotAcknowledgeBeforeAtomicReplacement() throws Exception {
|
||||
var template = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var live = new CharacterRecord(template.id(), template.name(), BigInteger.ZERO, template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), template.maximumHealth(),
|
||||
template.learned(), template.loadout(), template.cooldowns(), false, null, null);
|
||||
var requestedAt = template.diedAt().plusSeconds(10);
|
||||
var time = new java.util.concurrent.atomic.AtomicReference<>(requestedAt);
|
||||
var clock = new Clock() {
|
||||
@Override public java.time.ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(java.time.ZoneId zone) { return this; }
|
||||
@Override public java.time.Instant instant() { return time.get(); }
|
||||
};
|
||||
var entered = new CountDownLatch(1); var release = new CountDownLatch(1);
|
||||
var writes = new java.util.concurrent.atomic.AtomicInteger(); var caller = Thread.currentThread();
|
||||
var repository = new YamlCharacterRepository(data, (source, target) -> {
|
||||
assertNotSame(caller, Thread.currentThread());
|
||||
if (writes.incrementAndGet() == 1) {
|
||||
entered.countDown();
|
||||
try { if (!release.await(5, TimeUnit.SECONDS)) throw new IOException("Gate timeout"); }
|
||||
catch (InterruptedException e) { throw new IOException(e); }
|
||||
}
|
||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
});
|
||||
try (var storage = new CharacterStorage(repository, clock)) {
|
||||
var create = storage.create(live);
|
||||
java.util.concurrent.CompletableFuture<java.util.Optional<CharacterRecord>> death;
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
death = storage.recordDeath(live.id());
|
||||
time.set(requestedAt.plusSeconds(90));
|
||||
assertFalse(death.isDone());
|
||||
} finally { release.countDown(); }
|
||||
create.get(5, TimeUnit.SECONDS);
|
||||
var dead = death.get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertEquals(requestedAt, dead.diedAt()); assertEquals(dead, repository.load(live.id()).orElseThrow());
|
||||
assertEquals(2, writes.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deathWriteFailureOrLostAcknowledgmentNeverPermitsDuplicateDeathOfAnAlreadyDeadRecord() throws Exception {
|
||||
for (boolean moved : new boolean[]{false, true}) {
|
||||
var template = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var live = new CharacterRecord(template.id(), template.name(), BigInteger.ZERO, template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), template.maximumHealth(),
|
||||
template.learned(), template.loadout(), template.cooldowns(), false, null, null);
|
||||
var repository = new YamlCharacterRepository(data); repository.create(live);
|
||||
var broken = new YamlCharacterRepository(data, (source, target) -> {
|
||||
if (moved) Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
throw new IOException("Unacknowledged death");
|
||||
});
|
||||
try (var storage = new CharacterStorage(broken, Clock.systemUTC())) {
|
||||
assertThrows(CompletionException.class, () -> storage.recordDeath(live.id()).join());
|
||||
var current = repository.load(live.id()).orElseThrow(); assertEquals(moved, current.dead());
|
||||
if (moved) {
|
||||
assertTrue(storage.recordDeath(live.id()).join().isEmpty());
|
||||
assertEquals(current, repository.load(live.id()).orElseThrow());
|
||||
} else assertEquals(live, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAnOldOrUnknownDeathBookWithoutChangingTheSavedCharacter() throws Exception {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class EquipmentSessionStoreTest {
|
||||
@TempDir Path data;
|
||||
// Synthetic clock, not a document/event timestamp.
|
||||
private static final Instant NOW = Instant.parse("2000-01-01T00:00:00.123456789Z");
|
||||
private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC);
|
||||
private final UUID player = UUID.randomUUID();
|
||||
private final UUID session = UUID.randomUUID();
|
||||
private final UUID character = UUID.randomUUID();
|
||||
|
||||
private static <T> T await(CompletionStage<T> stage) throws Exception {
|
||||
return stage.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test void previousGameModeIsAcknowledgedPersistedAndCannotBeReplacedByARepeatedPreparation() throws Exception {
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var prepared = await(store.prepare(player, session, character, "CREATIVE"));
|
||||
assertEquals("CREATIVE", prepared.pending().previousGameMode());
|
||||
try (var reopened = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(prepared, await(reopened.find(player)).orElseThrow());
|
||||
assertEquals(prepared, await(reopened.prepare(player, session, character, "CREATIVE")));
|
||||
failure(reopened.prepare(player, session, character, "SURVIVAL"));
|
||||
assertEquals(prepared, await(reopened.find(player)).orElseThrow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Path record() { return data.resolve("sessions").resolve(player + ".yml"); }
|
||||
|
||||
private static Throwable failure(CompletionStage<?> stage) {
|
||||
return assertThrows(ExecutionException.class,
|
||||
() -> stage.toCompletableFuture().get(5, TimeUnit.SECONDS)).getCause();
|
||||
}
|
||||
|
||||
private static void replace(Path source, Path target) throws IOException {
|
||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
private static void waitFor(CountDownLatch latch) throws IOException {
|
||||
try {
|
||||
if (!latch.await(5, TimeUnit.SECONDS)) throw new IOException("Test gate timed out");
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Test gate interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeExitAtomicallyClearsMatchingReceiptAndDrainsAcrossShutdown() throws Exception {
|
||||
var store = new EquipmentSessionStore(data, CLOCK);
|
||||
await(store.prepare(player, session, character));
|
||||
var completed = store.completeExit(player, session, Duration.ofSeconds(900));
|
||||
store.close();
|
||||
var saved = await(completed);
|
||||
assertNull(saved.pending(), "Accepted exit must include cleanup, not queue it after shutdown");
|
||||
assertEquals(BigInteger.ONE, saved.revision(), "One atomic write");
|
||||
assertEquals(NOW.plusSeconds(900), saved.lastExit().deadline());
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofHours(1)))) {
|
||||
assertEquals(saved, await(reopened.completeExit(player, session, Duration.ofDays(1))));
|
||||
UUID next = UUID.randomUUID();
|
||||
var pending = await(reopened.prepare(player, next, character));
|
||||
assertEquals(pending, await(reopened.completeExit(player, session, Duration.ZERO)));
|
||||
var exited = await(reopened.recordExit(player, next, Duration.ofSeconds(30)));
|
||||
var restored = await(reopened.completeExit(player, next, Duration.ofDays(2)));
|
||||
assertNull(restored.pending());
|
||||
assertEquals(exited.lastExit(), restored.lastExit());
|
||||
assertInstanceOf(IOException.class, failure(reopened.completeExit(player, UUID.randomUUID(), Duration.ZERO)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void atomicExitFailureKeepsReceiptAndExistingDeadlineUntilSingleWriteRetry() throws Exception {
|
||||
EquipmentSessionStore.State exited;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
await(store.prepare(player, session, character));
|
||||
exited = await(store.recordExit(player, session, Duration.ofSeconds(30)));
|
||||
}
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var failing = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
throw new IOException("Injected exit replacement failure");
|
||||
})) {
|
||||
assertInstanceOf(IOException.class, failure(failing.completeExit(player, session, Duration.ofDays(1))));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
assertEquals(exited, await(failing.find(player)).orElseThrow());
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofDays(1)))) {
|
||||
for (Duration invalid : List.of(Duration.ofNanos(-1), Duration.ofSeconds(Long.MAX_VALUE))) {
|
||||
failure(reopened.completeExit(player, session, invalid));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
var result = await(reopened.completeExit(player, session, Duration.ZERO));
|
||||
assertNull(result.pending());
|
||||
assertEquals(exited.lastExit(), result.lastExit());
|
||||
assertEquals(exited.revision().add(BigInteger.ONE), result.revision());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgmentsFollowWorkerCommitAndObserversCannotCancelOwnedWork() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
Thread caller = Thread.currentThread();
|
||||
var diskThread = new AtomicReference<Thread>();
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
diskThread.set(Thread.currentThread());
|
||||
entered.countDown();
|
||||
waitFor(release);
|
||||
replace(source, target);
|
||||
})) {
|
||||
var stage = store.prepare(player, session, character);
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
assertNotSame(caller, diskThread.get());
|
||||
assertFalse(Files.exists(record()));
|
||||
assertFalse(stage.toCompletableFuture().isDone());
|
||||
assertTrue(stage.toCompletableFuture().cancel(true));
|
||||
assertTrue(stage.toCompletableFuture().complete(null));
|
||||
assertFalse(stage.toCompletableFuture().isDone(), "Observations cannot complete the owned acknowledgment");
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
var saved = await(stage);
|
||||
assertNotNull(saved.pending());
|
||||
assertEquals(saved, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeIsNonblockingDrainsAcceptedWorkAndExitTimeIsCapturedBeforeTheQueueRuns() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var time = new AtomicReference<>(NOW);
|
||||
Clock clock = new Clock() {
|
||||
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return time.get(); }
|
||||
};
|
||||
var store = new EquipmentSessionStore(data, clock, (source, target) -> {
|
||||
entered.countDown();
|
||||
waitFor(release);
|
||||
replace(source, target);
|
||||
});
|
||||
var prepared = store.prepare(player, session, character);
|
||||
CompletionStage<EquipmentSessionStore.State> exited = null;
|
||||
CompletionStage<EquipmentSessionStore.State> cleared = null;
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
time.set(NOW.plusSeconds(2));
|
||||
exited = store.recordExit(player, session, Duration.ofSeconds(30));
|
||||
cleared = store.clearReceipt(player, session);
|
||||
time.set(NOW.plusSeconds(600));
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), store::close);
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.find(player)));
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.prepare(player, UUID.randomUUID(), character)));
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.clearReceipt(player, session)));
|
||||
} finally {
|
||||
release.countDown();
|
||||
store.close();
|
||||
await(prepared);
|
||||
if (exited != null) await(exited);
|
||||
if (cleared != null) await(cleared);
|
||||
}
|
||||
var exit = await(exited);
|
||||
assertEquals(NOW.plusSeconds(2), exit.lastExit().exitedAt());
|
||||
assertEquals(NOW.plusSeconds(32), exit.lastExit().deadline());
|
||||
try (var reopened = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(await(cleared), await(reopened.find(player)).orElseThrow());
|
||||
assertNull(await(cleared).pending());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void completedExitUsesRequestTimeBehindAWorkerBacklogAndRetriesKeepThatDeadline() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var time = new AtomicReference<>(NOW);
|
||||
Clock clock = new Clock() {
|
||||
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return time.get(); }
|
||||
};
|
||||
try (var store = new EquipmentSessionStore(data, clock, (source, target) -> {
|
||||
entered.countDown(); waitFor(release); replace(source, target);
|
||||
})) {
|
||||
var preparation = store.prepare(player, session, character);
|
||||
CompletionStage<EquipmentSessionStore.State> completion;
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
time.set(NOW.plusSeconds(2));
|
||||
completion = store.completeExit(player, session, Duration.ofSeconds(900));
|
||||
assertFalse(completion.toCompletableFuture().isDone());
|
||||
time.set(NOW.plusSeconds(3600)); // Worker cannot execute the exit until after its deadline.
|
||||
} finally { release.countDown(); }
|
||||
await(preparation);
|
||||
var completed = await(completion);
|
||||
assertNull(completed.pending());
|
||||
assertEquals(NOW.plusSeconds(2), completed.lastExit().exitedAt());
|
||||
assertEquals(NOW.plusSeconds(902), completed.lastExit().deadline());
|
||||
assertTrue(completed.canEnter(UUID.randomUUID(), Duration.ofSeconds(900), clock.instant()));
|
||||
assertEquals(completed, await(store.completeExit(player, session, Duration.ofDays(1))));
|
||||
assertEquals(completed, await(store.recordExit(player, session, Duration.ofDays(1))));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedForcedTemporaryReplacementPreservesOriginalAndRetryIsPossible() throws Exception {
|
||||
EquipmentSessionStore.State original;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
original = await(store.prepare(player, session, character));
|
||||
}
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var failing = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
assertTrue(Files.isRegularFile(source));
|
||||
assertTrue(Files.readString(source).contains("schema-version: 1"));
|
||||
assertArrayEquals(before, Files.readAllBytes(target));
|
||||
throw new IOException("PRIVATE injected filesystem detail");
|
||||
})) {
|
||||
Throwable error = failure(failing.recordExit(player, session, Duration.ofSeconds(900)));
|
||||
assertInstanceOf(IOException.class, error);
|
||||
assertFalse(error.toString().contains("PRIVATE"));
|
||||
assertNull(error.getCause());
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
assertEquals(original, await(failing.find(player)).orElseThrow());
|
||||
assertInstanceOf(IOException.class, failure(failing.clearReceipt(player, session)));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
try (var paths = Files.list(data.resolve("sessions"))) {
|
||||
assertFalse(paths.anyMatch(path -> path.toString().endsWith(".tmp")));
|
||||
}
|
||||
try (var retry = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(BigInteger.ONE, await(retry.recordExit(player, session, Duration.ZERO)).revision());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPreparationDoesNotCreateAReceiptAndConstructorDoesNotTouchInvalidDirectory() throws Exception {
|
||||
try (var failing = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
throw new IOException("Refused atomic replacement");
|
||||
})) {
|
||||
assertInstanceOf(IOException.class, failure(failing.prepare(player, session, character)));
|
||||
assertFalse(Files.exists(record()));
|
||||
assertTrue(await(failing.find(player)).isEmpty());
|
||||
}
|
||||
Path blocked = data.resolve("not-a-directory");
|
||||
Files.writeString(blocked, "untouched");
|
||||
try (var store = new EquipmentSessionStore(blocked, CLOCK)) {
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertEquals("untouched", Files.readString(blocked));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneFailFastLockCoordinatesInstancesWithoutLeakingPerSessionLockFiles() throws Exception {
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var original = await(store.prepare(player, session, character));
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var channel = FileChannel.open(data.resolve("sessions/.sessions.lock"), StandardOpenOption.WRITE);
|
||||
var lock = channel.lock();
|
||||
var other = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertTrue(lock.isValid());
|
||||
assertInstanceOf(IOException.class, failure(other.prepare(player, UUID.randomUUID(), character)));
|
||||
assertInstanceOf(IOException.class, failure(other.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(other.clearReceipt(player, session)));
|
||||
assertInstanceOf(IOException.class, failure(other.find(player)));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
assertEquals(original, await(store.find(player)).orElseThrow());
|
||||
for (int index = 0; index < 48; index++) {
|
||||
UUID owner = UUID.randomUUID();
|
||||
UUID attempt = UUID.randomUUID();
|
||||
await(store.prepare(owner, attempt, character));
|
||||
await(store.clearReceipt(owner, attempt));
|
||||
}
|
||||
try (var paths = Files.list(data.resolve("sessions"))) {
|
||||
var files = paths.toList();
|
||||
assertEquals(1L, files.stream().filter(path -> path.toString().endsWith(".lock")).count());
|
||||
assertFalse(files.stream().anyMatch(path -> path.toString().endsWith(".tmp")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void competingInstancesCannotReplaceAnAcknowledgedPendingSession() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
try (var first = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
entered.countDown();
|
||||
waitFor(release);
|
||||
replace(source, target);
|
||||
}); var second = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var preparation = first.prepare(player, session, character);
|
||||
UUID competing = UUID.randomUUID();
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
assertInstanceOf(IOException.class, failure(second.prepare(player, competing, character)));
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
var saved = await(preparation);
|
||||
assertInstanceOf(IOException.class, failure(second.prepare(player, competing, character)));
|
||||
assertEquals(saved, await(second.prepare(player, session, character)));
|
||||
assertEquals(saved, await(second.find(player)).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void symlinkedRecordsAndLockFilesAreNeverFollowedOrReplaced() throws Exception {
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
await(store.prepare(player, session, character));
|
||||
Path outside = data.resolve("outside.yml");
|
||||
Files.move(record(), outside);
|
||||
byte[] bytes = Files.readAllBytes(outside);
|
||||
Files.createSymbolicLink(record(), outside);
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, session)));
|
||||
assertTrue(Files.isSymbolicLink(record()));
|
||||
assertArrayEquals(bytes, Files.readAllBytes(outside));
|
||||
Files.delete(record());
|
||||
Files.move(outside, record());
|
||||
Path lock = data.resolve("sessions/.sessions.lock");
|
||||
Files.delete(lock); // Fixture only; no work is running or holding this lock.
|
||||
Files.writeString(outside, "protected lock target");
|
||||
Files.createSymbolicLink(lock, outside);
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, session)));
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertEquals("protected lock target", Files.readString(outside));
|
||||
assertArrayEquals(bytes, Files.readAllBytes(record()));
|
||||
assertTrue(Files.isSymbolicLink(lock));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void symlinkedSessionDirectoryAndNonregularRecordAreRefused() throws Exception {
|
||||
Path outside = Files.createDirectory(data.resolve("outside"));
|
||||
Files.createSymbolicLink(data.resolve("sessions"), outside);
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
try (var paths = Files.list(outside)) { assertEquals(0, paths.count()); }
|
||||
Files.delete(data.resolve("sessions"));
|
||||
Files.createDirectories(record());
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertTrue(Files.isDirectory(record()));
|
||||
}
|
||||
}
|
||||
|
||||
private String validYaml() {
|
||||
return """
|
||||
schema-version: 1
|
||||
player-id: %s
|
||||
revision: '9'
|
||||
pending:
|
||||
session-id: %s
|
||||
character-id: %s
|
||||
prepared-at: '%s'
|
||||
last-exit:
|
||||
session-id: %s
|
||||
character-id: %s
|
||||
exited-at: '%s'
|
||||
deadline: '%s'
|
||||
""".formatted(player, session, character, NOW, session, character, NOW.plusSeconds(1), NOW.plusSeconds(901));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedUnsafeAndInconsistentYamlIsPreservedWithSanitizedFailures() throws Exception {
|
||||
Files.createDirectories(data.resolve("sessions"));
|
||||
String valid = validYaml();
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
Files.writeString(record(), valid);
|
||||
assertEquals(BigInteger.valueOf(9), await(store.find(player)).orElseThrow().revision());
|
||||
for (String invalid : List.of(
|
||||
valid.replace("schema-version: 1", "schema-version: 2"),
|
||||
valid + "schema-version: 1\n",
|
||||
valid.replace("revision: '9'", "revision: '-1'"),
|
||||
valid.replace("revision: '9'", "revision: '01'"),
|
||||
valid.replace("revision: '9'", "revision: 1.5"),
|
||||
valid.replace(player.toString(), UUID.randomUUID().toString()),
|
||||
valid.replace(session.toString(), "1-1-1-1-1"),
|
||||
valid.replace(" prepared-at: '" + NOW + "'\n", ""),
|
||||
valid.replace(" character-id: " + character + "\n", ""),
|
||||
valid.replace("last-exit:\n session-id: " + session + "\n character-id: " + character,
|
||||
"last-exit:\n session-id: " + session + "\n character-id: " + UUID.randomUUID()),
|
||||
valid.replace(NOW.plusSeconds(901).toString(), NOW.toString()),
|
||||
valid.replace(NOW.toString(), "2000-02-30T00:00:00Z"),
|
||||
valid.replace(NOW.toString(), "2000-01-01T00:00:00+00:00"),
|
||||
valid.replace(NOW.toString(), "2000-01-01T24:00:00Z"),
|
||||
valid.replace(NOW.toString(), "2000-01-01T00:00:60Z"),
|
||||
valid + "unknown-recovery-authority: true\n",
|
||||
"pending: &receipt [*receipt]\n",
|
||||
"!!java.net.URL ['https://PRIVATE.invalid/']",
|
||||
"PRIVATE: [unterminated", "", valid + "---\n" + valid)) {
|
||||
Files.writeString(record(), invalid);
|
||||
for (CompletionStage<?> attempt : List.of(store.find(player), store.prepare(player, session, character),
|
||||
store.recordExit(player, session, Duration.ZERO), store.clearReceipt(player, session))) {
|
||||
Throwable error = failure(attempt);
|
||||
assertInstanceOf(IOException.class, error);
|
||||
assertFalse(error.toString().contains("PRIVATE"));
|
||||
assertNull(error.getCause(), "No parser snippets through nested exceptions");
|
||||
}
|
||||
assertEquals(invalid, Files.readString(record()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundsUtf8ReadsAndKeepsArbitraryPrecisionRevisionsExact() throws Exception {
|
||||
Files.createDirectories(data.resolve("sessions"));
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
for (byte[] invalid : List.of(new byte[] {(byte) 0xc3, 0x28}, "x".repeat(16_385).getBytes(java.nio.charset.StandardCharsets.UTF_8))) {
|
||||
Files.write(record(), invalid);
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertArrayEquals(invalid, Files.readAllBytes(record()));
|
||||
}
|
||||
BigInteger revision = BigInteger.TEN.pow(100);
|
||||
Files.writeString(record(), validYaml().replace("revision: '9'", "revision: '" + revision + "'"));
|
||||
assertEquals(revision, await(store.find(player)).orElseThrow().revision());
|
||||
assertEquals(revision.add(BigInteger.ONE), await(store.clearReceipt(player, session)).revision());
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(BigInteger.TEN.pow(100).add(BigInteger.ONE), await(reopened.find(player)).orElseThrow().revision());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundedWritesCannotReplaceALoadableRecordWithAnOversizedOne() throws Exception {
|
||||
Files.createDirectories(data.resolve("sessions"));
|
||||
String original = "schema-version: 1\nplayer-id: " + player + "\nrevision: '" + "9".repeat(16_200) + "'\n";
|
||||
Files.writeString(record(), original);
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertTrue(await(store.find(player)).isPresent(), "Input fits the bounded format");
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertEquals(original, Files.readString(record()));
|
||||
assertNull(await(store.find(player)).orElseThrow().pending());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnacknowledgedPostMoveFailureRetainsItsAmbiguousReceiptAndNeverReplaysOrDeletesIt() throws Exception {
|
||||
try (var uncertain = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
replace(source, target);
|
||||
throw new IOException("Failure after replacement; result uncertain to caller");
|
||||
})) {
|
||||
assertInstanceOf(IOException.class, failure(uncertain.prepare(player, session, character)));
|
||||
}
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofDays(1)))) {
|
||||
var retained = await(reopened.find(player)).orElseThrow();
|
||||
assertEquals(new EquipmentSessionStore.Receipt(session, character, NOW), retained.pending());
|
||||
assertEquals(BigInteger.ZERO, retained.revision());
|
||||
assertInstanceOf(IOException.class, failure(reopened.prepare(player, UUID.randomUUID(), character)));
|
||||
assertEquals(retained, await(reopened.prepare(player, session, character)));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void abortedPreparationCanBeClearedWithoutInventingAnExitAndDoesNotTouchCharacterFiles() throws Exception {
|
||||
Path characterFile = data.resolve("characters").resolve(character + ".yml");
|
||||
Files.createDirectories(characterFile.getParent());
|
||||
Files.writeString(characterFile, "existing character data is not this store's schema");
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
await(store.prepare(player, session, character));
|
||||
var cleared = await(store.clearReceipt(player, session)); // Test caller supplies never-packed proof.
|
||||
assertNull(cleared.pending());
|
||||
assertNull(cleared.lastExit());
|
||||
assertEquals(BigInteger.ONE, cleared.revision());
|
||||
assertEquals(cleared, await(store.clearReceipt(player, session)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertNotNull(await(store.prepare(player, UUID.randomUUID(), character)).pending());
|
||||
}
|
||||
assertEquals("existing character data is not this store's schema", Files.readString(characterFile));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicRecordsValidateMembersAndPairedSessionIdentity() {
|
||||
assertThrows(NullPointerException.class, () -> new EquipmentSessionStore.Receipt(session, null, NOW));
|
||||
assertThrows(NullPointerException.class, () -> new EquipmentSessionStore.Exit(session, character, null, NOW));
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.Exit(session, character, NOW, NOW.minusNanos(1)));
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.Receipt(session, character, Instant.MAX));
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.State(player, BigInteger.valueOf(-1), null, null));
|
||||
var receipt = new EquipmentSessionStore.Receipt(session, character, NOW);
|
||||
var wrongCharacter = new EquipmentSessionStore.Exit(session, UUID.randomUUID(), NOW, NOW);
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.State(player, BigInteger.ZERO, receipt, wrongCharacter));
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChecksUseSavedDeadlineNotNewConfigurationAndZeroOnlyBypassesTheDelay() throws Exception {
|
||||
EquipmentSessionStore.State exited;
|
||||
UUID other = UUID.randomUUID();
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var prepared = await(store.prepare(player, session, character));
|
||||
assertTrue(prepared.canEnter(other, Duration.ofSeconds(900), NOW));
|
||||
exited = await(store.recordExit(player, session, Duration.ofSeconds(900)));
|
||||
assertTrue(exited.canEnter(character, Duration.ofSeconds(900), NOW));
|
||||
assertFalse(exited.canEnter(other, Duration.ofSeconds(1), NOW.plusSeconds(899)));
|
||||
assertFalse(exited.canEnter(other, Duration.ofDays(7), NOW.plusSeconds(899)));
|
||||
assertTrue(exited.canEnter(other, Duration.ofDays(7), NOW.plusSeconds(900)));
|
||||
assertTrue(exited.canEnter(other, Duration.ZERO, NOW));
|
||||
assertFalse(exited.canEnter(other, Duration.ofSeconds(900), NOW), "Zero bypass does not erase saved deadline");
|
||||
assertThrows(IllegalArgumentException.class, () -> exited.canEnter(other, Duration.ofSeconds(-1), NOW));
|
||||
assertEquals(exited, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofDays(1)))) {
|
||||
assertTrue(await(reopened.find(player)).orElseThrow().canEnter(other, Duration.ofDays(7), NOW.plusSeconds(86400)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidDelaysFailUnchangedEvenForDuplicateExitsAndMissingSessionsAreNotInvented() throws Exception {
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, session)));
|
||||
assertTrue(await(store.find(player)).isEmpty());
|
||||
var prepared = await(store.prepare(player, session, character));
|
||||
for (Duration invalid : java.util.List.of(Duration.ofNanos(-1), Duration.ofSeconds(Long.MAX_VALUE),
|
||||
Duration.ofDays(4_000_000))) {
|
||||
failure(store.recordExit(player, session, invalid));
|
||||
assertEquals(prepared, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
var exited = await(store.recordExit(player, session, Duration.ZERO));
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
for (Duration invalid : java.util.List.of(Duration.ofNanos(-1), Duration.ofSeconds(Long.MAX_VALUE))) {
|
||||
failure(store.recordExit(player, session, invalid));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
assertEquals(exited, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
assertEquals(NOW, exited.lastExit().deadline());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void exitsRetainReceiptsUntilProvenRestorationAndDuplicatesNeverExtendDeadlines() throws Exception {
|
||||
EquipmentSessionStore.State cleared;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var prepared = await(store.prepare(player, session, character));
|
||||
assertEquals(prepared, await(store.prepare(player, session, character)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, UUID.randomUUID())));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, UUID.randomUUID(), character)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, UUID.randomUUID(), Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, UUID.randomUUID())));
|
||||
assertEquals(prepared, await(store.find(player)).orElseThrow());
|
||||
|
||||
var exited = await(store.recordExit(player, session, Duration.ofMinutes(15)));
|
||||
assertEquals(BigInteger.ONE, exited.revision());
|
||||
assertEquals(prepared.pending(), exited.pending(), "Exit is not proof of restoration");
|
||||
assertEquals(new EquipmentSessionStore.Exit(session, character, NOW, NOW.plusSeconds(900)), exited.lastExit());
|
||||
assertEquals(exited, await(store.recordExit(player, session, Duration.ofDays(1))));
|
||||
assertEquals(exited, await(store.prepare(player, session, character)));
|
||||
cleared = await(store.clearReceipt(player, session));
|
||||
assertEquals(BigInteger.TWO, cleared.revision());
|
||||
assertNull(cleared.pending());
|
||||
assertEquals(exited.lastExit(), cleared.lastExit());
|
||||
assertEquals(cleared, await(store.clearReceipt(player, session)));
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofHours(1)))) {
|
||||
assertEquals(cleared, await(reopened.recordExit(player, session, Duration.ofDays(7))));
|
||||
assertInstanceOf(IOException.class, failure(reopened.prepare(player, session, character)));
|
||||
UUID nextSession = UUID.randomUUID();
|
||||
var next = await(reopened.prepare(player, nextSession, character));
|
||||
assertEquals(BigInteger.valueOf(3), next.revision());
|
||||
assertEquals(cleared.lastExit(), next.lastExit());
|
||||
assertInstanceOf(IOException.class, failure(reopened.clearReceipt(player, session)));
|
||||
assertEquals(next, await(reopened.recordExit(player, session, Duration.ZERO)), "Old retry must not mutate new pending session");
|
||||
var nextExit = await(reopened.recordExit(player, nextSession, Duration.ofSeconds(30)));
|
||||
assertEquals(BigInteger.valueOf(4), nextExit.revision());
|
||||
assertEquals(NOW.plusSeconds(3630), nextExit.lastExit().deadline());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparationAcknowledgesRealVersionedYamlAndSurvivesReopen() throws Exception {
|
||||
EquipmentSessionStore.State saved;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertFalse(Files.exists(data.resolve("sessions")), "Constructor must defer disk IO");
|
||||
assertTrue(await(store.find(player)).isEmpty());
|
||||
saved = await(store.prepare(player, session, character));
|
||||
assertEquals(player, saved.playerId());
|
||||
assertEquals(BigInteger.ZERO, saved.revision());
|
||||
assertEquals(new EquipmentSessionStore.Receipt(session, character, NOW), saved.pending());
|
||||
assertNull(saved.lastExit());
|
||||
assertTrue(Files.isRegularFile(record()), "Acknowledgment follows persistence");
|
||||
String yaml = Files.readString(record());
|
||||
assertTrue(yaml.contains("schema-version: 1"));
|
||||
assertFalse(yaml.contains("!!"));
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(saved, await(reopened.find(player)).orElseThrow());
|
||||
}
|
||||
assertFalse(Files.exists(data.resolve("characters")), "Existing character storage is untouched");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class OrdinaryVitalsTest {
|
||||
@Test void canonicalOrdinarySnapshotRetainsExactHealthNutritionAndDisplayValues() {
|
||||
var value = new OrdinaryVitals(12.25, 7, 2.5f, 3.75f, false, 20);
|
||||
assertEquals(value, OrdinaryVitals.decode(value.encode()));
|
||||
var scaled = new OrdinaryVitals(1, 0, 0, 0, true, 44);
|
||||
assertEquals(scaled, OrdinaryVitals.decode(scaled.encode()));
|
||||
}
|
||||
|
||||
@Test void malformedNonfiniteNegativeAndNoncanonicalSnapshotsCannotAuthorizeRestoration() {
|
||||
for (String input : List.of("", "garbage", "x".repeat(300), "NaN;7;2.0;3.0;false;20.0",
|
||||
"Infinity;7;2.0;3.0;false;20.0", "-1.0;7;2.0;3.0;false;20.0", "12.0;-1;2.0;3.0;false;20.0",
|
||||
"12.0;21;2.0;3.0;false;20.0", "12.0;7;NaN;3.0;false;20.0", "12.0;7;2.0;-1.0;false;20.0",
|
||||
"12.0;7;2.0;Infinity;false;20.0", "12.0;7;2.0;3.0;yes;20.0", "12.0;7;2.0;3.0;false;0.0",
|
||||
"12;7;2.0;3.0;false;20.0", "12.0;7;2.0;3.0;false;20.0;extra")) {
|
||||
assertThrows(IllegalArgumentException.class, () -> OrdinaryVitals.decode(input), input);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,55 @@ class CharacterProgressTest {
|
||||
character.buyStat(before.characterId(), before.revision(), stat));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nativeHealthCeilingDoesNotCapConOrTurnFurtherPurchasesIntoHealing() {
|
||||
var character = new CharacterProgress(UUID.randomUUID(),
|
||||
new ProgressionRules(integer(2000), integer(100), 30));
|
||||
for (int i = 0; i < 1013; i++) buy(character, Stat.CON);
|
||||
character.recordHealth(new BigDecimal("1019.25")); // 3.75 health points missing
|
||||
buy(character, Stat.CON);
|
||||
assertEquals(new BigDecimal("1024"), character.snapshot().maximumHealth());
|
||||
assertEquals(new BigDecimal("1020.25"), character.snapshot().currentHealth());
|
||||
var before = character.snapshot();
|
||||
buy(character, Stat.CON);
|
||||
var capped = character.snapshot();
|
||||
assertEquals(new BigDecimal("1024"), capped.maximumHealth());
|
||||
assertEquals(before.currentHealth(), capped.currentHealth());
|
||||
assertEquals(integer(1015), capped.stats().get(Stat.CON));
|
||||
assertEquals(before.unspentPoints().subtract(BigInteger.ONE), capped.unspentPoints());
|
||||
assertEquals(CharacterProgress.Purchase.STALE_REVISION,
|
||||
character.buyStat(before.characterId(), before.revision(), Stat.CON));
|
||||
assertEquals(capped, character.snapshot());
|
||||
assertThrows(IllegalArgumentException.class, () -> character.recordHealth(new BigDecimal("1024.01")));
|
||||
assertEquals(capped, character.snapshot());
|
||||
}
|
||||
|
||||
@Test
|
||||
void suppliedNativeLimitAllowsPartialConGainAndZeroGainOnceReached() {
|
||||
var character = new CharacterProgress(UUID.randomUUID(), ProgressionRules.defaults(), new BigDecimal("10.5"));
|
||||
character.recordHealth(new BigDecimal("6.25"));
|
||||
buy(character, Stat.CON);
|
||||
assertEquals(new BigDecimal("10.5"), character.snapshot().maximumHealth());
|
||||
assertEquals(new BigDecimal("6.75"), character.snapshot().currentHealth());
|
||||
buy(character, Stat.CON);
|
||||
assertEquals(new BigDecimal("6.75"), character.snapshot().currentHealth());
|
||||
assertEquals(integer(2), character.snapshot().stats().get(Stat.CON));
|
||||
var low = new CharacterProgress(UUID.randomUUID(), ProgressionRules.defaults(), new BigDecimal("5"));
|
||||
assertEquals(new BigDecimal("5"), low.snapshot().maximumHealth());
|
||||
assertEquals(new BigDecimal("5"), low.snapshot().currentHealth());
|
||||
var higher = new CharacterProgress(UUID.randomUUID(),
|
||||
new ProgressionRules(integer(2000), integer(100), 30), new BigDecimal("2048"));
|
||||
for (int i = 0; i < 1015; i++) buy(higher, Stat.CON);
|
||||
assertEquals(new BigDecimal("1025"), higher.snapshot().maximumHealth());
|
||||
assertEquals(new BigDecimal("1025"), higher.snapshot().currentHealth());
|
||||
for (String invalid : new String[] {"0", "-1"}) {
|
||||
assertThrows(IllegalArgumentException.class, () -> new CharacterProgress(UUID.randomUUID(),
|
||||
ProgressionRules.defaults(), new BigDecimal(invalid)));
|
||||
}
|
||||
assertThrows(NullPointerException.class, () -> new CharacterProgress(UUID.randomUUID(),
|
||||
ProgressionRules.defaults(), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void conAddsItsGainToBothPoolsPreservingTheFiveOfSevenToSevenOfNineHeartExample() {
|
||||
var character = new CharacterProgress(UUID.randomUUID(), ProgressionRules.defaults());
|
||||
|
||||
Reference in new issue
Block a user