aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 23c0cc3adcc83bc5a3bdfe24f0e0074d1c31ee7a
parent bcfb6730bad957c92b94ed1ce165ba77cd7a968f
Author: anon <anon@example.com>
Date:   Mon,  2 Nov 2026 19:49:54 +0000

Apply original resurrection shock and restore cold weapon resources

Diffstat:
MTODO.md | 25++++++++++++++++++-------
Mdocs/insurance.md | 3++-
Mdocs/inventory.md | 33+++++++++++++++++++++++++--------
Mdocs/player-resurrection.md | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mdocs/reclaim.md | 5+++--
Mserver/browser_reclaim_weapon_test.go | 20++++++++++++++++++--
Mserver/database.go | 8+++++---
Mserver/main.go | 14++++++--------
Mserver/regeneration.go | 7+++++++
Mserver/regeneration_test.go | 3++-
Mserver/resurrection.go | 3+++
Aserver/resurrection_shock_test.go | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/resurrection_test.go | 4++--
Mserver/state.go | 1+
Mserver/stats.go | 11+++++++++--
Mserver/target_protocol_test.go | 2+-
Mserver/world.go | 1+
Mserver/world.sql | 3++-
Mserver/world_loading_test.go | 41+++++++++++++++++++++++++++++++++++++++++
Mtools/client/test_reclaim_weapon.mjs | 25++++++++++++++++++++++++-
20 files changed, 346 insertions(+), 42 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -3692,13 +3692,24 @@ and server restarts. Turn every reproduced bug into a focused regression test. rollback, shared ranged outcomes and resurrection without replay. Two native clients verified removal and return; historical persistent-nano exceptions remain open in [temporary nanos](docs/nano-buffs.md#death-and-resurrection). -- [ ] [P1] Recover and apply original resurrection-shock rules. The shipped - return reports temporarily reduced stats, but the current server restores - 1 HP/nano without applying a stat penalty. Recover the original modifier, - duration/recovery, level exceptions and equipment/resource consequences; - verify native/server agreement and cold expiry without inventing a blanket - reduction. The controlled weapon-reclaim check isolates item conservation - under current stats and does not establish canonical post-return eligibility. +- [ ] [P1] Finish resurrection-shock policy and observer replay. The original + level-15 onset (stat 247=5000), float32 reduction before direct bonuses, and + 27-per-two-second recovery now apply to server qualification/resources and + owner FullCharacter replay. Focused Go and short native death/reclaim checks + cover refusal, controlled late recovery, exact item retention and cold zero; + level 14/15 and active cold onset are covered in Go. Remaining completion + checks: recover original offline/dead/loading recovery policy and audit remote + skill/timing prediction without FullCharacter, including phase differences. + Do not infer these rules from the client-only timer or the expedited fixture. + Returned 1 HP/nano is still provisional. See + [resurrection shock](docs/player-resurrection.md#resurrection-shock). +- [x] [P0] Restore weapon-derived resource maxima after cold replay. A recovered + QL75 LIZARD displayed its +15 Psychic but left native maximum nano at 672 + instead of the server's 681. Publish final resource foundations after weapon + and nano replay, including without active nanos. A failing bootstrap-order + regression and a short native death/reclaim/recovery/cold check now verify + the correction without changing current resources or duplicating bonuses. + See [weapon reclaim](docs/inventory.md#retained-weapon-death-and-reclaim). - [ ] [P0] Audit corpse loot, credits and expiry. Cover entitled/unrelated players, simultaneous pickup, partial looting, full inventory, stale windows, expiry, repeat requests and persistence of both sides of each transfer. diff --git a/docs/insurance.md b/docs/insurance.md @@ -203,7 +203,8 @@ Socket writes occur outside the shared state mutex. A successful use completes GenericCmd and sends CharacterAction 79. Its last word now carries the saved cumulative XP into native stat 236. The preceding stat-49 word remains zero; its original time representation has not been -recovered. Fees and shock stat penalties remain separate work. [Private reclaim](reclaim.md) now +recovered. Fees remain open; [resurrection shock](player-resurrection.md#resurrection-shock) +now applies the recovered native calculation. [Private reclaim](reclaim.md) now handles ordinary inventory items from level 10 and prevents saving until all reclaim items are collected. Ordinary profile edits and teleports preserve the saved scanner. Unknown scanner identities in saved diff --git a/docs/inventory.md b/docs/inventory.md @@ -423,23 +423,40 @@ Native removal retains the same weapon in ordinary inventory and removes its reclaim; the native client performs its normal death return in playfield 705. The driver waits for the replacement world stream's actor readiness, picks the real reclaim booth and collects both rows through native clicks. The weapon's -returned inventory row then emits a real equip request and successfully equips. +returned inventory row initially refuses re-equip because resurrection shock +reduces Shotgun below its requirement. The native skills window shows reduced +red abilities (102 at the captured recovery phase). A controlled last-tick +checkpoint at reduction 27, followed by page replay and ordinary recovery, +avoids waiting six minutes. Once native and server reduction both reach zero, +the same inventory row emits a real equip request and successfully equips. Its FullUpdate carries stat 26=13, and the energy stack remains 100. Native skills show Psychic 215 from base 200, matching one server bonus of 15. After closing the original database, a fresh server and native client restore the same physical IDs, selected QL/endpoints, slots, quantities and ammunition. The worn weapon again arrives with 13 rounds and displays Psychic 215. Screenshots -were inspected; no native/page errors occurred. The complete warm/cold check -took 38.18s, with traces under `local/reclaim-weapon/20261102-112607/`. -Focused Reclaim/Resurrection/Vektor Go checks passed in 71.067s. This records a +were inspected; no native/page errors occurred. The shock-aware warm/cold check +took 50.87s, with traces under `local/reclaim-weapon/20261102-114547/`. +Focused Resurrection/Regeneration/Signed/Vektor Go checks passed in 76.118s. This records a necessary regression for the reported equipment-loss path; it found no additional production ownership defect and does not close the broader disappearance audit. -The native return text also advertises resurrection shock, while current server -return only restores 1 HP/nano. Original penalties, recovery and eligibility -remain a separate TODO; this fixture's successful re-equip does not establish -canonical qualification during shock. +The [resurrection-shock calculation](player-resurrection.md#resurrection-shock) +now applies to server qualification and resources and survives native replay. +Offline policy and observer timing prediction remain unresolved; the controlled +last-tick setup is not earned-progression or full-duration recovery evidence. + +The exact cold resource check reproduced a separate P0 replay defect. Psychic +displayed 215, but native maximum nano remained 672 instead of the server's 681, +even after ten seconds. FullCharacter rebuilds resources before the instantiated +weapon's later OnWear. Bootstrap only corrected maxima when active nanos existed, +and that correction preceded the weapon. It now publishes final resource +foundations after both replays for every owner. The native cold maximum reaches +681, matching the server; current resources and the bonus remain unchanged. +`TestWorldLoadingPublishesResourceFoundationsAfterWeaponReplay` failed before +the fix and now protects packet order and value. The final browser check waits +for actual derived-maxima agreement, rather than assuming actor readiness means +that all equipment effects have completed. ```sh AO_GAME_TEST=1 go test ./server -run '^TestBrowserReclaimWeapon$' -count=1 -timeout=4m -v diff --git a/docs/player-resurrection.md b/docs/player-resurrection.md @@ -28,8 +28,8 @@ Original addresses below use base `0x10000000`; generated C uses `0x36000000`. - The recovery helper clears the death presentation and enables visibility. For local actors it also invokes level-dependent reclaim/shock feedback: level 10 and higher takes the reclaim branch, and level 15 and higher takes - the resurrection-shock branch. These client branches do not establish the - original server's item transfer or stat penalty rules. + the resurrection-shock branch. The stat calculation is recovered below; + these branches do not establish the original server's item transfer policy. The fresh REA recovery-helper decompilation is evidence `ev_c2a370e32e75f900b6adc42b43d81fd62a5402a7380724acda44b335bc925c2d`; @@ -92,10 +92,73 @@ the return preserves resources and location while ordinary regeneration resumes. The supported scanner also protects saved XP, with classic uninsured loss committed alongside death; see [XP protection](insurance.md#classic-xp-protection). Other scanners, insurance fees -and resurrection shock stat penalties remain unimplemented. Ordinary inventory items now enter +remain open. Resurrection shock follows the recovered client calculation below. +Ordinary inventory items enter [private reclaim](reclaim.md) from level 10; equipment and NoDrop items remain with the player. See the [scanner evidence and limits](insurance.md). +## Resurrection shock + +Original `FUN_10053230` invokes `FUN_10076230` for local actors at level 15 +and above. It sets raw stat 247 and the skill controller's cached reduction +at offset `+0x2c` to 5000. FullCharacter application at `1007f4bf` restores +that cache from stat 247. Omitting the stat during return/reconnect therefore +erases the penalty even though the native return message announces it. + +`FUN_10074a30`, instructions `10074a77` through `10074aac`, subtracts the +following amount for abilities 16-21 and skills 100-168 only: + +```text +reduction(value) = trunc(shock * value * float32(0.0001)) +effective_ability = raw_ability - reduction(raw_ability) + direct_modifiers +skill_foundation = raw_skill + trunc(weighted_effective_abilities * float32(0.01) * 0.25) +effective_skill = skill_foundation - reduction(skill_foundation) + direct_modifiers +``` + +The scale at `101714e4` is bytes `17 b7 d1 38`, slightly below exact .0001. +For raw ability 200, initial shock subtracts 99, leaving 101. Direct modifiers +are added afterward. The reduced abilities also reduce skill trickle before +the skill's own penalty. This affects qualification, attack/timing inputs, +resource maxima and regeneration through their existing effective-stat getters; +it does not rewrite trained bases or remove retained equipment. + +Actor update `FUN_1006ea50` subtracts 27, with a zero floor, on the same +GameTime `+0x1d` phase as [two-second recovery](npc-regeneration.md#recovered-client-behavior). +Recovery takes 186 checks, about 370-372 seconds depending on the initial phase. +It updates stat 247 and refreshes native skills, resources and equipment checks. +The zero transition prints the original recovery-complete message. + +The server commits onset with the return's vitals and position, publishes stat +247 in FullCharacter, and advances the remaining value in memory on its existing +ready-player regeneration phase. Resource maxima refresh as the derived values +change. Periodic vitals checkpoints and ordinary disconnect saves retain the +remaining reduction; cold loading also preserves an already recovered zero. +Current policy pauses while offline/loading/dead, as with resource recovery. +The original server's offline policy and exact cross-client phase synchronization +remain evidence gaps. Remote actors do not receive FullCharacter, so observer +skill/timing prediction during shock still needs a separate protocol audit. +Returned 1 HP/1 nano remains provisional. + +Complete REA Evidence and limitations are retained under +`local/resurrection-shock/`: onset/replay `ev_42a219a257a8edb2ae8021f5f4dc15f541909d36e2f45cdbd6335b5a312a2cfe`, +getter/tick `ev_5a9675300fd6b8cfed2f1fc3cedc6fd28072f9329236147f36541601cd54ed41`, +modifier assembly `ev_c3dc476ddb84eedb69e4e81bbbd80a7c5bf28e3aca92e4d8e2e0386d6813ad6f`, +and scale bytes `ev_bea04c6411ffc7716565942de8d22ff624f6b9713f0cfd08944999359441115e`. +These are static observations of the shipped DLL, not historical server captures. +The extracted original getters also pass the same eight added shock cases on +Linux and WASM, covering initial reduction, boosted trickle, direct modifiers +and the final rounding boundary. This controlled getter fixture substitutes +container lookup/notification boundaries; it does not execute a complete client. + +`server/resurrection_shock_test.go` covers level 14/15, durable onset, exact +arithmetic, qualification, resources, phase/decrement/floor, checkpoint cadence +and cold recovered state. The resurrection save-failure regression also checks +that a failed level-15 return applies no live penalty. The short maintained +[weapon-reclaim check](inventory.md#retained-weapon-death-and-reclaim) covers +native onset, refusal, replay, recovery and retained equipment. It also exposed +and fixed a persistent nine-point cold nano-maximum gap: final resource +foundations now follow held-weapon replay even without active nanos. + ## Verification `server/initial_resurrection_test.go` covers all three affiliations, authored diff --git a/docs/reclaim.md b/docs/reclaim.md @@ -22,8 +22,9 @@ The collection delay is provisionally 75 seconds from the killing blow. This uses the native DeadTimer fallback, not a recovered historical server timer. Uncollected items accumulate across deaths without expiry; each keeps its own availability time. Those repeated-death and retention policies are also -provisional. XP insurance, uninsured/PvP corpse loot, backpacks and resurrection -shock penalties are separate work. +provisional. XP insurance, uninsured/PvP corpse loot and backpacks are separate +work. [Resurrection shock](player-resurrection.md#resurrection-shock) applies +the recovered native penalty and online recovery calculation. ## Shipped rules and placement diff --git a/server/browser_reclaim_weapon_test.go b/server/browser_reclaim_weapon_test.go @@ -60,7 +60,8 @@ func TestBrowserReclaimWeapon(t *testing.T) { world.mutex.Lock() defer world.mutex.Unlock() json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "health": player.health, - "playfield": player.playfield, "psychic": player.equipmentBonus(21)}) + "playfield": player.playfield, "psychic": player.equipmentBonus(21), "shock": player.resurrectionShock, + "effective_psychic": player.effectiveAbility(21), "maximum_health": player.maximumHealth(), "maximum_nano": player.maximumNano()}) } mux.HandleFunc("GET /test-state", testState) mux.HandleFunc("POST /test-fatal-hit", func(w http.ResponseWriter, r *http.Request) { @@ -92,6 +93,20 @@ func TestBrowserReclaimWeapon(t *testing.T) { } w.WriteHeader(http.StatusNoContent) }) + mux.HandleFunc("POST /test-last-shock-tick", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + defer world.mutex.Unlock() + // A controlled late-recovery checkpoint avoids six minutes of waiting. + player.resurrectionShock = 27 + if err := world.savePosition_locked(player); err != nil { + t.Error(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + }) host := httptest.NewServer(mux) defer host.Close() closeTestBrowserStreams(t, world) @@ -106,6 +121,7 @@ func TestBrowserReclaimWeapon(t *testing.T) { select { case now := <-ticker.C: world.advanceEquipment(now) + world.advanceRegeneration(now) case <-ctx.Done(): return } @@ -132,7 +148,7 @@ func TestBrowserReclaimWeapon(t *testing.T) { } cold := newServer() defer cold.db.Close() - if !slices.Equal(player.inventory.Items, cold.characters[1].inventory.Items) || len(cold.characters[1].inventory.Reclaim) != 0 || cold.characters[1].equipmentBonus(21) != 15 { + if !slices.Equal(player.inventory.Items, cold.characters[1].inventory.Items) || len(cold.characters[1].inventory.Reclaim) != 0 || cold.characters[1].equipmentBonus(21) != 15 || cold.characters[1].resurrectionShock != 0 { t.Fatal("cold recovery changed the reclaimed weapon, ammunition or Psychic bonus") } world, player = cold, cold.characters[1] diff --git a/server/database.go b/server/database.go @@ -63,6 +63,7 @@ type playerVitals struct { NanoRechargeUntil time.Time `yaml:"nano_recharge_until"` RegenerationAt time.Time `yaml:"regeneration_at"` RegenerationSeconds uint32 `yaml:"regeneration_seconds"` + ResurrectionShock uint32 `yaml:"resurrection_shock"` } func (character *character) profile() playerProfile { @@ -76,7 +77,7 @@ func (character *character) profile() playerProfile { func (character *character) vitals() playerVitals { return playerVitals{character.health, character.nano, character.nanoReserved, character.sitting, character.aggDef, - character.rechargeUntil, character.nanoRechargeUntil, character.regenerationAt, character.regenerationSeconds} + character.rechargeUntil, character.nanoRechargeUntil, character.regenerationAt, character.regenerationSeconds, character.resurrectionShock} } func (character *character) applyVitals(vitals playerVitals) { @@ -84,11 +85,12 @@ func (character *character) applyVitals(vitals playerVitals) { character.nanoReserved = vitals.NanoReserved character.rechargeUntil, character.nanoRechargeUntil = vitals.RechargeUntil, vitals.NanoRechargeUntil character.regenerationAt, character.regenerationSeconds = vitals.RegenerationAt, vitals.RegenerationSeconds + character.resurrectionShock = vitals.ResurrectionShock } // Character records contain scalar SQL values, including each trained skill. const positionColumns = "playfield, position_x, position_y, position_z, rotation_x, rotation_y, rotation_z, rotation_w, return_playfield, return_door" -const vitalColumns = "health, nano, nano_reserved, sitting, agg_def, recharge_until, nano_recharge_until, regeneration_at, regeneration_seconds" +const vitalColumns = "health, nano, nano_reserved, sitting, agg_def, recharge_until, nano_recharge_until, regeneration_at, regeneration_seconds, resurrection_shock" const characterColumns = profileColumns + ", " + positionColumns + ", " + vitalColumns type storedPosition struct { @@ -114,7 +116,7 @@ func (position storedPosition) editor() playerPosition { func (vitals *playerVitals) fields() []any { return []any{&vitals.Health, &vitals.Nano, &vitals.NanoReserved, &vitals.Sitting, &vitals.AggDef, &vitals.RechargeUntil, - &vitals.NanoRechargeUntil, &vitals.RegenerationAt, &vitals.RegenerationSeconds} + &vitals.NanoRechargeUntil, &vitals.RegenerationAt, &vitals.RegenerationSeconds, &vitals.ResurrectionShock} } type characterRecord struct { diff --git a/server/main.go b/server/main.go @@ -408,15 +408,13 @@ func (server *server) serveWorldClient(client *worldClient) error { updates = append(updates, missionJournalPacket(mission, time.Now())) } updates = append(updates, activeNanoPackets(character, time.Now())...) - if len(character.activeNanos) != 0 { - // FullCharacter recomputes maxima before the later ability replay. - for _, stat := range [][2]uint32{{1, character.maximumHealth() - uint32(character.equipmentBonus(1)+character.nanoBonus(1))}, {221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}} { - body := binary.BigEndian.AppendUint32(nil, stat[0]) - body = binary.BigEndian.AppendUint32(body, stat[1]) - updates = append(updates, n3Packet(0x2b333d6e, 50000, character.id, body)) - } - } updates = append(updates, equippedWeaponPackets(character)...) + // FullCharacter rebuilds maxima before the later nano/weapon OnWear replay. + for _, stat := range [][2]uint32{{1, character.maximumHealth() - uint32(character.equipmentBonus(1)+character.nanoBonus(1))}, {221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}} { + body := binary.BigEndian.AppendUint32(nil, stat[0]) + body = binary.BigEndian.AppendUint32(body, stat[1]) + updates = append(updates, n3Packet(0x2b333d6e, 50000, character.id, body)) + } updates = append(updates, server.combatInterest_locked(client, nil)...) if client.target { if err := server.ensureWorldResources_locked(character.playfield); err != nil { diff --git a/server/regeneration.go b/server/regeneration.go @@ -47,6 +47,13 @@ func (server *server) advanceRegeneration(now time.Time) { continue } + // kkr.dll FUN_1006ea50 recovers shock on the same two-second phase. + if player.resurrectionShock > 0 { + previous := *player + player.resurrectionShock = max(27, player.resurrectionShock) - 27 + server.finishResourceChange_locked(updates, player, previous, now) + } + // kkr.dll FUN_10074560 / FUN_1006ea50, with the native float reciprocal. stats := player.baseStats() healthInterval, nanoInterval := player.regenerationIntervals() diff --git a/server/regeneration_test.go b/server/regeneration_test.go @@ -122,6 +122,7 @@ func TestRegenerationSkipsDeadLoadingOfflineAndNPCCharacters(t *testing.T) { t.Run(scenario, func(t *testing.T) { world, conn, start := newRegenerationWorld(t) world.clients[1].regenerationSeconds = 810 + world.characters[1].resurrectionShock = 5000 switch scenario { case "dead": world.characters[1].health = 0 @@ -138,7 +139,7 @@ func TestRegenerationSkipsDeadLoadingOfflineAndNPCCharacters(t *testing.T) { world.advanceRegeneration(start.Add(2 * time.Second)) - if world.characters[1].health != health || world.characters[1].nano != 0 || len(conn.packets) != 0 { + if world.characters[1].health != health || world.characters[1].nano != 0 || world.characters[1].resurrectionShock != 5000 || len(conn.packets) != 0 { t.Fatalf("%s regenerated: %+v packets=%x", scenario, world.characters[1], conn.packets) } }) diff --git a/server/resurrection.go b/server/resurrection.go @@ -51,6 +51,9 @@ func (server *server) handleResurrection(client *worldClient, body []byte) error updated.nextAttack = time.Time{} updated.rechargeUntil = time.Time{} updated.nanoRechargeUntil = time.Time{} + if player.level >= 15 { + updated.resurrectionShock = 5000 + } if err := server.savePosition_locked(&updated); err != nil { server.mutex.Unlock() return err diff --git a/server/resurrection_shock_test.go b/server/resurrection_shock_test.go @@ -0,0 +1,110 @@ +package main + +import ( + "fmt" + "testing" + "time" +) + +func TestResurrectionShockMatchesOriginalGetter(t *testing.T) { + player := &character{stats: testCharacterStats(), resurrectionShock: 5000} + player.stats.Abilities = characterAbilitiesStats{200, 200, 200, 200, 200, 200} + player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{21, 15}, {162, 20}}) + + ability := player.effectiveAbility(21) + skill := player.effectiveSkill(162, 300, [6]uint32{0, 0, 0, 0, 0, 100}) + player.resurrectionShock = 27 + lastAbility := player.effectiveAbility(21) + lastSkill := player.effectiveSkill(162, 300, [6]uint32{0, 0, 0, 0, 0, 100}) + + if ability != 116 || skill != 185 || lastAbility != 215 || lastSkill != 373 || player.stats.Abilities.Psychic != 200 { + t.Fatalf("native reduction/trickle/direct bonuses: %d/%d, final %d/%d", ability, skill, lastAbility, lastSkill) + } +} + +func TestResurrectionShockStartsAtLevelFifteenAndPersists(t *testing.T) { + for _, level := range []uint16{14, 15} { + t.Run(fmt.Sprint(level), func(t *testing.T) { + t.Chdir(t.TempDir()) + world, _ := newCombatWorld(t) + loadResurrectionLocations(t, world) + player := world.characters[1] + player.name, player.appearance = "Shock", 0x515 + player.level, player.health = level, 0 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + + if err := world.handleResurrection(world.clients[1], resurrectionRequest(1)[20:]); err != nil { + t.Fatal(err) + } + cold := newServer() + defer cold.db.Close() + + want := uint32(0) + if level == 15 { + want = 5000 + } + if player.resurrectionShock != want || cold.characters[1].resurrectionShock != want || cold.characters[1].health != 1 { + t.Fatal("resurrection lost the level gate or durable onset") + } + }) + } +} + +func TestResurrectionShockRecoversOnNativePhaseAndCheckpoints(t *testing.T) { + t.Chdir(t.TempDir()) + world, _, start := newRegenerationWorld(t) + player := world.characters[1] + player.name, player.appearance = "Shock", 0x515 + player.rotation = [4]float32{0, 0, 0, 1} + player.resurrectionShock = 5000 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + + world.advanceRegeneration(start.Add(2*time.Second - time.Nanosecond)) + if player.resurrectionShock != 5000 { + t.Fatal("shock recovered before the two-second phase") + } + world.advanceRegeneration(start.Add(2 * time.Second)) + if player.resurrectionShock != 4973 || player.savedVitals.ResurrectionShock != 5000 { + t.Fatal("shock tick changed its decrement or persisted simulation state immediately") + } + for second := 4; second <= 370; second += 2 { + world.advanceRegeneration(start.Add(time.Duration(second) * time.Second)) + } + if player.resurrectionShock != 5 { + t.Fatal("shock reached zero before the 186th check") + } + world.advanceRegeneration(start.Add(372 * time.Second)) + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + cold := newServer() + defer cold.db.Close() + + if player.resurrectionShock != 0 || cold.characters[1].resurrectionShock != 0 { + t.Fatal("shock underflowed or returned after a cold load") + } +} + +func TestResurrectionShockBlocksWeaponQualificationUntilRecovery(t *testing.T) { + player := &character{level: 100, profession: 7, stats: testCharacterStats()} + player.stats.Abilities = characterAbilitiesStats{200, 200, 200, 200, 200, 200} + player.stats.Ranged.Shotgun = 300 + item := ownedItem{Type: 51018, Template: 124261, Quality: 75} + if !player.canEquip(item) { + t.Fatal("unpenalized control cannot equip the weapon") + } + maximumHealth, maximumNano := player.maximumHealth(), player.maximumNano() + + player.resurrectionShock = 5000 + canEquip := player.canEquip(item) + health, nano := player.maximumHealth(), player.maximumNano() + player.resurrectionShock = 0 + + if canEquip || !player.canEquip(item) || health >= maximumHealth || nano >= maximumNano || player.maximumHealth() != maximumHealth || player.maximumNano() != maximumNano { + t.Fatal("shock did not affect qualification and restore derived resources") + } +} diff --git a/server/resurrection_test.go b/server/resurrection_test.go @@ -165,12 +165,12 @@ func TestResurrectionSaveFailureLeavesDeadCharacterAndSessionUnchanged(t *testin if err := os.WriteFile("data", nil, 0600); err != nil { t.Fatal(err) } - world.characters[1].health = 0 + world.characters[1].health, world.characters[1].level = 0, 15 client := world.clients[1] err := world.handleResurrection(client, resurrectionRequest(1)[20:]) - if err == nil || len(conn.packets) != 0 || world.characters[1].health != 0 || world.characters[1].playfield != 950 || world.clients[1] != client || !client.ready { + if err == nil || len(conn.packets) != 0 || world.characters[1].health != 0 || world.characters[1].resurrectionShock != 0 || world.characters[1].playfield != 950 || world.clients[1] != client || !client.ready { t.Fatal("failed save partially resurrected the player") } } diff --git a/server/state.go b/server/state.go @@ -58,6 +58,7 @@ type character struct { browserTokenHash string resurrectionTerminal uint32 + resurrectionShock uint32 implantChangesUntil time.Time nanoRechargeUntil time.Time skillLocks map[uint32]time.Time diff --git a/server/stats.go b/server/stats.go @@ -161,7 +161,8 @@ func (character *character) baseStats() characterStats { func (character *character) effectiveAbility(stat uint32) int32 { abilities := character.baseStats().Abilities values := [6]uint16{abilities.Strength, abilities.Agility, abilities.Stamina, abilities.Intelligence, abilities.Sense, abilities.Psychic} - return int32(values[stat-16]) + character.inventory.equipmentBonus(stat) + character.nanoBonus(stat) + base := int32(values[stat-16]) + return base - character.shockReduction(base) + character.inventory.equipmentBonus(stat) + character.nanoBonus(stat) } func (character *character) effectiveSkill(stat uint32, base uint16, weights [6]uint32) int32 { @@ -171,7 +172,13 @@ func (character *character) effectiveSkill(stat uint32, base uint16, weights [6] weighted += character.effectiveAbility(16+uint32(index)) * int32(weight) } // Preserve the native float constants before truncating at integer boundaries. - return int32(base) + int32(float64(weighted)*float64(float32(0.01))*0.25) + character.equipmentBonus(stat) + character.nanoBonus(stat) + value := int32(base) + int32(float64(weighted)*float64(float32(0.01))*0.25) + return value - character.shockReduction(value) + character.equipmentBonus(stat) + character.nanoBonus(stat) +} + +func (character *character) shockReduction(base int32) int32 { + // kkr.dll FUN_10074a30 scales the unmodified value using float32 .0001. + return int32(float64(character.resurrectionShock) * float64(base) * float64(float32(0.0001))) } type trainedStat struct { diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -113,7 +113,7 @@ initialized: if hex.EncodeToString(npc[60:89]) != "000005cb0b456469746564204e50430000000000000000000000000007" { t.Fatalf("target NPC appearance, name and new stats: %x", npc[60:89]) } - if hex.EncodeToString(full[57:105]) != "000003f100018e150000003600000001000000340000000000000039000000000000015e000005aa000000ec00000000" { + if hex.EncodeToString(full[57:105]) != "000003f1000192060000003600000001000000340000000000000039000000000000015e000005aa000000ec00000000" { t.Fatalf("target seventh list and initial progression/insurance stats: %x", full[57:105]) } if hex.EncodeToString(full[105:121]) != "0000003e000000000000004b00000000" { diff --git a/server/world.go b/server/world.go @@ -249,6 +249,7 @@ func fullCharacterPacket(character *character) []byte { [2]uint32{27, character.health}, [2]uint32{1, character.maximumHealth() - uint32(character.equipmentBonus(1)+character.nanoBonus(1))}, [2]uint32{37, character.titleLevel()}, [2]uint32{368, uint32(max(1, character.profession))}, [2]uint32{51, uint32(character.aggDef)}, [2]uint32{61, character.inventory.Credits}, + [2]uint32{247, character.resurrectionShock}, [2]uint32{47, uint32(character.appearance >> 2 & 3)}, [2]uint32{360, uint32(scale)}, [2]uint32{214, character.nano}, [2]uint32{221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}) diff --git a/server/world.sql b/server/world.sql @@ -124,7 +124,8 @@ CREATE TABLE IF NOT EXISTS characters ( recharge_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00', nano_recharge_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00', regeneration_at DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00', - regeneration_seconds INTEGER NOT NULL DEFAULT 0 + regeneration_seconds INTEGER NOT NULL DEFAULT 0, + resurrection_shock INTEGER NOT NULL DEFAULT 0 ); CREATE UNIQUE INDEX IF NOT EXISTS player_login_names ON characters(name COLLATE NOCASE) WHERE length(password_hash)>0; CREATE TABLE IF NOT EXISTS players ( diff --git a/server/world_loading_test.go b/server/world_loading_test.go @@ -3,10 +3,51 @@ package main import ( "bytes" "encoding/binary" + "net" "testing" "time" ) +func TestWorldLoadingPublishesResourceFoundationsAfterWeaponReplay(t *testing.T) { + world := newTestServer(t) + player := world.newCharacter() + player.level, player.profession, player.appearance = 100, 7, 0x515 + player.stats.Abilities = characterAbilitiesStats{200, 200, 200, 200, 200, 200} + player.inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: 124261, Quality: 75, Slot: 6, Count: 1}} + client, connection := net.Pipe() + defer client.Close() + client.SetDeadline(time.Now().Add(5 * time.Second)) + go func() { defer connection.Close(); world.serveWorldConnection(connection) }() + + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + binary.BigEndian.PutUint16(cookie, 0xdfdf) + if _, err := client.Write(cookie); err != nil { + t.Fatal(err) + } + weaponSeen := false + stats := make(map[uint32]uint32) + for { + packet, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + key := binary.BigEndian.Uint32(packet[16:20]) + if key == 0x3b1d2268 { + weaponSeen = true + } + if weaponSeen && key == 0x2b333d6e { + stats[binary.BigEndian.Uint32(packet[29:33])] = binary.BigEndian.Uint32(packet[33:37]) + } + if key == 0x5f52412e { + break + } + } + + if !weaponSeen || stats[1] != 872 || stats[221] != 681 { + t.Fatalf("weapon-derived resource foundations were not replayed last: %v", stats) + } +} + func TestWorldLoadingObserverReceivesPeriodicLifecycleAfterActorSnapshot(t *testing.T) { for _, lethal := range []bool{false, true} { t.Run(map[bool]string{false: "expiry", true: "death"}[lethal], func(t *testing.T) { diff --git a/tools/client/test_reclaim_weapon.mjs b/tools/client/test_reclaim_weapon.mjs @@ -35,6 +35,10 @@ try { assert.equal(dead.playfield, 705); assert.equal(dead.inventory.Reclaim.length, 2); assert.equal(dead.inventory.Reclaim.find(entry => entry.Item.ID === 1).Item.Ammo, 13); + assert(dead.shock > 4500 && dead.shock <= 5000); + assert(dead.effective_psychic >= 101 && dead.effective_psychic < 115); + assert(game.local().stats[247] > 4500 && game.local().stats[247] <= 5000); + assert.equal(game.local().stats[21], 200); assert.equal((await page.request.post(url + '/test-ready-reclaim')).status(), 204); const [x, y] = await game.pick(51059, 3221881537); await game.click(x, y, 'right'); @@ -47,11 +51,28 @@ try { await game.click(170, 8); if (!game.state.regions.some(region => region[0] === 654 && region[1] === 0 && region[2] === 832 && region[3] === 182)) await game.key('KeyI'); await game.save(output + '/collected'); + const attempt = game.sequence; + await game.click(681, 45, 'right'); + await game.save(output + '/shock-rejected'); + assert(!game.events.some(event => event.sequence > attempt && event.direction === 'framesent' && event.opcode === '47537a24')); + assert.equal((await state()).inventory.Items.find(item => item.ID === 1).Slot, 64); + await game.key('KeyU'); + await game.save(output + '/shock-skills'); + + // Replay a controlled last-tick checkpoint, then observe native/server expiry. + assert.equal((await page.request.post(url + '/test-last-shock-tick')).status(), 204); + await page.reload(); + await game.ready(); + await game.wait('native shock recovers', snapshot => game.local(snapshot).stats[247] === 0); + await page.waitForFunction(async () => (await (await fetch('/test-state')).json()).shock === 0); + await game.key('KeyI'); await game.click(681, 45, 'right'); await game.wait('reclaimed native weapon equips again', snapshot => game.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 6)); } const final = await state(); assert.equal(final.psychic, 15); + assert.equal(final.shock, 0); + assert.equal(final.effective_psychic, 215); assert.equal(final.inventory.Items.find(item => item.ID === 1).Ammo, 13); assert.equal(final.inventory.Items.find(item => item.ID === 2).Count, 100); assert.equal(final.inventory.Reclaim, null); @@ -60,6 +81,8 @@ try { ]); await game.wait('loaded reclaimed weapon delivered', () => game.events.some(event => event.direction === 'framereceived' && event.opcode === '3b1d2268' && event.actor[1] === 1)); + await game.wait('derived resource maxima restored', snapshot => game.local(snapshot).stats[1] === final.maximum_health && + game.local(snapshot).stats[221] === final.maximum_nano); const event = game.events.findLast(event => event.direction === 'framereceived' && event.opcode === '3b1d2268' && event.actor[1] === 1); const packet = Buffer.from(event.hex, 'hex'); const stats = new Map(); @@ -68,7 +91,7 @@ try { await game.key('KeyU'); await game.save(output + '/psychic'); assert.equal(game.errors.length, 0); - console.log('PASS:', phase, 'same instantiated weapon, 13 loaded/100 carried rounds and exactly-once Psychic bonus after death/reclaim'); + console.log('PASS:', phase, 'reclaimed weapon, ammunition, recovered stats and exactly-once Psychic bonus'); } finally { try { await game.save(output + '/final'); } finally { await browser.close(); }