aorecomp

Anarchy Online classic in the browser

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


commit 3bce13d226421753e7c68c5cf1db8ff45b987f6c
parent 38166f031c69121596285acbd12fe58003fddcb2
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 05:21:24 +0000

Publish NPC combat recovery without discarding queued hits

Diffstat:
MTODO.md | 13+++++++++++--
Mdocs/npc-regeneration.md | 62++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mdocs/weapon-hit-chance.md | 11++++++-----
Aserver/browser_npc_recovery_test.go | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/npc_regeneration.go | 9++++++++-
Mserver/npc_regeneration_test.go | 46+++++++++++++++++++++++++++++++++++++++++-----
Atools/client/test_npc_recovery.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 296 insertions(+), 27 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1132,6 +1132,14 @@ for exact records, protocol, tests and remaining reconstruction assumptions. Quiet corrections reconcile the clients' distinct prediction phases, with at most one idle recovery tick of drift in the native capture. Species balance and modified recovery inputs remain separate work. +- [x] [P0] Prevent false-zero NPC HP after authoritative combat recovery. + The recorded ordinary fight displayed zero HP before the real final hit after + a three-point server recovery tick. Two controlled native clients reproduce + that withheld update and now retain HP8 through the included pending hit, + then HP3 after the later hit until the real final death. Actual recovery + publishes without changing result queues, attack deadlines or feedback; + unchanged combat HP remains quiet. Independent prediction phases and original + server cadence remain separate gaps; see [NPC recovery](docs/npc-regeneration.md). - [ ] [P2] Support changed NPC recovery inputs. Check: evidenced HealInterval, HealDelta, Body Development, RestModifier, stat 519 and recovery-disable flags affect both server recovery and native prediction consistently, including @@ -3798,8 +3806,9 @@ and server restarts. Turn every reproduced bug into a focused regression test. matching displayed HP or safe correction during combat. The ordinary hit/miss mission trace also showed native NPC HP0 1.757 seconds before the authoritative final three-damage/death packet, after a server - combat recovery tick. Preserve that concrete case in the recovery-phase - audit; see [hit/miss native verification](docs/weapon-hit-chance.md#native-verification). + combat recovery tick. The focused withheld-recovery fix above now reproduces + and resolves that failure; broader prediction-phase comparisons remain open. + See [hit/miss native verification](docs/weapon-hit-chance.md#native-verification). - [ ] [P1] Audit ranged ammunition and reload. Cover empty/partial/full magazines, matching/wrong/missing ammunition, insufficient stacks, repeated reloads, reload during each attack phase, failed saves and round conservation across diff --git a/docs/npc-regeneration.md b/docs/npc-regeneration.md @@ -73,22 +73,31 @@ checkpoints. Restart restores checkpointed NPC HP with a fresh recovery clock; it does not replay offline healing. Significant Fling damage outcomes commit immediately, as described in [Fling Shot](fling-shot.md). -Quiet health corrections use the existing zero-feedback HealthDamage packet. -They reach only ready observers that already know the NPC in its playfield. -Corrections wait while the NPC or any weapon attacker targeting it is fighting, -so queued animation damage cannot subtract twice. StopFight precedes the next -quiet correction. Combat prediction phases can differ between clients and -the server; the subsequent quiet correction reconciles the display. +Health corrections use the existing zero-feedback HealthDamage packet. They +reach only ready observers that already know the NPC in its playfield. An actual +recovery change publishes immediately, including during combat. Otherwise quiet +periodic corrections still wait while the NPC or an attacker targeting it is +fighting. No unchanged combat HP update is added. + +The maintained HealthDamage receiver in +`client/game/kkr.dll/lifted-0052.c::sub_360B0A50` records which received weapon +results the absolute HP already includes. Those results retain their damage, +animation, feedback and ammunition, but do not debit HP again at impact. Later +hits still apply normally. A committed recovery therefore reaches both clients +without stopping an attacker or discarding its queued results. These updates do +not synchronize independent client recovery phases or establish the original +server's publication cadence. Original holder stop `10079250` drains all queued weapon results against its current resolved target through `100ab5a0`, then clears its special-action queue. Stopping the NPC drains its outgoing results, not the player's hits -against it. Safe correction requires the relevant attackers' stops to precede -the correction, matching targets and no later result from that engagement. -HealthDamage itself assigns HP without draining results or resetting recovery. -Missing or changed targets and healing/inspection during combat remain separate -ordering questions. The exact source ledger, retained records and generated -message bodies are in `local/npc-regeneration-research/native-followup/`. +against it. Periodic quiet corrections retain this stop-before-snapshot ordering, +with matching targets and no later result from that engagement. +The original HealthDamage body assigns HP without draining results or resetting +recovery; the maintained reconciliation above accounts for received outcomes. +Missing or changed targets remain separate ordering questions. The exact source +ledger, retained records and generated message bodies are in +`local/npc-regeneration-research/native-followup/`. Admitted NPC profiles now retain engagement outside their weapon range, including fixed spawns. Repeatedly stopping and restarting a ranged target had selected @@ -107,6 +116,31 @@ they are not substitutes for that missing evidence. ## Verification +### Combat recovery before weapon impact + +`TestBrowserNPCCombatRecovery` reproduces the recorded false-zero target HP +with two controlled native clients. An injured Leet begins at10 HP. Both players +receive its ordinary combat start and baseline HP, avoiding unrelated idle +prediction during login. The owner's real Q attack delivers a normal5-point +hit. A controlled scheduler phase then executes one real3-point combat recovery +while that result is pending. A second normal hit leaves authoritative HP3. +Previously both clients reached HP0 because the recovery update was withheld. + +The actual recovery now reaches both clients at HP8 while the first result +remains unchanged in each queue. Its impact retains8; the later hit leaves3. +Both server attack/recharge deadlines and engagements are unchanged by recovery. +A third real hit commits death and creates the native corpse on both clients. +No extra recovery feedback, attack cancellation or result is added. This verifies +publication and reconciliation, not earned progression or recovery cadence. +Captures: `local/npc-combat-recovery/20261102-211705/`. + +Public scheduler regressions cover actual combat recovery, incoming-only combat, +both observers, unchanged clocks/phase, zero-feedback bytes and no duplicate +publication on repeated visits. Existing quiet corrections, readiness/interest, +clamping and periodic checkpoint behavior remain covered. + +### Recovery rates and quiet reconciliation + Focused tests cover idle/combat rates, the native maximum-health division boundaries, clamping, scheduler jitter/backlogs, repeated visits, disengagement ordering, incoming weapon queues, observer interest/readiness, @@ -164,8 +198,8 @@ Two-client checks delivered the same seven-point special, taking the Reet from 100 to 93 HP. After the attacker's disconnect/reconnect ended retaliation, both native heaps and the database reached 100. A separate combat capture confirmed that clients can predict their three-point combat ticks at different -phases; this remains reconciled after combat rather than by interrupting weapon -queues with absolute HP updates. +phases. Actual server recovery now publishes through the reconciled snapshot +above; subsequent quiet corrections still settle the remaining prediction drift. For idle verification the attacker moved beyond the Reet's melee range before firing a nine-point special. Both native heaps showed 91, 92 and 93 HP, then diff --git a/docs/weapon-hit-chance.md b/docs/weapon-hit-chance.md @@ -119,13 +119,14 @@ damage contribution was granted. These deliberate fixture stats establish protocol behavior rather than historical NPC balance. All browser checks used the GPU and reported no page errors or unimplemented adapters. -The ordinary trace also preserves the existing NPC recovery-phase limitation. +The ordinary trace also preserves the false-zero NPC recovery baseline. Four targets required 103 authoritative damage, including a three-point combat recovery tick. One target displayed zero native HP 1.757 seconds before the -server's final three-damage/death packet. This does not establish NPC HP -agreement during combat; the broader [recovery audit](npc-regeneration.md) -remains open. Player HP agreement and controlled zero-damage miss delivery -were checked independently. Evidence is under `local/hit-miss-smoke/` and +server's final three-damage/death packet. A focused two-client regression now +reproduces and fixes the withheld authoritative recovery through pending impacts; +see [combat recovery](npc-regeneration.md#combat-recovery-before-weapon-impact). +Independent prediction phases remain open. Player HP agreement and zero-damage +miss delivery were checked independently. Evidence is under `local/hit-miss-smoke/` and `local/hit-miss-controlled/`, including `native-verified.json`. The complete maintained Go suite passed: 1,664 top-level tests and 16,385 diff --git a/server/browser_npc_recovery_test.go b/server/browser_npc_recovery_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserNPCCombatRecovery(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for NPC recovery with queued weapon hits") + } + + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/npc-combat-recovery", time.Now().Format("20060102-150405")) + world := newTestServer(t) + var npc *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (npc == nil || actor.id < npc.id) { + npc = actor + } + } + if npc == nil { + t.Fatal("no admitted level-one Leet") + } + npc.playfield, npc.position, npc.rotation = 705, [3]float32{960, 16.5, 514}, [4]float32{0, 0, 0, 1} + npc.health, npc.motion = 10, nil + world.characters = map[uint32]*character{npc.id: npc} + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.playfield, player.position = 705, [3]float32{960 + float32(index*2), 16.5, 511} + player.rotation = [4]float32{0, 0, 0, 1} + player.stats = testCharacterStats() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("npc-recovery-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + json.NewEncoder(w).Encode(map[string]any{"health": npc.health, "npc": npc.id, + "npcTarget": npc.fighting, "npcAttack": npc.nextAttack, "npcRecharge": npc.rechargeUntil, + "ownerTarget": world.characters[1].fighting, "ownerAttack": world.characters[1].nextAttack, + "ownerRecharge": world.characters[1].rechargeUntil, "counter": npc.regenerationSeconds}) + }) + // Enter combat before the baseline snapshot so idle prediction cannot obscure it. + mux.HandleFunc("POST /test-engage", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + updates := make(map[*worldClient][][]byte) + world.startAttack_locked(npc, world.characters[1], time.Now(), updates) + world.queueHealthSnapshot_locked(updates, npc) + world.mutex.Unlock() + world.sendCombatUpdates(updates) + }) + // Advance only the admitted attack's next outcome; no gameplay is earned here. + mux.HandleFunc("POST /test-swing", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + deadline := world.characters[1].nextAttack + world.mutex.Unlock() + world.advanceCombat(deadline) + }) + // Place the real recovery scheduler one check before its combat tick. + mux.HandleFunc("POST /test-recover", func(w http.ResponseWriter, r *http.Request) { + now := time.Now() + world.mutex.Lock() + npc.regenerationAt, npc.regenerationSeconds = now.Add(-2*time.Second), 58 + world.mutex.Unlock() + world.advanceRegeneration(now) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_npc_recovery.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + if err := command.Run(); err != nil { + t.Fatal(err) + } + + if npc.health != 0 || npc.corpse == nil || npc.regenerationSeconds != 60 { + t.Fatal("recovery regression did not reach the real final death") + } + t.Logf("Browser artifacts: %s", output) +} diff --git a/server/npc_regeneration.go b/server/npc_regeneration.go @@ -22,11 +22,18 @@ func (server *server) advanceNPCRegeneration_locked(now time.Time, updates map[* // kkr.dll FUN_1006ea50: NPC idle recovery replaces delta and interval. // NPC spawns retain native defaults: interval 30, delta 3, BodyDevelopment // below RestModifier 100, and stat 519 = 0, independent of species/level. + health := npc.health if npc.fighting == 0 { npc.health = min(npc.maximumHealth(), npc.health+max(1, npc.maximumHealth()/120)) } else if npc.regenerationSeconds%60 == 0 { npc.health = min(npc.maximumHealth(), npc.health+3) } - server.queueQuietHealth_locked(updates, npc) + + // Publish recovery during combat; the HealthDamage receiver reconciles queued results. + if npc.health != health { + server.queueHealthSnapshot_locked(updates, npc) + } else { + server.queueQuietHealth_locked(updates, npc) + } } } diff --git a/server/npc_regeneration_test.go b/server/npc_regeneration_test.go @@ -105,10 +105,14 @@ func TestNPCRegenerationCombatUsesNativeDeltaAndCounter(t *testing.T) { if world.characters[1000000].health != 20 { t.Fatal("combat health recovered before counter 60") } + if len(conn.packets) != 0 { + t.Fatal("unchanged combat health published a correction") + } world.advanceRegeneration(start.Add(60 * time.Second)) - if world.characters[1000000].health != 23 || len(conn.packets) != 0 { - t.Fatalf("combat recovery or premature correction: hp=%d packets=%x", world.characters[1000000].health, conn.packets) + if world.characters[1000000].health != 23 || len(conn.packets) != 1 || + binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x3710256c || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 23 { + t.Fatalf("combat recovery was not published: hp=%d packets=%x", world.characters[1000000].health, conn.packets) } } @@ -165,7 +169,7 @@ func TestNPCRegenerationSendsQuietHealthOnlyToReadyObserversWithInterest(t *test } } -func TestNPCRegenerationDefersCorrectionForIncomingWeaponQueue(t *testing.T) { +func TestNPCRegenerationPublishesRecoveryDuringIncomingWeaponQueue(t *testing.T) { world, conn, start := newNPCRegenerationWorld(t) world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) conn.packets = nil @@ -173,8 +177,40 @@ func TestNPCRegenerationDefersCorrectionForIncomingWeaponQueue(t *testing.T) { world.advanceRegeneration(start) world.advanceRegeneration(start.Add(2 * time.Second)) - if world.characters[1000000].health != 21 || len(conn.packets) != 0 { - t.Fatalf("incoming-only recovery changed native queue: hp=%d packets=%x", world.characters[1000000].health, conn.packets) + if world.characters[1000000].health != 21 || len(conn.packets) != 1 || + binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x3710256c || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 21 { + t.Fatalf("incoming-only recovery was not published: hp=%d packets=%x", world.characters[1000000].health, conn.packets) + } +} + +func TestNPCRegenerationRetainsBothAttackClocksWhenPublishingRecovery(t *testing.T) { + world, conn, start := newNPCRegenerationWorld(t) + peer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: peer, target: true, ready: true, + npcs: map[uint32]bool{1000000: true}, regenerationAt: start.Add(time.Hour)} + if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + player, npc := world.characters[1], world.characters[1000000] + world.advanceCombat(player.nextAttack) + world.advanceRegeneration(start) + npc.regenerationSeconds = 58 + clocks := [4]time.Time{player.nextAttack, player.rechargeUntil, npc.nextAttack, npc.rechargeUntil} + conn.packets, peer.packets = nil, nil + + world.advanceRegeneration(start.Add(2 * time.Second)) + world.advanceRegeneration(start.Add(2 * time.Second)) + + if npc.health != 18 || npc.regenerationSeconds != 60 || player.fighting != npc.id || npc.fighting != 1 || + clocks != [4]time.Time{player.nextAttack, player.rechargeUntil, npc.nextAttack, npc.rechargeUntil} { + t.Fatal("recovery changed its amount/phase, engagement or attack clocks") + } + if len(conn.packets) != 1 || len(peer.packets) != 1 || !bytes.Equal(conn.packets[0][16:], peer.packets[0][16:]) || + binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x3710256c || + binary.BigEndian.Uint32(conn.packets[0][24:28]) != npc.id || + !bytes.Equal(conn.packets[0][29:45], []byte{0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) { + t.Fatal("combat recovery did not publish one zero-feedback snapshot to both observers") } } diff --git a/tools/client/test_npc_recovery.mjs b/tools/client/test_npc_recovery.mjs @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', + args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = [], evidence = {}; +const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id); +const pending = game => actor(game, 1)?.weapons.some(weapon => weapon.pending.length); +try { + for (let index = 0; index < 2; index++) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'npc-recovery-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + evidence.initial = await server(); + const npc = evidence.initial.npc; + await Promise.all(games.map(game => game.wait('both players and the injured Leet', () => actor(game, 1) && actor(game, 2) && actor(game, npc)))); + const [x, y] = await owner.pick(50000, npc); + await owner.click(x, y); + assert((await owner.page.request.post(url + '/test-engage')).ok()); + await Promise.all(games.map(game => game.wait('combat baseline before any weapon outcome', () => + actor(game, npc).combatTarget === 1 && actor(game, npc).stats[27] === 10))); + await owner.key('q'); + await owner.wait('real native attack request', () => owner.events.some(event => + event.direction === 'framesent' && event.opcode === '28494070')); + assert((await owner.page.request.post(url + '/test-swing')).ok()); + await Promise.all(games.map(game => game.wait('first real weapon result pending', () => pending(game)))); + evidence.pending = {server: await server(), clients: games.map(game => ({health: actor(game, npc).stats[27], weapons: actor(game, 1).weapons}))}; + assert.equal(evidence.pending.server.health, 5); + assert(evidence.pending.clients.every(client => client.health === 10)); + + // A controlled phase advances the ordinary three-point combat recovery once. + assert((await owner.page.request.post(url + '/test-recover')).ok()); + evidence.recovered = await server(); + assert.deepEqual(evidence.recovered, {...evidence.pending.server, health: 8, counter: 60}); + await Promise.all(games.map(game => game.wait('recovery snapshot or first impact', () => + actor(game, npc).stats[27] === 8 || !pending(game)))); + evidence.included = games.map(game => ({health: actor(game, npc).stats[27], weapons: actor(game, 1).weapons})); + await Promise.all(games.map(game => game.wait('first impact consumed', () => !pending(game)))); + evidence.first = {server: await server(), clients: games.map(game => ({health: actor(game, npc).stats[27], weapons: actor(game, 1).weapons}))}; + await Promise.all(games.map((game, index) => game.save(output + '/first-' + index))); + + assert((await owner.page.request.post(url + '/test-swing')).ok()); + await Promise.all(games.map(game => game.wait('second real weapon result pending', () => pending(game)))); + await Promise.all(games.map(game => game.wait('second impact consumed', () => !pending(game)))); + evidence.second = {server: await server(), clients: games.map(game => ({health: actor(game, npc).stats[27], weapons: actor(game, 1).weapons}))}; + await Promise.all(games.map((game, index) => game.save(output + '/second-' + index))); + assert.equal(evidence.second.server.health, 3); + assert(evidence.second.clients.every(client => client.health === 3), 'Native NPC HP reached zero before the real death because combat recovery was withheld'); + assert(evidence.first.clients.every(client => client.health === 8)); + assert(evidence.included.every(client => client.health === 8)); + evidence.included.forEach((client, index) => assert.deepEqual(client.weapons, evidence.pending.clients[index].weapons)); + assert.deepEqual(evidence.first.server, evidence.recovered); + + assert((await owner.page.request.post(url + '/test-swing')).ok()); + await Promise.all(games.map(game => game.wait('real death creates the corpse', state => + state.actors.some(actor => actor.type === 51050 && actor.id === npc)))); + evidence.death = await server(); + assert.equal(evidence.death.health, 0); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: authoritative NPC recovery survives queued impacts, both clients keep three HP until the real final death'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +}