aorecomp

Anarchy Online classic in the browser

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


commit fe77707285357ba37c3164117dc3d5132bcb2b76
parent 62e78389af3b6481b6977ca6111f1272657397b1
Author: anon <anon@example.com>
Date:   Sun,  8 Nov 2026 00:59:20 +0000

Reduce simulation allocations and idle health traffic

Diffstat:
MDEVELOPERS.md | 9++++++---
Mdocs/combat-regeneration.md | 8++++++--
Aserver/browser_idle_health_test.go | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 13++++++++++++-
Mserver/gamedata/load.go | 13+++++++++++--
Mserver/player_movement.go | 40+++++++++++++++++++++++++---------------
Mserver/regeneration.go | 4+++-
Mserver/regeneration_test.go | 44+++++++++++++++++++++++++++++++++++++++++++-
Mserver/state.go | 1+
Mserver/world.go | 26+++++++++++++++-----------
Mserver/world_output_test.go | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/zone_runtime.go | 1+
Atools/client/test_idle_health.mjs | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 299 insertions(+), 36 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -90,8 +90,10 @@ grid of its connected players. Actors enter at 180 metres and leave beyond movement, combat and follow controllers; departure stops dependent controllers before removing the actor. Subsequent actor updates reach only observers that know it. Team resource messages remain available outside actor visibility and -across zones. Health reconciliation retains its existing cadence. Broadcasts -encode the native packet once, then copy it for each recipient's output queue. +across zones. Injured players reconcile quiet health every two seconds; full +health uses ten seconds, and actual healing is published immediately. Broadcasts +and queued batches encode shared native packets once, then copy them for each +recipient's output queue. Per-frame position scratch storage stays with its zone. Zone activation restores its NPC checkpoint or creates its authored population in one transaction. Concurrent arrivals share that owner's activation, while @@ -99,7 +101,8 @@ the directory continues routing other zones. NPC identities are reserved before activation, so late-loaded populations cannot collide with pets or respawns. Admin catalog, map and player-list observations do not activate populations; inactive NPC markers use authored positions or committed state. Game data stays -loaded for catalog searches and validation. +loaded for catalog searches and validation. Item quality variants share identical +immutable names and descriptions; the deduplication index is discarded at startup. Five minutes after the last connection leaves, an idle zone checkpoints before stopping its timers and releasing NPC actors, spatial/navigation state and diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md @@ -1,9 +1,13 @@ # Authoritative resources and editable stats Player health and nano now regenerate on the server using the recovered -14.9.1 client arithmetic. Quiet clients receive absolute corrections every +14.9.1 client arithmetic. Quiet injured players receive absolute corrections every two seconds, so local prediction no longer accumulates independently of server -state. This matches the recovered client rules; the unavailable original +state. Players at full health reconcile every ten seconds because native recovery +already clamps at the maximum. Actual healing is published immediately, including +the change that reaches full health. Owner nano, team resources and NPC health +retain their two-second cadence. This matches the recovered client arithmetic; +the unavailable original server's scheduler is not established by those rules. ## Character data diff --git a/server/browser_idle_health_test.go b/server/browser_idle_health_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserFullHealthReconciliation(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native idle-health reconciliation") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/idle-health", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + world := newDormantServerForTest(t) + for i := range 2 { + player := world.newCharacter() + player.position, player.rotation = [3]float32{52 + float32(i)*2, 14, 56}, [4]float32{0, 0, 0, 1} + player.health, player.nano = player.maximumHealth(), player.maximumNano() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("idle-health-", i)))) + if err := world.saveUser(player); err != nil { + t.Fatal(err) + } + } + shutdown := startTestService(t, world) + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("POST /test-injure", testPlayerHTTP(world, 1, func(state *server, w http.ResponseWriter, r *http.Request) { + // An unannounced fixture injury must be reconciled on the next normal tick. + state.characters[1].health -= 9 + state.clients[1].regenerationAt, state.clients[1].regenerationSeconds = time.Now(), 0 + w.WriteHeader(http.StatusNoContent) + })) + mux.HandleFunc("GET /test-state", testPlayerHTTP(world, 1, func(state *server, w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{"health": state.characters[1].health, + "maximum": state.characters[1].maximumHealth(), "sitting": state.characters[1].sitting}) + })) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_idle_health.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + + err := command.Run() + host.Close() + + if failure := shutdown(); failure != nil { + t.Fatal(failure) + } + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } +} diff --git a/server/combat.go b/server/combat.go @@ -657,9 +657,20 @@ func (server *server) queueCombat(updates map[*worldClient][][]byte, character, } func (server *server) sendCombatUpdates(updates map[*worldClient][][]byte) { + // Queued broadcasts share packet slices. Cache conversion by their first byte's + // address for this batch only; sendEncoded copies before stamping each recipient. + native := make(map[*byte][]byte) for client, packets := range updates { for _, packet := range packets { - if err := client.send(packet); err != nil { + encoded := packet + if client.target && binary.BigEndian.Uint16(packet[2:4]) == 10 { + encoded = native[&packet[0]] + if encoded == nil { + encoded = targetPacket(append([]byte(nil), packet...)) + native[&packet[0]] = encoded + } + } + if err := client.sendEncoded(encoded); err != nil { if client.ready { log.Printf("Combat: %v", err) } diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -211,8 +211,9 @@ func init() { if err != nil { panic(err) } + texts := make(map[string]string) for _, name := range parts { - loadItems(name) + loadItems(name, texts) } for index := range Items.Items { if Items.Items[index].RecordType == 1000020 { @@ -353,7 +354,7 @@ func loadYAML(name string, value any) { } } -func loadItems(name string) { +func loadItems(name string, texts map[string]string) { file, err := files.Open(name) if err != nil { panic(err) @@ -370,6 +371,14 @@ func loadItems(name string) { if err != nil { panic(fmt.Errorf("gamedata %s: %w", name, err)) } + // Quality variants share immutable text; the temporary index dies at startup. + for _, value := range []*string{&item.Name, &item.Description} { + if shared, ok := texts[*value]; ok { + *value = shared + } else { + texts[*value] = *value + } + } Items.Items = append(Items.Items, item) } } diff --git a/server/player_movement.go b/server/player_movement.go @@ -601,12 +601,19 @@ func (server *server) advancePlayerMovement(now time.Time) { server.sendCombatUpdates(updates) } +type playerMovementFrame struct { + client *worldClient + player *character + position, targetPosition [3]float32 +} + func (server *server) queuePlayerMovement(now time.Time, updates map[*worldClient][][]byte) { - previous := make(map[uint32][3]float32, len(server.clients)) + // Reuse one zone-owned frame list instead of looking up every player each pass. + frames := server.movementFrames[:0] // Advance ordinary inputs first so every follower observes this frame's target. for id, client := range server.clients { player := server.characters[id] - previous[id] = player.position + frames = append(frames, playerMovementFrame{client: client, player: player, position: player.position}) if !client.ready || client.loading || player.health == 0 { if player.followTarget != 0 { server.queueCombat(updates, player, player, npcMovementPacket(player, 2), npcMovementPacket(player, 4)) @@ -628,26 +635,26 @@ func (server *server) queuePlayerMovement(now time.Time, updates map[*worldClien server.queueCombat(updates, player, player, npcMovementPacket(player, 0x94)) } } - targets := make(map[uint32][3]float32) - for _, client := range server.clients { - player := server.characters[client.id] + for index := range frames { + frame := &frames[index] + player := frame.player if player.followTarget != 0 { - if target := server.characters[player.followTarget]; server.playerFollowTargetAvailable(client, target) { - targets[target.id] = target.position + if target := server.characters[player.followTarget]; server.playerFollowTargetAvailable(frame.client, target) { + frame.targetPosition = target.position } } } - for id, client := range server.clients { - player := server.characters[id] + for _, frame := range frames { + player := frame.player if player.followTarget != 0 { target := server.characters[player.followTarget] - if !server.playerFollowTargetAvailable(client, target) { + if !server.playerFollowTargetAvailable(frame.client, target) { player.followTarget = 0 player.movement.action(player, 2) player.movement.action(player, 4) player.movement.updatedAt = now server.queueCombat(updates, player, player, npcMovementPacket(player, 2), npcMovementPacket(player, 4)) - } else if player.advanceMovement(now, targets[target.id]) { + } else if player.advanceMovement(now, frame.targetPosition) { server.queueCombat(updates, player, player, npcMovementPacket(player, 0x94)) } } @@ -661,9 +668,9 @@ func (server *server) queuePlayerMovement(now time.Time, updates map[*worldClien } server.advancePetFollowing(now, updates) // Resource/range effects see all participants at the completed frame. - for id, client := range server.clients { - player := server.characters[id] - if player.position == previous[id] { + for _, frame := range frames { + player, client := frame.player, frame.client + if player.position == frame.position { continue } server.abortNano(client, now, updates) @@ -671,9 +678,12 @@ func (server *server) queuePlayerMovement(now time.Time, updates map[*worldClien server.cancelPlayerTrade(client) } if client.bank != nil && !server.bankAvailable(client) { - updates[client] = append(updates[client], characterActionPacket(id, [5]uint32{106})) + updates[client] = append(updates[client], characterActionPacket(player.id, [5]uint32{106})) } } + // Retain capacity without retaining departed players or their connections. + clear(frames) + server.movementFrames = frames[:0] } func playerMovementMassPackets(player *character) [][]byte { diff --git a/server/regeneration.go b/server/regeneration.go @@ -78,7 +78,9 @@ func (server *server) advanceRegeneration(now time.Time) { // Actual recovery includes received hits even while their animations are pending. if player.health != health { server.queueHealthSnapshot(updates, player) - } else { + } else if player.health != player.maximumHealth() || client.regenerationSeconds%10 == 0 { + // Full health is stable under native recovery; retain a slower correction + // while injured actors still reconcile independent prediction every tick. server.queueQuietHealth(updates, player) } body := binary.BigEndian.AppendUint32(nil, 214) diff --git a/server/regeneration_test.go b/server/regeneration_test.go @@ -157,8 +157,46 @@ func TestRegenerationCorrectsAbsoluteIdleResourcesForOwnerAndObserver(t *testing } } +func TestRegenerationFullHealthReconcilesEveryTenSeconds(t *testing.T) { + world, conn, start := newRegenerationWorld(t) + world.characters[1000000].regenerationAt = start.Add(time.Hour) + world.characters[1].health = world.characters[1].maximumHealth() + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, regenerationAt: start.Add(time.Hour)} + + for second := 2; second <= 8; second += 2 { + world.advanceRegeneration(start.Add(time.Duration(second) * time.Second)) + } + if len(observer.packets) != 0 || len(conn.packets) != 4 { + t.Fatal("stable full health was broadcast or owner nano corrections were lost") + } + world.advanceRegeneration(start.Add(10 * time.Second)) + + if len(observer.packets) != 1 || binary.BigEndian.Uint32(observer.packets[0][16:20]) != 0x3710256c || + binary.BigEndian.Uint32(observer.packets[0][29:33]) != 37 { + t.Fatal("full health did not receive its periodic reconciliation", observer.packets) + } +} + +func TestRegenerationInjuryResumesQuietCorrections(t *testing.T) { + world, conn, start := newRegenerationWorld(t) + world.characters[1000000].regenerationAt = start.Add(time.Hour) + world.characters[1].health = world.characters[1].maximumHealth() + world.advanceRegeneration(start.Add(2 * time.Second)) + world.characters[1].health = 20 + conn.packets = nil + + world.advanceRegeneration(start.Add(4 * time.Second)) + + if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x3710256c || + binary.BigEndian.Uint32(conn.packets[0][29:33]) != 20 { + t.Fatal("injury waited for the full-health reconciliation interval", conn.packets) + } +} + func TestRegenerationClampsHealthAndNanoToNativeMaximums(t *testing.T) { - world, _, start := newRegenerationWorld(t) + world, conn, start := newRegenerationWorld(t) world.characters[1].health = 36 world.characters[1].nano = 34 world.clients[1].regenerationSeconds = 810 @@ -168,6 +206,10 @@ func TestRegenerationClampsHealthAndNanoToNativeMaximums(t *testing.T) { if world.characters[1].health != 37 || world.characters[1].nano != 35 { t.Fatalf("resource overflow: %+v", world.characters[1]) } + if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x3710256c || + binary.BigEndian.Uint32(conn.packets[0][29:33]) != 37 { + t.Fatal("actual healing to full health waited for periodic reconciliation", conn.packets) + } } func TestRegenerationSkipsDeadLoadingOfflineAndNPCCharacters(t *testing.T) { diff --git a/server/state.go b/server/state.go @@ -171,6 +171,7 @@ type server struct { corpseExpiry []*character missionExpiry []acceptedMission clients map[uint32]*worldClient + movementFrames []playerMovementFrame fighting map[uint32]*character browserCreations map[string]*browserCreationCredentials weather int diff --git a/server/world.go b/server/world.go @@ -214,23 +214,27 @@ func characterPacket(character *character) []byte { } func playerCombatStatPackets(character *character) [][]byte { - var packets [][]byte - stats := character.baseStats().nativeStats() - stats = append(stats, [2]uint32{51, uint32(character.aggDef)}) + stats := character.baseStats() rest, posture := uint32(100), uint32(0) if character.sitting { rest, posture = 25, 2 } - stats = append(stats, [2]uint32{425, rest}, [2]uint32{430, posture}) // Remote timing uses the same raw foundations as the owner's FullCharacter. // Native getters derive trickle from these bases and separate wear/nano modifiers. - for _, stat := range stats { - switch stat[0] { - case 16, 17, 18, 19, 20, 21, 51, 118, 119, 120, 138, 149, 425, 430: - body := binary.BigEndian.AppendUint32(nil, stat[0]) - body = binary.BigEndian.AppendUint32(body, stat[1]) - packets = append(packets, n3Packet(0x2b333d6e, 50000, character.id, body)) - } + values := [14][2]uint32{ + {16, uint32(stats.Abilities.Strength)}, {17, uint32(stats.Abilities.Agility)}, + {18, uint32(stats.Abilities.Stamina)}, {19, uint32(stats.Abilities.Intelligence)}, + {20, uint32(stats.Abilities.Sense)}, {21, uint32(stats.Abilities.Psychic)}, + {138, uint32(stats.Body.Swimming)}, {118, uint32(stats.Speed.MeleeInitiative)}, + {119, uint32(stats.Speed.RangedInitiative)}, {120, uint32(stats.Speed.PhysicalInitiative)}, + {149, uint32(stats.Speed.NanoInitiative)}, {51, uint32(character.aggDef)}, + {425, rest}, {430, posture}, + } + packets := make([][]byte, 0, 16) + for _, stat := range values { + body := binary.BigEndian.AppendUint32(nil, stat[0]) + body = binary.BigEndian.AppendUint32(body, stat[1]) + packets = append(packets, n3Packet(0x2b333d6e, 50000, character.id, body)) } packets = append(packets, playerMovementMassPackets(character)...) return packets diff --git a/server/world_output_test.go b/server/world_output_test.go @@ -433,3 +433,51 @@ func TestWorldBroadcastSharesEncodingWithoutSharingRecipientHeaders(t *testing.T } } } + +func TestCombatBatchPreservesSharedPacketsAndRecipientOrder(t *testing.T) { + // Share a packet twice, with a distinct packet between its deliveries. + world := &server{} + move := npcMovementPacket(&character{id: 17, rotation: [4]float32{0, 0, 0, 1}}, 1) + stop := stopFightPacket(17) + original := slices.Clone(move) + updates := make(map[*worldClient][][]byte) + for id := uint32(1); id <= 3; id++ { + client := &worldClient{id: id, ready: true, target: id != 3, conn: &combatTestConn{}} + updates[client] = [][]byte{move, stop, move} + } + + world.sendCombatUpdates(updates) + + if !bytes.Equal(move, original) { + t.Fatal("batch conversion mutated its shared source") + } + for client := range updates { + packets := client.conn.(*combatTestConn).packets + if len(packets) != 3 || !bytes.Equal(packets[0], packets[2]) { + t.Fatal("batch lost or changed a repeated packet", packets) + } + offset, length := 16, 48 + if !client.target { + offset, length = 20, 76 + } + if len(packets[0]) != length || binary.BigEndian.Uint32(packets[0][offset:]) != 0x54111123 || + binary.BigEndian.Uint32(packets[1][offset:]) != 0x4a41203e { + t.Fatal("batch changed protocol or packet order", packets) + } + for _, packet := range packets { + if binary.BigEndian.Uint32(packet[12:16]) != client.id { + t.Fatal("batch retained another recipient's header", packet) + } + } + } + + // Reusing a source buffer in a later batch must not reuse its old conversion. + binary.BigEndian.PutUint32(move[36:40], 2) + world.sendCombatUpdates(updates) + for client := range updates { + packet := client.conn.(*combatTestConn).packets[3] + if client.target && packet[29] != 2 || !client.target && binary.BigEndian.Uint32(packet[36:40]) != 2 { + t.Fatal("batch retained a stale conversion", packet) + } + } +} diff --git a/server/zone_runtime.go b/server/zone_runtime.go @@ -85,6 +85,7 @@ func (zone *zoneRuntime) run(state *server) { checkpoints.Stop() } movementTicks, actionTicks, crossingTicks, checkpointTicks = nil, nil, nil, nil + state.movementFrames = nil } defer pauseTicks() if !state.populationDormant() { diff --git a/tools/client/test_idle_health.mjs b/tools/client/test_idle_health.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +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 = []; +const actor = game => game.state.actors.find(actor => actor.type === 50000 && actor.id === 1 && !actor.deleting); +const corrections = (game, since) => game.events.filter(event => event.sequence > since && + event.direction === 'framereceived' && event.opcode === '3710256c' && event.actor?.[1] === 1); +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: 'idle-health-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const state = async () => (await owner.page.request.get(url + '/test-state')).json(); + const initial = await state(); + await Promise.all(games.map(game => game.wait('full owner visible', () => actor(game)?.stats[27] === initial.maximum))); + await owner.key('KeyX'); + await owner.wait('real sit changes recovery posture', () => owner.local().stats[430] === 2); + assert.equal((await state()).sitting, true); + + // Watch native recovery across two corrections, including the gap between them. + await Promise.all(games.map(async game => { + const since = game.sequence; + await game.wait('two full-health reconciliations', () => { + assert.equal(actor(game).stats[27], initial.maximum, 'full native health drifted'); + return corrections(game, since).length >= 2; + }, 25000); + const packets = corrections(game, since); + assert(packets[1].time - packets[0].time >= 8500, 'full health still broadcasts every two seconds'); + })); + + // Standing and an unannounced controlled injury restore the frequent correction. + await owner.key('KeyX'); + await owner.wait('owner stands', () => owner.local().stats[430] !== 2); + const sequences = games.map(game => game.sequence); + assert.equal((await owner.page.request.post(url + '/test-injure')).status(), 204); + const injured = await state(); + assert.equal(injured.health, initial.maximum - 9); + await Promise.all(games.map(async (game, index) => { + await game.wait('three injured-health corrections', () => corrections(game, sequences[index]).length >= 3, 9000); + const packets = corrections(game, sequences[index]); + assert(packets[2].time - packets[0].time < 6000, 'injury retained the slow full-health cadence'); + assert(packets.every(packet => Buffer.from(packet.hex, 'hex').readUInt32BE(29) === injured.health)); + await game.wait('native health matches injury', () => actor(game).stats[27] === injured.health); + })); + assert.equal((await state()).health, injured.health); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: native full-health stability with slower reconciliation, real posture input and prompt injury corrections'); +} finally { + try { await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); } + finally { await browser.close(); } +}