aorecomp

Anarchy Online classic in the browser

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


commit c4b5b2c2ea0687f129fdcbe3b50b82c3dac134db
parent 1c019fa11882128f361a5b2eb7b3ff6c52e553ee
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 06:53:35 +0000

Limit NPC simulation to nearby players with an activity grace period

Diffstat:
Mdocs/npc-pursuit.md | 16++++++++++------
Mdocs/npc-regeneration.md | 7+++++--
Mdocs/world-state.md | 9+++++++--
Mserver/admin_pages.go | 19++++++++++++++-----
Mserver/admin_test.go | 17+++++++++++++++++
Mserver/combat.go | 4++--
Mserver/database_test.go | 6+++---
Mserver/initiative_debuff_test.go | 2+-
Mserver/interest.go | 19+++++++++++++++++++
Mserver/interest_test.go | 4++--
Mserver/item_database.go | 20+++++++++++---------
Mserver/item_pages.go | 2+-
Mserver/nano_buffs.go | 3+++
Mserver/nano_periodic.go | 2+-
Mserver/nano_periodic_test.go | 7+++++++
Aserver/npc_activity_test.go | 170+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/npc_navigation_test.go | 8+++++++-
Mserver/npc_outdoor_surface_test.go | 4+++-
Mserver/npc_regeneration.go | 2+-
Mserver/npc_regeneration_test.go | 7+++----
Mserver/npc_shared_pursuit_test.go | 2++
Mserver/pet_follow.go | 2+-
Mserver/roaming.go | 14++++++--------
Mserver/state.go | 3++-
Mserver/world_store.go | 12++++++------
25 files changed, 304 insertions(+), 57 deletions(-)

diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md @@ -44,7 +44,9 @@ original-server scheduling frequency. Return to the retained spawn is an explicit reconstruction policy. A bounded source search found no period Leet rule proving that exact destination or its -timing. Return continues without observers. Health uses the separate +timing. Motion, including returns, runs within 600 metres horizontally of a +ready player in the same playfield, and for five minutes after the last nearby +player leaves. Loading players do not activate NPCs. Health uses the separate [recovery rule](npc-regeneration.md), including while returning. Unprofiled appearance stand-ins do not acquire combat pursuit. Proximity aggression, original outdoor route selection and broader navigation fidelity remain separate TODOs. @@ -52,9 +54,10 @@ original outdoor route selection and broader navigation fidelity remain separate Motion state retains home, destination, idle-wandering eligibility and return progress independently of combat capability. It uses the existing periodic NPC checkpoint; movement does not write SQLite on each tick. Cold loading restores -the current admitted profile and returns displaced living combatants home before -idling. Transient targets and attack clocks are not restored. Roots hold that -return until expiry, and the normal signed run-speed rule applies to snares. +the current admitted profile; displaced living combatants resume returning home +when a player comes nearby, before idling. Transient targets and attack clocks +are not restored. Roots hold that return until expiry, and the normal signed +run-speed rule applies to snares. Dead remains stay where they fell; the separately committed replacement life starts at home and inherits the same idle policy. @@ -256,8 +259,9 @@ observations use position and time, not those unidentified fields. Focused Go tests cover attack range and retained deadlines, a moving target, identical route packets for two observers, return after target loss, continued -return without observers, a new encounter during return, corpse exclusion, -new-observer ordering and unchanged behavior for unverified profiles. +return during the grace period without observers, a new encounter during return, +corpse exclusion, new-observer ordering and unchanged behavior for unverified +profiles. The full `go test ./server/...` suite passed (120.670 seconds). Movement and NPC recovery tests also passed five runs under the race detector (120.199 diff --git a/docs/npc-regeneration.md b/docs/npc-regeneration.md @@ -63,8 +63,11 @@ combat-profile catalog. This does not establish the original server's creature balance. NPC nano recovery and changed recovery stats remain outside the implementation. -The server keeps one two-second phase and counter per living NPC, independent -of observers. Starting or stopping an attack changes the applicable branch +The server keeps one two-second phase and counter per living NPC. Recovery runs +within 600 metres horizontally of a ready, non-loading player in the same +playfield and for five minutes after the last nearby player leaves. After that, +dormant NPCs retain their health and clock until a player returns. Starting or +stopping an attack changes the applicable branch without resetting that phase or granting an additional heal. A late scheduler visit performs one check and skips the stalled backlog, following the existing player recovery policy. A fresh respawn gets full health and a new clock; diff --git a/docs/world-state.md b/docs/world-state.md @@ -61,8 +61,13 @@ The world header is updated only when its counters, clock or population-initialization state change. NPC state is checked on the one-second world tick, but routine writes occur at least 20 seconds -apart, with random starting phases, only in zones with a connected player. -The last player leaving a zone triggers one final snapshot. Unchanged rows +apart, with random starting phases, only for NPCs within 600 metres horizontally +of a ready, non-loading player in the same playfield, or within a five-minute +grace period after the last nearby player leaves. Roaming, pursuit, returns, +recovery and periodic effects use the same activity gate. Grace expiry triggers +one final snapshot; an occupied zone does not activate its entire population. +The activity deadline lives in memory; after a restart, NPCs wait for a nearby +player before resuming. Unchanged rows are skipped. Corpse ownership and cash changes save immediately with their loot transaction. A new database takes one initial population snapshot. SIGINT/SIGTERM flush pending state before closing the database. A crash can diff --git a/server/admin_pages.go b/server/admin_pages.go @@ -8,6 +8,7 @@ import ( "encoding/json" "fmt" "html" + "net" "net/http" "os" "strings" @@ -87,19 +88,27 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) { func (server *server) usersPage(w http.ResponseWriter, r *http.Request) { server.mutex.Lock() players := server.users_locked() - connected := make(map[uint32]bool) + addresses := make(map[uint32]string) for id, client := range server.clients { - connected[id] = client.ready + if client.ready { + address := client.conn.RemoteAddr().String() + if host, _, err := net.SplitHostPort(address); err == nil { + address = host + } + addresses[id] = address + } } server.mutex.Unlock() server.adminPageStart(w, "Players", "Players") - fmt.Fprint(w, "<h1>Players</h1><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th></tr>") + fmt.Fprint(w, "<h1>Players</h1><table><tr><th>ID</th><th>Name</th><th>Status</th><th>IP address</th><th>Zone</th></tr>") for _, player := range players { status := "Offline" - if connected[player.ID] { + address := "-" + if addresses[player.ID] != "" { + address = addresses[player.ID] status = "Connected" } - fmt.Fprintf(w, "<tr><td>%d</td><td><a href='admin/players/%d'>%s</a></td><td>%s</td><td>%s (%d)</td></tr>", player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(gamedata.Playfields[player.Playfield].Name), player.Playfield) + fmt.Fprintf(w, "<tr><td>%d</td><td><a href='admin/players/%d'>%s</a></td><td>%s</td><td>%s</td><td>%s (%d)</td></tr>", player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(address), html.EscapeString(gamedata.Playfields[player.Playfield].Name), player.Playfield) } fmt.Fprint(w, "</table></main></body></html>") } diff --git a/server/admin_test.go b/server/admin_test.go @@ -372,3 +372,20 @@ func TestAdminDatabaseCountsPreparedAndDirectExecutions(t *testing.T) { t.Fatal("query count", world.databaseQueries.Load()-before) } } + +func TestAdminPlayersListsConnectedIPAddresses(t *testing.T) { + world := newAdminTestServer(t) + world.characters[1] = &character{id: 1, name: "Online"} + world.characters[2] = &character{id: 2, name: "Offline"} + world.clients[1] = &worldClient{id: 1, ready: true, conn: &combatTestConn{}} + handler := world.httpHandler() + login := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=", nil) + + page := adminRequest(handler, "GET", "/admin/players", "", login.Result().Cookies()[0]) + + if page.Code != 200 || !strings.Contains(page.Body.String(), "<th>IP address</th>") || + !strings.Contains(page.Body.String(), "<td>Connected</td><td>192.0.2.1</td>") || + !strings.Contains(page.Body.String(), "<td>Offline</td><td>-</td>") { + t.Fatal("player connection addresses missing", page.Code, page.Body) + } +} diff --git a/server/combat.go b/server/combat.go @@ -413,7 +413,7 @@ func (server *server) advanceCombat(now time.Time) { // An unavailable opponent must not prevent another participant taking over. for _, attacker := range server.fighting { - if attacker.npc && len(attacker.threat) != 0 { + if attacker.npc && len(attacker.threat) != 0 && server.npcActive_locked(attacker, now) { server.selectNPCTarget_locked(attacker, now, updates) } } @@ -426,7 +426,7 @@ func (server *server) advanceCombat(now time.Time) { sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) for _, id := range ids { attacker := server.fighting[id] - if attacker == nil { + if attacker == nil || attacker.npc && !server.npcActive_locked(attacker, now) { continue } target := server.characters[attacker.fighting] diff --git a/server/database_test.go b/server/database_test.go @@ -252,7 +252,7 @@ func TestWorldDatabasePersistsContributorChangesAfterRestart(t *testing.T) { } } -func TestNPCCheckpointsSkipEmptyZonesAndLimitRoutineWrites(t *testing.T) { +func TestNPCCheckpointsSkipDormantNPCsAndLimitRoutineWrites(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) @@ -268,7 +268,7 @@ func TestNPCCheckpointsSkipEmptyZonesAndLimitRoutineWrites(t *testing.T) { seconds int present bool x float32 - }{{60, false, 53}, {61, true, 53}, {62, true, 54}, {80, true, 54}, {102, true, 54}, {103, true, 55}, {104, false, 55}, {165, false, 56}} + }{{60, false, 53}, {61, true, 53}, {62, true, 54}, {80, true, 54}, {102, true, 54}, {103, true, 55}, {404, false, 55}, {465, false, 56}} var counts [8]int var positions [8]float32 for index, step := range steps { @@ -290,6 +290,6 @@ func TestNPCCheckpointsSkipEmptyZonesAndLimitRoutineWrites(t *testing.T) { } if counts != [8]int{0, 1, 1, 1, 2, 2, 3, 3} || positions != [8]float32{52, 53, 53, 53, 54, 54, 55, 55} { - t.Fatalf("empty zones or early checkpoints rewrote NPC state: counts=%v positions=%v", counts, positions) + t.Fatalf("dormant NPCs or early checkpoints rewrote NPC state: counts=%v positions=%v", counts, positions) } } diff --git a/server/initiative_debuff_test.go b/server/initiative_debuff_test.go @@ -184,7 +184,7 @@ func TestIceFlechetteTimerUsesNPCCheckpointsWithoutRewritingStillActors(t *testi saved := world.savedNPCs[1000000] saved.NextSave = at.Add(20 * time.Second) world.savedNPCs[1000000] = saved - world.npcZones = map[uint32]bool{world.characters[1000000].playfield: true} + world.activeNPCs = map[uint32]bool{1000000: true} auditCheckpointWrites(t, world) if _, err := world.db.Exec("CREATE TRIGGER audit_nano AFTER UPDATE ON active_nanos BEGIN INSERT INTO checkpoint_writes VALUES ('active_nanos', 'UPDATE'); END"); err != nil { t.Fatal(err) diff --git a/server/interest.go b/server/interest.go @@ -2,6 +2,25 @@ package main import "time" +func (server *server) npcActive_locked(npc *character, now time.Time) bool { + // Keep nearby NPCs active for five minutes after the last player leaves. + for id, client := range server.clients { + if !client.ready || client.loading { + continue + } + player := server.characters[id] + if player.playfield != npc.playfield { + continue + } + x, z := player.position[0]-npc.position[0], player.position[2]-npc.position[2] + if x*x+z*z <= 600*600 { + npc.npcActiveUntil = now.Add(5 * time.Minute) + return true + } + } + return now.Before(npc.npcActiveUntil) +} + func (server *server) updateNPCInterest_locked(client *worldClient, now time.Time) [][]byte { player := server.characters[client.id] position := predictedPosition_locked(player, now) diff --git a/server/interest_test.go b/server/interest_test.go @@ -169,7 +169,7 @@ func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) { if binary.BigEndian.Uint32(motion[20:]) != 0x260f3671 || binary.BigEndian.Uint32(motion[28:]) != 1000000 || motion[48] != 22 || math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(motion[49:]))-1549.887)) > .001 { t.Fatalf("entering NPC motion: %x", motion) } - if world.characters[1000001].position[0] >= 1999.5 || world.characters[1000001].position[0] <= 1999 { - t.Fatal("unobserved NPC stopped roaming on the server") + if world.characters[1000001].position != [3]float32{2000, 0, 1000} { + t.Fatal("unobserved NPC advanced its position") } } diff --git a/server/item_database.go b/server/item_database.go @@ -155,16 +155,18 @@ func (server *server) persistItems_locked(store itemStore) error { } } } - zones := make(map[uint32]bool) - for id, client := range server.clients { - if client.ready { - zones[server.characters[id].playfield] = true - } + // Checkpoint active NPCs and save their final state when the grace period ends. + now := store.checkpointAt + if now.IsZero() { + now = time.Now() } - if store.removedMission != nil { - delete(zones, store.removedMission.world) + active := make(map[uint32]bool) + for id, npc := range server.characters { + if npc.npc && server.npcActive_locked(npc, now) && (store.removedMission == nil || npc.playfield != store.removedMission.world) { + active[id] = true + } } - savedNPCs, err := server.writeNPCs_locked(tx, store, zones) + savedNPCs, err := server.writeNPCs_locked(tx, store, active) if err != nil { return err } @@ -457,7 +459,7 @@ func (server *server) persistItems_locked(store itemStore) error { if err := tx.Commit(); err != nil { return err } - server.itemPlacements, server.savedNPCs, server.npcZones = placements, savedNPCs, zones + server.itemPlacements, server.savedNPCs, server.activeNPCs = placements, savedNPCs, active return nil } diff --git a/server/item_pages.go b/server/item_pages.go @@ -238,7 +238,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { server.adminPageStart(w, fmt.Sprintf("Item %d", id), "Items") fmt.Fprintf(w, "<h1>Item %d</h1>", id) if definition != nil { - fmt.Fprintf(w, "<h2>%s</h2><p>%s</p>", html.EscapeString(definition.Name), html.EscapeString(definition.Description)) + fmt.Fprintf(w, "<h2>%s</h2><p><strong>Description:</strong> %s</p>", html.EscapeString(definition.Name), html.EscapeString(definition.Description)) } if location.owner != 0 { fmt.Fprintf(w, "<p>Owner: <a href='admin/players/%d'>%s (%d)</a>. ", location.owner, html.EscapeString(ownerName), location.owner) diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -478,6 +478,9 @@ func (server *server) handleNanoRemoval(client *worldClient, body []byte) error func (server *server) advanceNanoBuffs_locked(now time.Time, updates map[*worldClient][][]byte) { for _, player := range server.characters { + if player.npc && !server.npcActive_locked(player, now) { + continue + } for index := len(player.activeNanos) - 1; index >= 0; index-- { if player.activeNanos[index].remainingAt(now) == 0 && player.activeNanos[index].ticksLeft == 0 { if err := server.removeNano_locked(player, index, now, updates); err != nil { diff --git a/server/nano_periodic.go b/server/nano_periodic.go @@ -10,7 +10,7 @@ import ( func (server *server) advancePeriodicNanos_locked(now time.Time, updates map[*worldClient][][]byte) { for _, target := range server.characters { - if !target.npc || slices.IndexFunc(target.activeNanos, func(effect activeNano) bool { + if !target.npc || !server.npcActive_locked(target, now) || slices.IndexFunc(target.activeNanos, func(effect activeNano) bool { return effect.ticksLeft != 0 && !effect.nextTick.After(now) }) < 0 { continue diff --git a/server/nano_periodic_test.go b/server/nano_periodic_test.go @@ -43,6 +43,13 @@ func TestPeriodicNanoColdRestoreRetainsPhaseAndPendingOverdueTicks(t *testing.T) } cold.advanceNanos(time.Now()) + if target.health != 100 || target.activeNanos[0].ticksLeft != 8 { + t.Fatal("unobserved NPC processed periodic damage") + } + // The caster stays offline; another nearby player activates the NPC. + cold.characters[2] = &character{id: 2, playfield: target.playfield, position: target.position, health: 100} + cold.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{target.id: true}} + cold.advanceNanos(time.Now()) if checkpoint == 10*time.Second { if target.health != 97 || target.activeNanos[0].ticksLeft != 7 || target.fighting != 0 { t.Fatal("restored first tick was lost, duplicated or attacked an offline caster") diff --git a/server/npc_activity_test.go b/server/npc_activity_test.go @@ -0,0 +1,170 @@ +package main + +import ( + "net/http" + "net/url" + "testing" + "time" +) + +func TestNPCActivitySkipsDistantAndUnavailablePlayers(t *testing.T) { + for _, scenario := range []string{"distant", "diagonal", "other zone", "offline", "loading", "not ready"} { + t.Run(scenario, func(t *testing.T) { + world, _, start := newNPCPursuitWorld(t) + npc := world.characters[1000000] + npc.health = 50 + switch scenario { + case "distant": + world.characters[1].position = [3]float32{602, 0, 0} + case "diagonal": + world.characters[1].position = [3]float32{500, 0, 500} + case "other zone": + world.characters[1].playfield = 635 + case "offline": + delete(world.clients, 1) + case "loading": + world.clients[1].loading = true + case "not ready": + world.clients[1].ready = false + } + before := npc.worldState(true, time.Time{}) + attack := npc.nextAttack + + for tick := 1; tick <= 16; tick++ { + now := start.Add(time.Duration(tick) * 250 * time.Millisecond) + world.advanceNPCs(now) + world.advanceCombat(now) + world.advanceRegeneration(now) + } + + if npc.worldState(true, time.Time{}) != before || npc.nextAttack != attack || npc.fighting != 1 { + t.Fatal("unobserved NPC advanced its simulation", npc.position, npc.motion, npc.regenerationAt) + } + }) + } +} + +func TestNPCActivityResumesNearAnyPlayerWithoutMovementCatchup(t *testing.T) { + world, _, start := newNPCPursuitWorld(t) + npc := world.characters[1000000] + npc.fighting, npc.health = 0, 50 + delete(world.fighting, npc.id) + npc.motion.moving, npc.motion.returning = true, true + npc.motion.home = [3]float32{21, 0, 0} + world.characters[1].position = [3]float32{2000, 0, 0} + world.advanceNPCs(start.Add(time.Hour)) + before := npc.position + world.characters[2] = &character{id: 2, playfield: 950, position: [3]float32{600, 0, 0}} + world.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)} + + world.advanceNPCs(start.Add(time.Hour + 250*time.Millisecond)) + world.advanceRegeneration(start.Add(time.Hour)) + world.advanceRegeneration(start.Add(time.Hour + 2*time.Second)) + + if before != [3]float32{1, 0, 0} || npc.position[0] <= 1 || npc.position[0] > 2.125 || npc.health != 51 { + t.Fatal("nearby observer did not resume bounded motion and recovery", before, npc.position, npc.health) + } +} + +func TestNPCActivityCheckpointsIgnoreDistantPopulation(t *testing.T) { + data := testNPCData() + group := &data.Playfields[0].Districts[0].Groups[0] + group.PlacementStatus = "authored_point" + for index := 0; index < 1000; index++ { + group.Positions = append(group.Positions, [3]float32{2000 + float32(index), 14, 56}) + } + useNPCData(t, data) + world := newTestServer(t) + if response := postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}); response.Code != http.StatusSeeOther { + t.Fatal(response.Code, response.Body) + } + world.clients[1] = &worldClient{id: 1, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)} + start := time.Now() + world.lastNPCUpdate = start + if err := world.checkpointWorld(start); err != nil { + t.Fatal(err) + } + distant := world.characters[1000001].worldState(true, time.Time{}) + queries := world.databaseQueries.Load() + + for tick := 1; tick <= 240; tick++ { + now := start.Add(time.Duration(tick) * 250 * time.Millisecond) + world.advanceNPCs(now) + world.advanceRegeneration(now) + if tick%4 == 0 { + if err := world.checkpointWorld(now); err != nil { + t.Fatal(err) + } + if err := world.flushPositions(now); err != nil { + t.Fatal(err) + } + } + } + + count := world.databaseQueries.Load() - queries + if count > 180 || world.characters[1000001].worldState(true, time.Time{}) != distant || world.savedNPCs[1000001].State != distant { + t.Fatal("distant population caused routine simulation or database traffic", count) + } + if world.characters[1000000].regenerationAt.IsZero() || world.savedNPCs[1000000].State.Character.Vitals.RegenerationAt.IsZero() { + t.Fatal("nearby NPC was not simulated and checkpointed") + } + t.Logf("1000 dormant NPCs, one nearby NPC and one player: %d queries over 60 simulated seconds", count) +} + +func TestNPCActivitySavesFinalPositionWhenGraceExpires(t *testing.T) { + world := newCheckpointWorld(t) + world.clients[1] = &worldClient{id: 1, ready: true} + now := time.Now() + if err := world.checkpointWorld(now); err != nil { + t.Fatal(err) + } + saved := world.savedNPCs[1000000] + saved.NextSave = now.Add(time.Hour) + world.savedNPCs[1000000] = saved + world.characters[1000000].position[0] = 53 + world.characters[1].position[0] = 2000 + + if err := world.checkpointWorld(now.Add(5 * time.Minute)); err != nil { + t.Fatal(err) + } + var x float32 + if err := world.db.QueryRow("SELECT position_x FROM characters WHERE id=1000000").Scan(&x); err != nil { + t.Fatal(err) + } + queries := world.databaseQueries.Load() + if err := world.checkpointWorld(now.Add(5*time.Minute + time.Second)); err != nil { + t.Fatal(err) + } + + if x != 53 || world.databaseQueries.Load()-queries != 2 { + t.Fatal("NPC dormancy must save the final state once", x, world.databaseQueries.Load()-queries) + } +} + +func TestNPCActivityGracePeriodAllowsHealingThenSleeps(t *testing.T) { + world, _, start := newNPCRegenerationWorld(t) + npc := world.characters[1000000] + world.advanceRegeneration(start) + delete(world.clients, 1) + + world.advanceRegeneration(start.Add(2 * time.Second)) + world.advanceRegeneration(start.Add(5*time.Minute - time.Second)) + if npc.health != 22 { + t.Fatal("recently observed NPC stopped healing", npc.health) + } + clock := npc.regenerationAt + world.advanceRegeneration(start.Add(5 * time.Minute)) + world.advanceRegeneration(start.Add(time.Hour)) + if npc.health != 22 || npc.regenerationAt != clock { + t.Fatal("dormant NPC continued healing", npc.health, npc.regenerationAt) + } + + // A returning player refreshes the grace period without replaying missed heals. + world.clients[1] = &worldClient{id: 1, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)} + world.advanceRegeneration(start.Add(time.Hour)) + delete(world.clients, 1) + world.advanceRegeneration(start.Add(time.Hour + 2*time.Second)) + if npc.health != 24 { + t.Fatal("returning player did not renew NPC activity", npc.health) + } +} diff --git a/server/npc_navigation_test.go b/server/npc_navigation_test.go @@ -205,7 +205,7 @@ func TestMissionNPCRootClearsPendingDetour(t *testing.T) { } } -func TestMissionNPCColdLoadReplansTheReturnWithoutObservers(t *testing.T) { +func TestMissionNPCColdLoadResumesReturnWhenObserved(t *testing.T) { world, _, _ := enteredMissionEncounterWorld(t) npc := world.characters[2000003] npc.position = [3]float32{15, .011, 15} @@ -225,6 +225,12 @@ func TestMissionNPCColdLoadReplansTheReturnWithoutObservers(t *testing.T) { restored := cold.characters[npc.id] cached := len(restored.motion.route) cold.lastNPCUpdate = start + before := restored.position + cold.advanceNPCs(start.Add(250 * time.Millisecond)) + if restored.position != before || len(restored.motion.route) != 0 { + t.Fatal("unobserved cold NPC advanced its return") + } + cold.clients[1] = &worldClient{id: 1, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)} for tick := 1; tick <= 96; tick++ { cold.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond)) } diff --git a/server/npc_outdoor_surface_test.go b/server/npc_outdoor_surface_test.go @@ -67,12 +67,14 @@ func TestNPCOutdoorReturnLeavesWaterAndRetainsHomeAfterColdLoad(t *testing.T) { t.Fatal(err) } cold := newTestInventoryServer(t) + cold.characters[1] = &character{id: 1, playfield: npc.playfield, position: [3]float32{138, 13.5, 98}, health: 100} + cold.clients[1] = &worldClient{id: 1, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)} cold.geometry, cold.terrain = world.geometry, world.terrain cold.lastNPCUpdate = now.Add(5 * time.Second) returning := cold.characters[npc.id] returning.motion.returning = true - for step := 21; step <= 80; step++ { + for step := 21; step <= 80 && returning.motion.returning; step++ { cold.advanceNPCs(now.Add(time.Duration(step) * 250 * time.Millisecond)) } diff --git a/server/npc_regeneration.go b/server/npc_regeneration.go @@ -4,7 +4,7 @@ import "time" func (server *server) advanceNPCRegeneration_locked(now time.Time, updates map[*worldClient][][]byte) { for _, npc := range server.characters { - if !npc.npc || npc.health == 0 { + if !npc.npc || npc.health == 0 || !server.npcActive_locked(npc, now) { continue } if npc.regenerationAt.IsZero() { diff --git a/server/npc_regeneration_test.go b/server/npc_regeneration_test.go @@ -262,21 +262,20 @@ func TestNPCRegenerationSkipsDeadAndPlayerCharacters(t *testing.T) { } } -func TestNPCRegenerationContinuesWithoutObservers(t *testing.T) { +func TestNPCRegenerationStaysDormantWithoutObservers(t *testing.T) { world, conn, start := newNPCRegenerationWorld(t) delete(world.clients, 1) world.advanceRegeneration(start) world.advanceRegeneration(start.Add(2 * time.Second)) - if world.characters[1000000].health != 21 || len(conn.packets) != 0 { - t.Fatal("NPC recovery depended on an observer") + if world.characters[1000000].health != 20 || !world.characters[1000000].regenerationAt.IsZero() || len(conn.packets) != 0 { + t.Fatal("unobserved NPC advanced recovery") } } func TestNPCRegenerationRespawnStartsWithFreshResourcesAndClock(t *testing.T) { world, _, start := newNPCRegenerationWorld(t) - delete(world.clients, 1) world.advanceRegeneration(start) world.advanceRegeneration(start.Add(2 * time.Second)) world.characters[1000000].health = 0 diff --git a/server/npc_shared_pursuit_test.go b/server/npc_shared_pursuit_test.go @@ -140,6 +140,8 @@ func TestFixedNPCColdLoadReturnsWithoutRestoringCombat(t *testing.T) { before := npc.position cold := newTestInventoryServer(t) + cold.characters[1].playfield = npc.playfield + cold.clients[1] = &worldClient{id: 1, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)} cold.lastNPCUpdate = time.Now() cold.advanceNPCs(cold.lastNPCUpdate.Add(250 * time.Millisecond)) cold.advanceNPCs(cold.lastNPCUpdate.Add(250 * time.Millisecond)) diff --git a/server/pet_follow.go b/server/pet_follow.go @@ -84,7 +84,7 @@ func petFollowPacket(pet *character, target uint32) []byte { func (server *server) advancePetFollowing_locked(now time.Time, updates map[*worldClient][][]byte) { for _, pet := range server.petExpiry { - if pet.followTarget == 0 { + if pet.followTarget == 0 || !server.npcActive_locked(pet, now) { continue } seconds := min(.25, max(0, now.Sub(pet.movement.updatedAt).Seconds())) diff --git a/server/roaming.go b/server/roaming.go @@ -44,18 +44,16 @@ func (server *server) advanceNPCs(now time.Time) { server.lastNPCUpdate = now clients := make(map[*worldClient][][]byte) - zones := make(map[uint32]bool) - for id, client := range server.clients { - if client.ready { + for _, client := range server.clients { + if client.ready && !client.loading { clients[client] = nil - zones[server.characters[id].playfield] = true } } - // Idle roaming needs observers; active pursuit and returning home do not. - for zone, characters := range server.mobileNPCs { + // Dormant NPCs keep their state until a nearby player returns. + for _, characters := range server.mobileNPCs { for _, character := range characters { - if character.health == 0 || !zones[zone] && character.fighting == 0 && !character.motion.returning { + if character.health == 0 || !server.npcActive_locked(character, now) { continue } if server.geometry.physical(character.playfield) { @@ -68,7 +66,7 @@ func (server *server) advanceNPCs(now time.Time) { if server.advanceNPCPursuit_locked(character, now, seconds, clients) { continue } - if !zones[zone] || character.fighting != 0 || !character.motion.roaming { + if character.fighting != 0 || !character.motion.roaming { continue } if character.motion.nextMove.IsZero() { diff --git a/server/state.go b/server/state.go @@ -51,6 +51,7 @@ type character struct { returnDoor *doorOrigin npc bool npcDefinitionID string + npcActiveUntil time.Time motion *npcMotion pet *ownedPet pets map[uint32]*character @@ -124,7 +125,7 @@ type server struct { databaseMutex sync.Mutex db *sql.DB savedNPCs map[uint32]savedNPC - npcZones map[uint32]bool + activeNPCs map[uint32]bool itemPlacements map[uint32]itemPlacement loginPort int worldPort int diff --git a/server/world_store.go b/server/world_store.go @@ -65,7 +65,7 @@ func (npc *character) worldState(present bool, respawnAt time.Time) npcState { return state } -func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[uint32]bool) (map[uint32]savedNPC, error) { +func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[uint32]bool) (map[uint32]savedNPC, error) { characters := maps.Clone(server.characters) deadlines := make(map[uint32]time.Time) for _, respawn := range server.npcRespawns { @@ -92,7 +92,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui } defer npcWrite.Close() - // Routine checkpoints are staggered; unobserved zones retain their last snapshot. + // Routine checkpoints are staggered; dormant NPCs retain their last snapshot. now := store.checkpointAt if now.IsZero() { now = time.Now() @@ -106,19 +106,19 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui continue } previous, exists := server.savedNPCs[id] - leaving := server.npcZones[npc.playfield] && !zones[npc.playfield] + leaving := server.activeNPCs[id] && !active[id] corpse := corpseState{} if npc.corpse != nil { corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt, npc.corpse.lootOrder} } // Loot transactions must persist corpse ownership and cash atomically. lootChanged := npc.corpse != nil && (!exists || !previous.State.HasCorpse || previous.State.Corpse != corpse) - if server.savedNPCs != nil && !store.flush && !leaving && !lootChanged && (!zones[npc.playfield] || exists && now.Before(previous.NextSave)) { + if server.savedNPCs != nil && !store.flush && !leaving && !lootChanged && (!active[id] || exists && now.Before(previous.NextSave)) { continue } state := npc.worldState(server.characters[id] != nil, deadlines[id]) nextSave := previous.NextSave - if nextSave.IsZero() || !server.npcZones[npc.playfield] && zones[npc.playfield] { + if nextSave.IsZero() || !server.activeNPCs[id] && active[id] { nextSave = now.Add(20*time.Second + time.Duration(rand.Int64N(int64(20*time.Second)))) } else if !now.Before(nextSave) { nextSave = now.Add(20 * time.Second) @@ -154,7 +154,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui } zone := previous.State.Character.Position.Playfield retiring := store.removedMission != nil && zone == store.removedMission.world - if !retiring && !store.flush && !zones[zone] && !server.npcZones[zone] { + if !retiring && !store.flush && !active[id] && !server.activeNPCs[id] { continue } if _, err := tx.Exec("DELETE FROM characters WHERE id = ?", id); err != nil {