commit ab9f5ded22666dc07f0b928c5c5d17a8050aaefd
parent d4bc084f622f0ae465060e0255d393f914a8b975
Author: anon <anon@example.com>
Date: Fri, 6 Nov 2026 23:51:40 +0000
Isolate zone navigation and index nearby NPC simulation
Diffstat:
44 files changed, 925 insertions(+), 201 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -73,6 +73,27 @@ that lock. Operations needing ordered simulation/session changes acquire
updates under the world lock and use the existing output queues after releasing
it. Do not hold the world lock across a blocking network write.
+Navigation searches use one goroutine and a bounded channel per playfield.
+Jobs own actor snapshots and pin immutable scene geometry; they never hold the
+simulation locks. The simulation accepts a result only while its motion request,
+starting pose, target and collision body still match. A full queue retries on the
+next tick. Mission retirement cancels its worker, and shutdown joins all workers
+before closing their resources. This isolates pathfinding, but other simulation
+and transaction work still shares the world lock; zones do not yet own all their
+mutable state independently.
+
+NPC visibility and activation query a grid of 200-metre X/Z cells keyed by
+playfield, then check exact horizontal distance. Movement updates membership,
+and spawn/removal must use `addNPC_locked`/`removeNPC_locked`. The active set keeps
+the fifteen-minute observation grace period. Routine NPC checkpoints inspect
+active actors and actors becoming dormant, and publish cache changes only after
+commit; they do not reconstruct inventory or clone every dormant NPC snapshot.
+
+Slow-lock logs report wait time separately from hold time, with the releasing
+caller. Simulation-loop logs report scheduling delay separately from elapsed
+work. Both log at 100ms, allowing the next gameplay stall to be attributed without
+assuming that an HTTP request's lock wait equals a simulation tick's duration.
+
The test-only API follows these boundaries: it serializes setup with the same
locks, refuses setup while the player has a game connection, invokes the
existing persistence methods and returns explicit snapshots. Its build tag
diff --git a/TODO.md b/TODO.md
@@ -48,6 +48,13 @@ research separately. More screenshots and test cases do not count as new gamepla
core. Restart removed the long stalls, and a 20-second CPU/mutex profile of the
idle server did not isolate the previous long holder. Reopen profiling when an
active-play stall reproduces; preserve gameplay and persistence cadence.
+ Path searches now run on snapshot workers per zone; nearby NPC queries use
+ spatial cells, and periodic checkpoints avoid full inventory reconstruction
+ and dormant snapshot copies. Slow-lock and loop timings distinguish contention,
+ lock hold time and scheduling delay. The original stall is still unattributed,
+ and ordinary state mutations still share the global lock. Full zone ownership
+ remains a separate architectural change, including command dispatch, transfers
+ and transaction completion.
- [x] **Use the original native character creation flow.** Login credentials are
collected in a compact modal with password confirmation at native naming,
diff --git a/server/combat_interest_test.go b/server/combat_interest_test.go
@@ -96,6 +96,7 @@ func TestCombatInterestWaitsForBothNPCParticipants(t *testing.T) {
world.advanceNPCs(now)
world.characters[1000001].position[0] = 2
+ world.indexNPC_locked(world.characters[1000001])
world.advanceNPCs(now.Add(time.Second))
if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x271b3a6b ||
diff --git a/server/corpse_expiry.go b/server/corpse_expiry.go
@@ -40,7 +40,7 @@ func (server *server) advanceCorpseExpiry(now time.Time) {
}
// Respawn holds its own source reference when its deadline is later.
- delete(server.characters, corpse.id)
+ server.removeNPC_locked(corpse.id)
if corpse.motion != nil {
server.mobileNPCs[corpse.playfield] = slices.DeleteFunc(server.mobileNPCs[corpse.playfield], func(other *character) bool { return other == corpse })
}
diff --git a/server/e2e_api.go b/server/e2e_api.go
@@ -42,9 +42,9 @@ func (server *server) e2ePlayer(w http.ResponseWriter, r *http.Request) {
// A stationary world-picking target uses the original Leet body.
id := server.nextNPC
server.nextNPC++
- server.characters[id] = &character{id: id, name: "Harness Leet", npc: true,
+ server.addNPC_locked(&character{id: id, name: "Harness Leet", npc: true,
playfield: player.playfield, position: request.Position, rotation: [4]float32{0, 0, 0, 1},
- appearance: 229, monsterData: 17655, level: 1, health: 100}
+ appearance: 229, monsterData: 17655, level: 1, health: 100})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]uint32{"id": id})
return
diff --git a/server/fixture_database_test.go b/server/fixture_database_test.go
@@ -20,6 +20,7 @@ func newServerForTest(t *testing.T) *server {
func registerTestDatabaseCleanup(t *testing.T, world *server) {
t.Helper()
t.Cleanup(func() {
+ world.stopNavigation()
if world.db == nil {
return
}
@@ -33,6 +34,33 @@ func registerTestDatabaseCleanup(t *testing.T, world *server) {
closeTestBrowserStreams(t, world)
}
+func advanceNavigationForTest(t *testing.T, world *server, now time.Time, advance func(time.Time)) {
+ t.Helper()
+ // Controlled clocks wait for search completion instead of racing simulated
+ // seconds against real worker time. Apply results through the normal tick.
+ for {
+ advance(now)
+ world.mutex.Lock()
+ var pending []*navigationJob
+ for _, actor := range world.characters {
+ if actor.motion != nil && actor.motion.navigation != nil {
+ pending = append(pending, actor.motion.navigation)
+ }
+ }
+ world.mutex.Unlock()
+ if len(pending) == 0 {
+ return
+ }
+ for _, job := range pending {
+ select {
+ case <-job.done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("navigation worker did not finish")
+ }
+ }
+ }
+}
+
func TestReloadFixtureClosesEveryDatabaseAtScopeExit(t *testing.T) {
t.Chdir(t.TempDir())
var first, second *server
diff --git a/server/interest.go b/server/interest.go
@@ -19,6 +19,10 @@ func (server *server) npcActive_locked(npc *character, now time.Time) bool {
x, z := player.position[0]-npc.position[0], player.position[2]-npc.position[2]
if x*x+z*z <= 200*200 {
npc.npcActiveUntil = now.Add(15 * time.Minute)
+ if server.simulatedNPCs == nil {
+ server.simulatedNPCs = make(map[uint32]*character)
+ }
+ server.simulatedNPCs[npc.id] = npc
return true
}
}
@@ -51,8 +55,8 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
// Send current state before motion when an NPC enters this observer's vicinity.
spawned := make(map[uint32]bool)
- for id, other := range server.characters {
- if !other.npc || other.playfield != player.playfield || client.npcs[id] {
+ for id, other := range server.nearbyNPCs_locked(player.playfield, position) {
+ if client.npcs[id] {
continue
}
x, z := other.position[0]-position[0], other.position[2]-position[2]
diff --git a/server/item_database.go b/server/item_database.go
@@ -161,8 +161,8 @@ func (server *server) persistItems_locked(store itemStore) error {
now = time.Now()
}
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) {
+ for id, npc := range server.simulationNPCs_locked(now) {
+ if store.removedMission == nil || npc.playfield != store.removedMission.world {
active[id] = true
}
}
@@ -286,7 +286,7 @@ func (server *server) persistItems_locked(store itemStore) error {
return err
}
}
- savedNPCs[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(20 * time.Second)}
+ savedNPCs.saved[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(20 * time.Second)}
}
if store.copiedMissionKey != nil {
var savedID uint32
@@ -482,7 +482,8 @@ func (server *server) persistItems_locked(store itemStore) error {
if err := tx.Commit(); err != nil {
return err
}
- server.itemPlacements, server.savedNPCs, server.activeNPCs = placements, savedNPCs, active
+ server.applyNPCCheckpoint_locked(savedNPCs)
+ server.itemPlacements, server.activeNPCs = placements, active
return nil
}
diff --git a/server/item_store.go b/server/item_store.go
@@ -275,7 +275,7 @@ func (server *server) writeItemStore_locked(store itemStore) error {
server.depletedResources = store.DepletedResources
server.nextItem = store.LastID
for _, npc := range store.spawnedNPCs {
- server.characters[npc.id] = npc
+ server.addNPC_locked(npc)
if npc.pet != nil {
server.petExpiry = append(server.petExpiry, npc)
} else {
diff --git a/server/mission_encounters_test.go b/server/mission_encounters_test.go
@@ -188,12 +188,12 @@ func TestMissionEncounterPursuitCrossesPortalAndReturnsWithoutDatabaseChurn(t *t
world.lastNPCUpdate = start
for tick := 1; tick <= 32; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick)*250*time.Millisecond), world.advanceNPCs)
}
far := npc.position
player.health = 0
for tick := 33; tick <= 80; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick)*250*time.Millisecond), world.advanceNPCs)
}
var storedZ float32
if err := world.db.QueryRow("SELECT position_z FROM characters WHERE id=?", id).Scan(&storedZ); err != nil {
@@ -220,7 +220,7 @@ func TestMissionEncounterPursuitCannotCrossTheOriginalRoomWall(t *testing.T) {
world.lastNPCUpdate = start
for tick := 1; tick <= tickCount; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick)*250*time.Millisecond), world.advanceNPCs)
}
if npc.position[0] <= 15 || npc.position[0] >= 18 || math.Abs(float64(npc.position[2]-28)) > 1 ||
diff --git a/server/mission_retirement.go b/server/mission_retirement.go
@@ -343,10 +343,14 @@ func (server *server) endMission_locked(mission acceptedMission, completed bool,
if npc := server.characters[id]; npc != nil && npc.pet != nil {
delete(server.characters[npc.pet.owner].pets, id)
}
- delete(server.characters, id)
+ server.removeNPC_locked(id)
delete(server.fighting, id)
}
delete(server.mobileNPCs, mission.world)
+ if navigator := server.navigation[mission.world]; navigator != nil {
+ close(navigator.stop)
+ delete(server.navigation, mission.world)
+ }
server.npcRespawns = slices.DeleteFunc(server.npcRespawns, func(respawn npcRespawn) bool { return respawn.npc.playfield == mission.world })
server.corpseExpiry = slices.DeleteFunc(server.corpseExpiry, func(corpse *character) bool { return corpse.playfield == mission.world })
server.petExpiry = slices.DeleteFunc(server.petExpiry, func(pet *character) bool { return pet.playfield == mission.world })
diff --git a/server/nano_buffs.go b/server/nano_buffs.go
@@ -476,8 +476,11 @@ func (server *server) handleNanoRemoval(client *worldClient, body []byte) error
return nil
}
-func (server *server) advanceNanoBuffs_locked(now time.Time, updates map[*worldClient][][]byte) {
- for _, player := range server.characters {
+func (server *server) advanceNanoBuffs_locked(now time.Time, affected []*character, updates map[*worldClient][][]byte) {
+ for _, player := range affected {
+ if len(player.activeNanos) == 0 {
+ continue
+ }
if player.npc && !server.npcActive_locked(player, now) {
continue
}
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -282,9 +282,16 @@ func (server *server) advanceNanos(now time.Time) {
server.mutex.Lock()
updates := make(map[*worldClient][][]byte)
server.expirePets_locked(now, updates)
- server.advancePeriodicNanos_locked(now, updates)
- server.advanceHealingNanos_locked(now, updates)
- server.advanceNanoBuffs_locked(now, updates)
+ // Enumerate effect owners once; actors without nanos need no proximity checks.
+ var affected []*character
+ for _, actor := range server.characters {
+ if len(actor.activeNanos) != 0 {
+ affected = append(affected, actor)
+ }
+ }
+ server.advancePeriodicNanos_locked(now, affected, updates)
+ server.advanceHealingNanos_locked(now, affected, updates)
+ server.advanceNanoBuffs_locked(now, affected, updates)
for id, client := range server.clients {
if client.nanoCast == nil || !now.After(client.nanoCast.readyAt) {
continue
diff --git a/server/nano_periodic.go b/server/nano_periodic.go
@@ -8,11 +8,11 @@ import (
"time"
)
-func (server *server) advancePeriodicNanos_locked(now time.Time, updates map[*worldClient][][]byte) {
- for _, target := range server.characters {
- if !target.npc || !server.npcActive_locked(target, now) || slices.IndexFunc(target.activeNanos, func(effect activeNano) bool {
+func (server *server) advancePeriodicNanos_locked(now time.Time, affected []*character, updates map[*worldClient][][]byte) {
+ for _, target := range affected {
+ if !target.npc || slices.IndexFunc(target.activeNanos, func(effect activeNano) bool {
return effect.ticksLeft != 0 && !effect.nextTick.After(now)
- }) < 0 {
+ }) < 0 || !server.npcActive_locked(target, now) {
continue
}
// Stage all overdue ticks together so a checkpoint cannot lose pending damage.
@@ -68,8 +68,8 @@ func (server *server) advancePeriodicNanos_locked(now time.Time, updates map[*wo
}
}
-func (server *server) advanceHealingNanos_locked(now time.Time, updates map[*worldClient][][]byte) {
- for _, target := range server.characters {
+func (server *server) advanceHealingNanos_locked(now time.Time, affected []*character, updates map[*worldClient][][]byte) {
+ for _, target := range affected {
if target.npc || target.health == 0 || slices.IndexFunc(target.activeNanos, func(effect activeNano) bool {
return effect.ticksLeft != 0 && !effect.nextTick.IsZero() && !effect.nextTick.After(now)
}) < 0 {
diff --git a/server/navigation_worker.go b/server/navigation_worker.go
@@ -0,0 +1,109 @@
+package main
+
+import (
+ "slices"
+ "time"
+)
+
+type navigationJob struct {
+ actor character
+ destination [3]float32
+ cancel chan struct{}
+ done chan struct{}
+ route [][3]float32
+}
+
+// Each playfield owns its search queue. A blocked search in one zone cannot
+// consume another zone's worker or hold either simulation mutex.
+type zoneNavigator struct {
+ jobs chan *navigationJob
+ stop chan struct{}
+ done chan struct{}
+}
+
+func (navigator *zoneNavigator) run() {
+ defer close(navigator.done)
+ for {
+ select {
+ case <-navigator.stop:
+ return
+ case job := <-navigator.jobs:
+ job.route = planNPCRoute(&job.actor, job.destination, job.cancel, navigator.stop)
+ close(job.done)
+ }
+ }
+}
+
+func (server *server) requestNPCRoute_locked(npc *character, destination [3]float32, now time.Time) bool {
+ if server.navigationStopped {
+ return false
+ }
+ // Motion replacement (death, zoning, a new command) drops the old job. A
+ // changed start, target or collision body invalidates an outstanding result.
+ if job := npc.motion.navigation; job != nil {
+ if job.actor.position != npc.position || job.actor.playfield != npc.playfield ||
+ job.actor.fighting != npc.fighting || job.actor.followTarget != npc.followTarget ||
+ job.actor.body != npc.body || surfaceDistanceSquared(job.destination, destination) >= 1 {
+ close(job.cancel)
+ npc.motion.navigation = nil
+ } else {
+ select {
+ case <-job.done:
+ npc.motion.route = job.route
+ npc.motion.navigation = nil
+ npc.motion.routeRetry = time.Time{}
+ if len(job.route) == 0 {
+ npc.motion.routeRetry = now.Add(time.Second)
+ }
+ return true
+ default:
+ return false
+ }
+ }
+ }
+
+ if server.navigation == nil {
+ server.navigation = make(map[uint32]*zoneNavigator)
+ }
+ navigator := server.navigation[npc.playfield]
+ if navigator == nil {
+ navigator = &zoneNavigator{jobs: make(chan *navigationJob, 32), stop: make(chan struct{}), done: make(chan struct{})}
+ server.navigation[npc.playfield] = navigator
+ server.navigationWorkers.Go(navigator.run)
+ }
+
+ // Only the worker can mutate the copied actor. Equipment and effect slices
+ // are read by collision and speed calculations; scenes are pinned for the job.
+ job := &navigationJob{actor: *npc, destination: destination, cancel: make(chan struct{}), done: make(chan struct{})}
+ job.actor.inventory.Items = slices.Clone(npc.inventory.Items)
+ job.actor.activeNanos = slices.Clone(npc.activeNanos)
+ job.actor.geometry = npc.geometry.navigationGeometry(npc.playfield)
+ select {
+ case navigator.jobs <- job:
+ npc.motion.navigation = job
+ default:
+ // Retry next tick rather than blocking the simulation on a full queue.
+ }
+ return false
+}
+
+func (geometry *sceneGeometry) navigationGeometry(playfield uint32) *sceneGeometry {
+ // Mission retirement may remove the live registration while a search runs.
+ // The completed scene stays immutable and alive until this job releases it.
+ return &sceneGeometry{cache: geometry, database: geometry.database,
+ playfields: geometry.playfields, terrain: geometry.terrain,
+ interiors: geometry.interiors, missions: map[uint32]*missionScene{playfield: geometry.mission(playfield)}}
+}
+
+func (server *server) stopNavigation() {
+ server.mutex.Lock()
+ if !server.navigationStopped {
+ server.navigationStopped = true
+ for _, navigator := range server.navigation {
+ close(navigator.stop)
+ }
+ clear(server.navigation)
+ }
+ server.mutex.Unlock()
+ server.navigationWorkers.Wait()
+}
diff --git a/server/navigation_worker_test.go b/server/navigation_worker_test.go
@@ -0,0 +1,175 @@
+package main
+
+import (
+ "testing"
+ "time"
+)
+
+func pauseNavigationForTest(t *testing.T, world *server, playfield uint32) {
+ t.Helper()
+ navigator := &zoneNavigator{jobs: make(chan *navigationJob, 32), stop: make(chan struct{}), done: make(chan struct{})}
+ world.navigation = map[uint32]*zoneNavigator{playfield: navigator}
+ resume := make(chan struct{})
+ world.navigationWorkers.Go(func() {
+ select {
+ case <-resume:
+ case <-navigator.stop:
+ }
+ navigator.run()
+ })
+ t.Cleanup(func() { close(resume); world.stopNavigation() })
+}
+
+func TestStalledZoneNavigationDoesNotBlockAnotherZone(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ first, npc := world.characters[1], world.characters[2000003]
+ first.position, npc.position = [3]float32{12.5, .011, 34}, [3]float32{15, .011, 15}
+ npc.fighting = first.id
+ npc.motion.moving = true
+ npc.motion.route = [][3]float32{{20, .011, 15}}
+ pauseNavigationForTest(t, world, first.playfield)
+ world.geometry.missions[65537] = world.geometry.mission(65536)
+ world.nextCharacter = max(world.nextCharacter, first.id)
+ second := world.newCharacter()
+ second.playfield, second.position, second.rotation = 65537, first.position, [4]float32{0, 0, 0, 1}
+ second.geometry = world.geometry
+ client := &worldClient{id: second.id, ready: true, target: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)}
+ world.clients[second.id] = client
+ other := *npc
+ other.id, other.playfield, other.fighting = 3000000, second.playfield, second.id
+ other.motion = &npcMotion{home: other.position}
+ world.addNPC_locked(&other)
+ now := time.Now()
+ world.lastNPCUpdate = now
+
+ finished := make(chan error, 1)
+ go func() {
+ world.advanceNPCs(now.Add(250 * time.Millisecond))
+ finished <- world.handleMovement(client, playerMovementRequest(second, 1))
+ }()
+ select {
+ case err := <-finished:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("a stalled zone blocked another zone's command")
+ }
+ if npc.motion.navigation == nil || other.motion.navigation == nil {
+ t.Fatal("fixture did not queue both zone searches")
+ }
+ select {
+ case <-other.motion.navigation.done:
+ case <-time.After(time.Second):
+ t.Fatal("another zone's navigation waited for the stalled worker")
+ }
+ world.advanceNPCs(now.Add(500 * time.Millisecond))
+ before := second.position
+ world.advancePlayerMovement(second.movement.updatedAt.Add(100 * time.Millisecond))
+
+ if npc.motion.moving || npc.position != [3]float32{15, .011, 15} || npc.motion.navigation == nil {
+ t.Fatal("stalled search unexpectedly advanced its actor")
+ }
+ if !other.motion.moving || len(other.motion.route) == 0 || second.position == before {
+ t.Fatal("independent zone did not advance navigation and player movement", other.motion, before, second.position)
+ }
+}
+
+func TestNavigationDiscardsAResultForAnOldTarget(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position, npc.position = [3]float32{12.5, .011, 34}, [3]float32{15, .011, 15}
+ npc.fighting = player.id
+ now := time.Now()
+ world.advanceNPCs(now)
+ job := npc.motion.navigation
+ if job == nil {
+ t.Fatal("fixture did not request a route")
+ }
+ select {
+ case <-job.done:
+ case <-time.After(time.Second):
+ t.Fatal("navigation worker did not finish")
+ }
+
+ player.position = [3]float32{15, .011, 43}
+ world.advanceNPCs(now.Add(250 * time.Millisecond))
+
+ if len(npc.motion.route) != 0 || npc.motion.navigation == nil || npc.motion.navigation == job {
+ t.Fatal("stale route was published or retained")
+ }
+ select {
+ case <-job.cancel:
+ default:
+ t.Fatal("replaced request was not cancelled")
+ }
+}
+
+func TestNavigationShutdownStopsQueuedWork(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position, npc.position = [3]float32{12.5, .011, 34}, [3]float32{15, .011, 15}
+ npc.fighting = player.id
+ pauseNavigationForTest(t, world, player.playfield)
+ world.advanceNPCs(time.Now())
+ navigator := world.navigation[player.playfield]
+
+ finished := make(chan struct{})
+ go func() { world.stopNavigation(); close(finished) }()
+
+ select {
+ case <-finished:
+ case <-time.After(time.Second):
+ t.Fatal("shutdown waited for queued navigation work")
+ }
+ select {
+ case <-navigator.done:
+ default:
+ t.Fatal("shutdown retained a navigation worker")
+ }
+}
+
+func TestNavigationRootCancelsAnOutstandingSearch(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position, npc.position = [3]float32{12.5, .011, 34}, [3]float32{15, .011, 15}
+ npc.fighting = player.id
+ pauseNavigationForTest(t, world, player.playfield)
+ now := time.Now()
+ world.advanceNPCs(now)
+ job := npc.motion.navigation
+ npc.activeNanos = []activeNano{{program: 42110, caster: player.id, expiresAt: now.Add(time.Minute)}}
+
+ world.advanceNPCs(now.Add(250 * time.Millisecond))
+
+ if npc.motion.navigation != nil || npc.motion.moving || npc.position != [3]float32{15, .011, 15} {
+ t.Fatal("root retained pending navigation or moved the NPC")
+ }
+ select {
+ case <-job.cancel:
+ default:
+ t.Fatal("root did not cancel the outstanding search")
+ }
+}
+
+func TestNavigationMissionRetirementStopsItsWorker(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position, npc.position = [3]float32{12.5, .011, 34}, [3]float32{15, .011, 15}
+ npc.fighting = player.id
+ zone := player.playfield
+ pauseNavigationForTest(t, world, zone)
+ world.advanceNPCs(time.Now())
+ navigator := world.navigation[zone]
+
+ err := world.handleMissionRemoval(world.clients[1], missionRemovalPacket(1, 2)[20:])
+
+ if err != nil || world.navigation[zone] != nil || world.characters[npc.id] != nil {
+ t.Fatal("mission retirement retained its worker or NPC", err)
+ }
+ select {
+ case <-navigator.done:
+ case <-time.After(time.Second):
+ t.Fatal("retired mission's navigation worker did not stop")
+ }
+}
diff --git a/server/npc_activity_test.go b/server/npc_activity_test.go
@@ -136,7 +136,7 @@ func TestNPCActivitySavesFinalPositionWhenGraceExpires(t *testing.T) {
t.Fatal(err)
}
- if x != 53 || world.databaseQueries.Load()-queries != 2 {
+ if x != 53 || world.databaseQueries.Load()-queries != 0 {
t.Fatal("NPC dormancy must save the final state once", x, world.databaseQueries.Load()-queries)
}
}
diff --git a/server/npc_checkpoint_batch_test.go b/server/npc_checkpoint_batch_test.go
@@ -50,9 +50,9 @@ func TestNPCCheckpointBatchesOnlyChangedTables(t *testing.T) {
t.Fatal(err)
}
- want := uint64(12)
+ want := uint64(10)
if change == "both" {
- want = 22
+ want = 20
}
if got := world.databaseQueries.Load() - queries; got != want {
t.Fatalf("1000 NPC checkpoints: got %d queries, want %d", got, want)
@@ -82,7 +82,7 @@ func TestNPCCheckpointBatchesOnlyChangedTables(t *testing.T) {
if err := world.checkpointWorld(now.Add(19 * time.Second)); err != nil {
t.Fatal(err)
}
- if world.databaseQueries.Load()-queries != 2 || world.savedNPCs[1000000].State.Character.Position.Position[0] == 54 {
+ if world.databaseQueries.Load()-queries != 0 || world.savedNPCs[1000000].State.Character.Position.Position[0] == 54 {
t.Fatal("routine movement persisted before 20 seconds")
}
})
diff --git a/server/npc_index.go b/server/npc_index.go
@@ -0,0 +1,107 @@
+package main
+
+import (
+ "iter"
+ "math"
+ "time"
+)
+
+type npcCell struct {
+ playfield uint32
+ x, z int
+}
+
+func (server *server) nearbyNPCs_locked(playfield uint32, position [3]float32) iter.Seq2[uint32, *character] {
+ if server.npcCells == nil {
+ server.npcCells = make(map[npcCell]map[uint32]*character)
+ server.npcLocations = make(map[uint32]npcCell)
+ for _, actor := range server.characters {
+ if actor.npc {
+ server.indexNPC_locked(actor)
+ }
+ }
+ }
+ // A 200m cell and its eight neighbours cover both interest radii. Callers
+ // still check exact distance, including the corners of these square cells.
+ x, z := int(math.Floor(float64(position[0])/200)), int(math.Floor(float64(position[2])/200))
+ return func(yield func(uint32, *character) bool) {
+ for dx := -1; dx <= 1; dx++ {
+ for dz := -1; dz <= 1; dz++ {
+ for id, npc := range server.npcCells[npcCell{playfield, x + dx, z + dz}] {
+ if !yield(id, npc) {
+ return
+ }
+ }
+ }
+ }
+ }
+}
+
+func (server *server) indexNPC_locked(npc *character) {
+ if server.npcCells == nil {
+ return
+ }
+ cell := npcCell{npc.playfield, int(math.Floor(float64(npc.position[0]) / 200)), int(math.Floor(float64(npc.position[2]) / 200))}
+ if previous, exists := server.npcLocations[npc.id]; exists {
+ if previous == cell && server.npcCells[cell][npc.id] == npc {
+ return
+ }
+ delete(server.npcCells[previous], npc.id)
+ if len(server.npcCells[previous]) == 0 {
+ delete(server.npcCells, previous)
+ }
+ }
+ if server.npcCells[cell] == nil {
+ server.npcCells[cell] = make(map[uint32]*character)
+ }
+ server.npcCells[cell][npc.id] = npc
+ server.npcLocations[npc.id] = cell
+}
+
+func (server *server) addNPC_locked(npc *character) {
+ server.characters[npc.id] = npc
+ server.indexNPC_locked(npc)
+}
+
+func (server *server) removeNPC_locked(id uint32) {
+ if npc := server.characters[id]; npc != nil && npc.motion != nil && npc.motion.navigation != nil {
+ close(npc.motion.navigation.cancel)
+ npc.motion.navigation = nil
+ }
+ if cell, exists := server.npcLocations[id]; exists {
+ delete(server.npcCells[cell], id)
+ if len(server.npcCells[cell]) == 0 {
+ delete(server.npcCells, cell)
+ }
+ delete(server.npcLocations, id)
+ }
+ delete(server.characters, id)
+ delete(server.simulatedNPCs, id)
+}
+
+func (server *server) simulationNPCs_locked(now time.Time) map[uint32]*character {
+ if server.simulatedNPCs == nil {
+ server.simulatedNPCs = make(map[uint32]*character)
+ }
+ // Previously observed NPCs retain the fifteen-minute grace period without
+ // rescanning distant cells or unoccupied zones.
+ for id, client := range server.clients {
+ if !client.ready || client.loading {
+ continue
+ }
+ player := server.characters[id]
+ for _, npc := range server.nearbyNPCs_locked(player.playfield, player.position) {
+ x, z := player.position[0]-npc.position[0], player.position[2]-npc.position[2]
+ if x*x+z*z <= 200*200 {
+ npc.npcActiveUntil = now.Add(15 * time.Minute)
+ server.simulatedNPCs[npc.id] = npc
+ }
+ }
+ }
+ for id, npc := range server.simulatedNPCs {
+ if server.characters[id] != npc || !now.Before(npc.npcActiveUntil) {
+ delete(server.simulatedNPCs, id)
+ }
+ }
+ return server.simulatedNPCs
+}
diff --git a/server/npc_index_test.go b/server/npc_index_test.go
@@ -0,0 +1,101 @@
+package main
+
+import (
+ "fmt"
+ "testing"
+ "time"
+)
+
+func TestNPCSpatialInterestPreservesRadiusAndZoneBoundaries(t *testing.T) {
+ world, _, now := newNPCPursuitWorld(t)
+ player := world.characters[1]
+ player.position = [3]float32{}
+ world.clients[1].npcs = make(map[uint32]bool)
+ template := *world.characters[1000000]
+ world.removeNPC_locked(template.id)
+ for i, position := range [][3]float32{{-180, 1000, 0}, {180, 0, 0}, {180.01, 0, 0}, {150, 0, 150}, {0, 0, -200}, {0, 0, -200.01}} {
+ npc := template
+ npc.id, npc.position, npc.motion, npc.fighting = uint32(1000000+i), position, nil, 0
+ world.addNPC_locked(&npc)
+ }
+ otherZone := template
+ otherZone.id, otherZone.playfield, otherZone.position = 2000000, 635, [3]float32{}
+ world.addNPC_locked(&otherZone)
+
+ world.advanceNPCs(now)
+
+ if visible := world.clients[1].npcs; len(visible) != 2 || !visible[1000000] || !visible[1000001] {
+ t.Fatal("spatial interest changed the 180m horizontal radius", visible)
+ }
+ if active := world.simulatedNPCs; len(active) != 4 || active[1000000] == nil || active[1000001] == nil || active[1000002] == nil || active[1000004] == nil {
+ t.Fatal("spatial activation changed the 200m radius or included another zone", active)
+ }
+}
+
+func TestNPCSpatialInterestFollowsMotionAcrossCells(t *testing.T) {
+ world, _, now := newNPCPursuitWorld(t)
+ world.characters[1].position = [3]float32{401, 0, 0}
+ world.clients[1].npcs = make(map[uint32]bool)
+ npc := world.characters[1000000]
+ npc.position = [3]float32{199, 0, 0}
+ npc.npcActiveUntil = now.Add(time.Minute)
+ npc.fighting = 0
+ npc.motion = &npcMotion{home: [3]float32{300, 0, 0}, returning: true}
+ world.simulatedNPCs = map[uint32]*character{npc.id: npc}
+ world.advanceNPCs(now)
+
+ for tick := 1; tick <= 32; tick++ {
+ world.advanceNPCs(now.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if npc.position[0] <= 221 || !world.clients[1].npcs[npc.id] {
+ t.Fatal("moving NPC was lost in its old spatial cell", npc.position, world.clients[1].npcs)
+ }
+ if len(world.npcCells) != 1 || len(world.npcCells[npcCell{950, 1, 0}]) != 1 {
+ t.Fatal("motion retained stale cell membership", world.npcCells)
+ }
+}
+
+func TestNPCSpatialIndexUpdatesSpawnsAndRemovals(t *testing.T) {
+ world, _, now := newNPCPursuitWorld(t)
+ world.advanceNPCs(now)
+ npc := *world.characters[1000000]
+ npc.id, npc.position, npc.motion, npc.fighting = 1000001, [3]float32{20, 0, 0}, nil, 0
+
+ world.removeNPC_locked(1000000)
+ world.addNPC_locked(&npc)
+ world.advanceNPCs(now.Add(250 * time.Millisecond))
+
+ if visible := world.clients[1].npcs; len(visible) != 1 || !visible[npc.id] {
+ t.Fatal("spawn/removal did not update spatial interest", visible)
+ }
+ if len(world.npcLocations) != 1 || len(world.npcCells[npcCell{950, 0, 0}]) != 1 {
+ t.Fatal("removed NPC retained spatial membership")
+ }
+}
+
+func BenchmarkNPCSpatialProximity(b *testing.B) {
+ for _, population := range []int{1000, 100000} {
+ b.Run(fmt.Sprint(population), func(b *testing.B) {
+ world := &server{characters: make(map[uint32]*character)}
+ world.addNPC_locked(&character{id: 1, npc: true, playfield: 950, position: [3]float32{1, 0, 0}})
+ for id := 2; id <= population; id++ {
+ world.addNPC_locked(&character{id: uint32(id), npc: true, playfield: 950, position: [3]float32{2000 + float32(id), 0, 0}})
+ }
+ world.nearbyNPCs_locked(950, [3]float32{})
+ b.ResetTimer()
+ for b.Loop() {
+ candidates, count := 0, 0
+ for _, npc := range world.nearbyNPCs_locked(950, [3]float32{}) {
+ candidates++
+ if surfaceDistanceSquared(npc.position, [3]float32{}) <= 200*200 {
+ count++
+ }
+ }
+ if candidates != 1 || count != 1 {
+ b.Fatal("query visited distant population", candidates, count)
+ }
+ }
+ })
+ }
+}
diff --git a/server/npc_motion_test.go b/server/npc_motion_test.go
@@ -26,7 +26,7 @@ func TestNPCRoamingMatchesNativeAccelerationAndWaypointArrival(t *testing.T) {
world.characters[1000000].motion.moving = true
world.characters[1000000].motion.nextMove = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if math.Abs(float64(world.characters[1000000].position[0]-scenario.position)) > .0001 || world.characters[1000000].motion.moving != scenario.moving {
t.Fatalf("native acceleration/arrival: position=%v moving=%t", world.characters[1000000].position, world.characters[1000000].motion.moving)
@@ -53,7 +53,7 @@ func TestNPCRoamingPublishesTheDestinationFloorHeight(t *testing.T) {
waters: map[uint32]*sceneWater{950: {zones: []waterZone{{maxHeight: -1}}}},
}
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if npc.position != [3]float32{5, 2.01, 5} || npc.motion.home != [3]float32{5, 0, 5} || !npc.motion.moving {
t.Fatal("choosing a route changed the current pose or retained home", npc.position, npc.motion)
@@ -73,7 +73,7 @@ func TestNPCRoamingDoesNotAdvertiseAnOccludedRoute(t *testing.T) {
npc.fighting = 0
npc.motion.home, npc.motion.nextMove = [3]float32{5, 0, 10}, start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if npc.motion.moving || npc.position != [3]float32{16, 0, 10} || len(conn.packets) != 0 {
t.Fatal("idle route crossed an obstruction hidden from the native follower", npc.position, npc.motion, conn.packets)
@@ -86,7 +86,7 @@ func TestNPCRoamingDoesNotAdvertiseAnOccludedRoute(t *testing.T) {
func TestNPCPursuitStartsItsRouteBeforeAdvancing(t *testing.T) {
world, conn, start := newNPCPursuitWorld(t)
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if world.characters[1000000].position != [3]float32{1, 0, 0} || !world.characters[1000000].motion.moving {
t.Fatalf("pursuit started with a position jump: %v", world.characters[1000000].position)
@@ -104,7 +104,7 @@ func TestNPCPursuitStopsAfterAdvancingTheCurrentInterval(t *testing.T) {
world.characters[1000000].running = true
world.characters[1000000].movement.velocity = [3]float32{4.5, 0, 0}
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if math.Abs(float64(world.characters[1000000].position[0]-2.125)) > .0001 || world.characters[1000000].motion.moving || world.characters[1000000].fighting != 1 {
t.Fatalf("pursuit arrival was deferred to an outdated pose: position=%v moving=%t fighting=%d", world.characters[1000000].position, world.characters[1000000].motion.moving, world.characters[1000000].fighting)
@@ -116,10 +116,10 @@ func TestNPCPursuitStopsAfterAdvancingTheCurrentInterval(t *testing.T) {
func TestNPCPursuitRouteChangesPreserveNativePosition(t *testing.T) {
world, conn, start := newNPCPursuitWorld(t)
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
world.characters[1].position = [3]float32{21, 0, 1}
- world.advanceNPCs(start.Add(500 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(500 * time.Millisecond), world.advanceNPCs)
if len(conn.packets) != 2 || !bytes.Equal(conn.packets[1][42:54], make([]byte, 12)) {
t.Fatalf("changing direction relocated the native actor: %x", conn.packets)
@@ -145,7 +145,7 @@ func TestNPCMotionStopsBeforeLeavingTheTerrainGrid(t *testing.T) {
npc.fighting = 0
}
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if npc.position != [3]float32{1.95, 0, 0} || npc.motion.moving || npc.movement.velocity != [3]float32{} {
t.Fatal("movement left the terrain grid", npc.position, npc.motion)
@@ -164,7 +164,7 @@ func TestNPCMotionRetainsItsGroundTangentVelocity(t *testing.T) {
world.lastNPCUpdate = start
for tick := 1; tick <= 7; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if math.Abs(float64(npc.movement.velocity[1])) <= 1 || npc.movement.velocity[2] >= 4.3 {
diff --git a/server/npc_navigation.go b/server/npc_navigation.go
@@ -70,7 +70,14 @@ func (queue *navigationQueue) Pop() any {
return node
}
-func planNPCRoute(npc *character, destination [3]float32) [][3]float32 {
+func planNPCRoute(npc *character, destination [3]float32, cancelled, stopped <-chan struct{}) [][3]float32 {
+ select {
+ case <-cancelled:
+ return nil
+ case <-stopped:
+ return nil
+ default:
+ }
// This bounded half-metre search is reconstruction policy, not a recovered
// original server algorithm. Probe copies never alter the live actor or DB.
if scene := npc.geometry.dungeon(npc.playfield); scene != nil {
@@ -87,6 +94,13 @@ func planNPCRoute(npc *character, destination [3]float32) [][3]float32 {
queue := navigationQueue{start}
costs := map[[3]int]float64{{0, int(math.Round(float64(npc.position[1]) * 2)), 0}: 0}
for visited := 0; queue.Len() != 0 && visited < 4096; visited++ {
+ select {
+ case <-cancelled:
+ return nil
+ case <-stopped:
+ return nil
+ default:
+ }
node := heap.Pop(&queue).(*navigationNode)
if surfaceDistanceSquared(node.actor.position, destination) < 1 {
if arrived, ok := probeNPCWalk(node.actor, destination); ok && surfaceDistanceSquared(arrived.position, destination) < .01 {
@@ -102,6 +116,13 @@ func planNPCRoute(npc *character, destination [3]float32) [][3]float32 {
actor := *npc
for len(points) != 0 {
for i := len(points) - 1; i >= 0; i-- {
+ select {
+ case <-cancelled:
+ return nil
+ case <-stopped:
+ return nil
+ default:
+ }
arrived, ok := probeNPCWalk(actor, points[i])
if ok && surfaceDistanceSquared(arrived.position, points[i]) < .01 {
route = append(route, points[i])
diff --git a/server/npc_navigation_test.go b/server/npc_navigation_test.go
@@ -26,7 +26,7 @@ func TestMissionNPCWalksAroundTheTongueAfterDescending(t *testing.T) {
}
for tick := 1; tick <= 48; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
lower := npc.position
player.position = [3]float32{15, .011, 28}
@@ -34,7 +34,7 @@ func TestMissionNPCWalksAroundTheTongueAfterDescending(t *testing.T) {
player.health = 0
}
for tick := 49; tick <= 144; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
var writes int
@@ -76,7 +76,7 @@ func TestMissionNPCDetoursIntoTheSidePassage(t *testing.T) {
npc.nextAttack = deadline
for tick := 1; tick <= 96; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if surfaceDistanceSquared(npc.position, player.position) >= 4 || npc.position[2] < 32 || npc.nextAttack != deadline {
@@ -99,7 +99,7 @@ func TestMissionNPCDetourDoesNotCutAcrossTheSidePassageWall(t *testing.T) {
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if len(npc.motion.route) < 2 || npc.motion.route[0][0] < 15 {
t.Fatal("detour requires sliding along the passage wall", npc.motion.route)
@@ -115,14 +115,14 @@ func TestMissionNPCRouteFollowsAChangingTarget(t *testing.T) {
world.fighting[npc.id] = npc
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
for tick := 2; tick <= 9; tick++ {
player.position[0] += .25
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
for tick := 10; tick <= 96; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if surfaceDistanceSquared(npc.position, player.position) >= 4 || npc.motion.moving || npc.fighting != player.id {
@@ -146,7 +146,7 @@ func TestMissionNPCLongRoutePublishesBoundedWaypointsToBothObservers(t *testing.
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
var routes [2][]byte
for index, output := range []*combatTestConn{first, second} {
@@ -173,9 +173,9 @@ func TestMissionNPCDoesNotCrossDisconnectedRooms(t *testing.T) {
world.lastNPCUpdate = start
before := npc.position
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
retry := npc.motion.routeRetry
- world.advanceNPCs(start.Add(500 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(500 * time.Millisecond), world.advanceNPCs)
if surfaceDistanceSquared(npc.position, before) >= .01 || npc.motion.moving || len(npc.motion.route) != 0 || !npc.motion.routeRetry.Equal(retry) || !retry.After(start.Add(time.Second)) {
t.Fatal("unreachable room caused movement or a search on every tick", npc.position, npc.motion)
@@ -191,14 +191,14 @@ func TestMissionNPCRootClearsPendingDetour(t *testing.T) {
world.fighting[npc.id] = npc
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
before := npc.position
if len(npc.motion.route) == 0 {
t.Fatal("fixture did not start an obstacle route")
}
npc.activeNanos = []activeNano{{program: 42110, caster: player.id, expiresAt: start.Add(time.Minute)}}
- world.advanceNPCs(start.Add(500 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(500 * time.Millisecond), world.advanceNPCs)
if npc.position != before || npc.motion.moving || npc.running || len(npc.motion.route) != 0 || npc.fighting != player.id {
t.Fatal("root retained an active waypoint route", npc.position, npc.motion)
@@ -213,7 +213,7 @@ func TestMissionNPCColdLoadResumesReturnWhenObserved(t *testing.T) {
npc.motion.returning = true
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if len(npc.motion.route) == 0 {
t.Fatal("fixture did not start an obstacle return")
}
@@ -226,13 +226,13 @@ func TestMissionNPCColdLoadResumesReturnWhenObserved(t *testing.T) {
cached := len(restored.motion.route)
cold.lastNPCUpdate = start
before := restored.position
- cold.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, cold, start.Add(250 * time.Millisecond), cold.advanceNPCs)
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))
+ advanceNavigationForTest(t, cold, start.Add(time.Duration(tick) * 250 * time.Millisecond), cold.advanceNPCs)
}
if cached != 0 || restored.motion.returning || restored.motion.moving || len(restored.motion.route) != 0 ||
@@ -250,12 +250,12 @@ func TestMissionNPCNewObserverReceivesTheRemainingDetourAfterSpawn(t *testing.T)
world.fighting[npc.id] = npc
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
observer := &combatTestConn{}
world.characters[2] = &character{id: 2, playfield: 65536, position: player.position}
world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)}
- world.advanceNPCs(start.Add(500 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(500 * time.Millisecond), world.advanceNPCs)
var keys []uint32
var route []byte
@@ -284,7 +284,7 @@ func TestMissionNPCDeathDiscardsItsPendingDetour(t *testing.T) {
world.fighting[npc.id] = npc
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if len(npc.motion.route) == 0 {
t.Fatal("fixture did not start an obstacle route")
}
@@ -296,7 +296,7 @@ func TestMissionNPCDeathDiscardsItsPendingDetour(t *testing.T) {
}
world.advanceCombat(player.nextAttack)
position := npc.position
- world.advanceNPCs(start.Add(time.Minute))
+ advanceNavigationForTest(t, world, start.Add(time.Minute), world.advanceNPCs)
if npc.health != 0 || npc.corpse == nil || npc.position != position || npc.motion.moving || npc.motion.returning || len(npc.motion.route) != 0 {
t.Fatal("dead NPC retained its obstacle route or moved its corpse", npc.position, npc.motion)
@@ -312,7 +312,7 @@ func TestMissionNPCFailedDeathCancelsItsDetourAndReturnsAlive(t *testing.T) {
world.fighting[npc.id] = npc
start := time.Now()
world.lastNPCUpdate = start
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
player.position, npc.health = npc.position, 1
world.combatRoll = func(uint32) uint32 { return 0 }
if err := world.handleCombat(client, attackPacket(player.id, npc.id)[20:]); err != nil {
@@ -328,7 +328,7 @@ func TestMissionNPCFailedDeathCancelsItsDetourAndReturnsAlive(t *testing.T) {
world.advanceCombat(player.nextAttack)
cancelled := !npc.motion.moving && len(npc.motion.route) == 0 && npc.motion.returning && npc.fighting == 0
for tick := 2; tick <= 96; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if !cancelled || npc.health != 1 || npc.corpse != nil || npc.motion.moving || npc.motion.returning ||
diff --git a/server/npc_outdoor_navigation_test.go b/server/npc_outdoor_navigation_test.go
@@ -46,7 +46,7 @@ func TestOutdoorNPCDetoursAroundOriginalTrainingScenery(t *testing.T) {
}
for tick := 1; tick <= 96; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if !npc.pursuitArrived(player.position) || !world.combatVisible_locked(npc, player, start.Add(24*time.Second)) ||
@@ -63,7 +63,7 @@ func TestOutdoorNPCDetourReturnsHomeAfterTargetLoss(t *testing.T) {
player.position, npc.position = [3]float32{50, 14.01, 58}, [3]float32{46, 14.01, 58}
npc.motion.home = npc.position
for tick := 1; tick <= 96; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if !npc.pursuitArrived(player.position) {
t.Fatal("fixture did not reach the far side of the original wall", npc.position)
@@ -71,7 +71,7 @@ func TestOutdoorNPCDetourReturnsHomeAfterTargetLoss(t *testing.T) {
player.health = 0
for tick := 97; tick <= 192; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if npc.motion.returning || npc.motion.moving || npc.fighting != 0 || surfaceDistanceSquared(npc.position, npc.motion.home) >= 1.01 {
@@ -87,7 +87,7 @@ func TestOutdoorNPCDoesNotDeclareArrivalThroughOriginalWall(t *testing.T) {
t.Fatal("fixture no longer places the close target behind the original wall")
}
- world.advanceNPCs(start.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs)
if !npc.motion.moving || len(npc.motion.route) < 2 || npc.pursuitArrived(player.position) {
t.Fatal("nearby target across a wall was mistaken for a clear arrival", npc.position, npc.motion)
@@ -99,12 +99,12 @@ func TestOutdoorNPCRouteFollowsAChangingTarget(t *testing.T) {
player, npc := world.characters[1], world.characters[1000000]
player.position, npc.position = [3]float32{50, 14.01, 58}, [3]float32{46, 14.01, 58}
for tick := 1; tick <= 4; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
player.position = [3]float32{60.5, 14.01, 70}
for tick := 5; tick <= 60; tick++ {
- world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, start.Add(time.Duration(tick) * 250 * time.Millisecond), world.advanceNPCs)
}
if !npc.pursuitArrived(player.position) || npc.motion.moving || npc.fighting != player.id {
diff --git a/server/npc_outdoor_surface_test.go b/server/npc_outdoor_surface_test.go
@@ -32,7 +32,7 @@ func TestNPCOutdoorRoamingUsesNativeWaterContact(t *testing.T) {
npc.motion.moving, npc.motion.nextMove = true, now
for step := 1; step <= 20; step++ {
- world.advanceNPCs(now.Add(time.Duration(step) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, now.Add(time.Duration(step)*250*time.Millisecond), world.advanceNPCs)
}
if npc.position[1] < 13.4 || npc.position[1] > 13.6 || !npc.movement.deepWater || npc.movement.components[0] != 4 || npc.motion.home != [3]float32{130, 14, 98} {
@@ -47,7 +47,7 @@ func TestNPCOutdoorPursuitUsesNativeWaterContact(t *testing.T) {
deadline, health := npc.nextAttack, npc.health
for step := 1; step <= 20; step++ {
- world.advanceNPCs(now.Add(time.Duration(step) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, now.Add(time.Duration(step)*250*time.Millisecond), world.advanceNPCs)
}
if npc.position[0] < 132 || npc.position[1] < 13.4 || npc.position[1] > 13.6 || !npc.movement.deepWater || npc.movement.components[0] != 4 ||
@@ -61,7 +61,7 @@ func TestNPCOutdoorReturnLeavesWaterAndRetainsHomeAfterColdLoad(t *testing.T) {
npc.motion.destination = [3]float32{134, 14, 98}
npc.motion.moving, npc.motion.nextMove = true, now
for step := 1; step <= 20; step++ {
- world.advanceNPCs(now.Add(time.Duration(step) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, world, now.Add(time.Duration(step)*250*time.Millisecond), world.advanceNPCs)
}
if err := world.flushWorld(); err != nil {
t.Fatal(err)
@@ -75,7 +75,7 @@ func TestNPCOutdoorReturnLeavesWaterAndRetainsHomeAfterColdLoad(t *testing.T) {
returning.motion.returning = true
for step := 21; step <= 80 && returning.motion.returning; step++ {
- cold.advanceNPCs(now.Add(time.Duration(step) * 250 * time.Millisecond))
+ advanceNavigationForTest(t, cold, now.Add(time.Duration(step)*250*time.Millisecond), cold.advanceNPCs)
}
if returning.motion.returning || returning.motion.moving || returning.movement.deepWater || returning.movement.components[0] != 2 ||
diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go
@@ -12,6 +12,7 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
if npc.combatProfile == nil || npc.fighting == 0 && !npc.motion.returning {
return false
}
+ defer server.indexNPC_locked(npc)
physical := server.geometry.physical(npc.playfield)
destination := npc.motion.home
if npc.fighting != 0 {
@@ -34,16 +35,18 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
changed := !npc.motion.moving || npc.motion.destination != destination
if physical {
- replan := len(npc.motion.route) == 0 && !now.Before(npc.motion.routeRetry)
+ replan := npc.motion.navigation != nil || len(npc.motion.route) == 0 && !now.Before(npc.motion.routeRetry)
if len(npc.motion.route) != 0 {
- replan = surfaceDistanceSquared(npc.motion.route[len(npc.motion.route)-1], destination) >= 1
+ replan = replan || surfaceDistanceSquared(npc.motion.route[len(npc.motion.route)-1], destination) >= 1
}
if replan {
- npc.motion.route = planNPCRoute(npc, destination)
- if len(npc.motion.route) == 0 {
- npc.motion.routeRetry = now.Add(time.Second)
- } else {
- npc.motion.routeRetry = time.Time{}
+ // Observers must stop following the old route while its replacement
+ // is pending; the completed job publishes a fresh starting pose.
+ if npc.motion.navigation == nil && npc.motion.moving {
+ server.stopNPCMotion_locked(npc, updates)
+ }
+ if !server.requestNPCRoute_locked(npc, destination, now) {
+ return true
}
changed = true
}
@@ -115,6 +118,10 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
}
func (server *server) stopNPCMotion_locked(npc *character, updates map[*worldClient][][]byte) {
+ if npc.motion.navigation != nil {
+ close(npc.motion.navigation.cancel)
+ npc.motion.navigation = nil
+ }
npc.motion.route = nil
if !npc.motion.moving {
return
diff --git a/server/npc_regeneration.go b/server/npc_regeneration.go
@@ -3,8 +3,8 @@ package main
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 || !server.npcActive_locked(npc, now) {
+ for _, npc := range server.simulationNPCs_locked(now) {
+ if npc.health == 0 {
continue
}
if npc.regenerationAt.IsZero() {
diff --git a/server/pet_attack_test.go b/server/pet_attack_test.go
@@ -51,7 +51,7 @@ func TestPetAttackPursuesAndCreditsOwnerWhileEnemyRetaliatesAgainstPet(t *testin
start := pet.movement.updatedAt
for tick := 1; tick <= 120 && target.health == 32; tick++ {
now := start.Add(time.Duration(tick) * 100 * time.Millisecond)
- world.advancePlayerMovement(now)
+ advanceNavigationForTest(t, world, now, world.advancePlayerMovement)
world.advanceCombat(now)
}
if target.health != 16 || target.fighting != pet.id || target.threat[pet.id] != 16 ||
@@ -60,8 +60,8 @@ func TestPetAttackPursuesAndCreditsOwnerWhileEnemyRetaliatesAgainstPet(t *testin
}
for tick := 1; tick <= 50 && pet.health == 17; tick++ {
now := target.nextAttack.Add(time.Duration(tick) * 100 * time.Millisecond)
- world.advancePlayerMovement(now)
- world.advanceNPCs(now)
+ advanceNavigationForTest(t, world, now, world.advancePlayerMovement)
+ advanceNavigationForTest(t, world, now, world.advanceNPCs)
world.advanceCombat(now)
}
if pet.health != 9 || owner.health != ownerHealth {
@@ -148,7 +148,7 @@ func TestPetCombatStopsWhenOwnerBecomesUnavailable(t *testing.T) {
}
world.advanceCombat(pet.nextAttack)
- world.advancePlayerMovement(time.Now().Add(time.Second))
+ advanceNavigationForTest(t, world, time.Now().Add(time.Second), world.advancePlayerMovement)
if pet.fighting != 0 || target.fighting != 0 || target.health != health || pet.health != 17 || pet.motion.returning {
t.Fatal("unavailable owner left pet combat or pursuit running")
@@ -278,11 +278,11 @@ func TestPetPursuitInterestReplaysRouteAndCombatAfterSpawn(t *testing.T) {
world.characters[1000000].position = [3]float32{40, 0, 0}
world.handlePetCommand(client, petAttackRequest())
now := pet.movement.updatedAt.Add(250 * time.Millisecond)
- world.advancePlayerMovement(now)
+ advanceNavigationForTest(t, world, now, world.advancePlayerMovement)
delete(client.npcs, pet.id)
output.packets = nil
- world.advanceNPCs(now)
+ advanceNavigationForTest(t, world, now, world.advanceNPCs)
spawn, route, attack := -1, -1, -1
for index, packet := range output.packets {
diff --git a/server/pet_dismiss_test.go b/server/pet_dismiss_test.go
@@ -28,7 +28,7 @@ func TestPetDismissCommitsOneRemovalAndStopsOldMotion(t *testing.T) {
world.handlePetCommand(client, petDismissRequest(1)[20:])
now := time.Now()
for tick := 1; tick <= 60; tick++ {
- world.advancePlayerMovement(now.Add(time.Duration(tick) * time.Second / 60))
+ advanceNavigationForTest(t, world, now.Add(time.Duration(tick) * time.Second / 60), world.advancePlayerMovement)
}
cold := newServerForTest(t)
diff --git a/server/pet_follow.go b/server/pet_follow.go
@@ -46,10 +46,14 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error {
if pet.health == 0 || pet.playfield != owner.playfield || pet.pet.expired(now) {
continue
}
+ if command == 7 && pet.fighting == target.id {
+ continue
+ }
+ if pet.motion != nil && pet.motion.navigation != nil {
+ close(pet.motion.navigation.cancel)
+ pet.motion.navigation = nil
+ }
if command == 7 {
- if pet.fighting == target.id {
- continue
- }
pet.followTarget = 0
pet.pet.paused = false
server.queueCombat_locked(updates, pet, owner, petFollowPacket(pet, 0))
@@ -148,9 +152,11 @@ func (server *server) advancePetFollowing_locked(now time.Time, updates map[*wor
// Share NPC route planning and native arrival forces, not player follow's 4m offset.
if pet.geometry.physical(pet.playfield) {
- if surfaceDistanceSquared(pet.motion.destination, owner.position) >= 1 ||
+ if pet.motion.navigation != nil || surfaceDistanceSquared(pet.motion.destination, owner.position) >= 1 ||
len(pet.motion.route) == 0 && !now.Before(pet.motion.routeRetry) {
- pet.motion.route = planNPCRoute(pet, owner.position)
+ if !server.requestNPCRoute_locked(pet, owner.position, now) {
+ continue
+ }
pet.motion.destination = owner.position
pet.motion.routeRetry = now.Add(time.Second)
}
@@ -160,6 +166,7 @@ func (server *server) advancePetFollowing_locked(now time.Time, updates map[*wor
}
previous := pet.position
_, blocked := pet.advanceNPCMotion(owner.position, seconds)
+ server.indexNPC_locked(pet)
pet.motion.moving = !blocked
if blocked {
pet.motion.route = nil
diff --git a/server/pet_follow_test.go b/server/pet_follow_test.go
@@ -28,7 +28,7 @@ func TestPetFollowMovesItsOwnedEntityWithoutRoutinePersistence(t *testing.T) {
err := world.handlePetCommand(client, petFollowRequest(1)[20:])
now := time.Now()
for step := 1; step <= 600; step++ {
- world.advancePlayerMovement(now.Add(time.Duration(step) * time.Second / 60))
+ advanceNavigationForTest(t, world, now.Add(time.Duration(step) * time.Second / 60), world.advancePlayerMovement)
}
if err != nil || pet.followTarget != 1 || pet.position[0] < start[0]+3 || surfaceDistanceSquared(pet.position, player.position) >= 5 ||
@@ -107,23 +107,23 @@ func TestPetFollowSuspendsAndResumesWithItsOwner(t *testing.T) {
world.handlePetCommand(client, petFollowRequest(1)[20:])
player.position = [3]float32{10, 0, 0}
now := pet.movement.updatedAt
- world.advancePlayerMovement(now.Add(250 * time.Millisecond))
+ advanceNavigationForTest(t, world, now.Add(250 * time.Millisecond), world.advancePlayerMovement)
start := pet.position
client.loading = true
output.packets = nil
- world.advancePlayerMovement(now.Add(500 * time.Millisecond))
- world.advancePlayerMovement(now.Add(time.Second))
+ advanceNavigationForTest(t, world, now.Add(500 * time.Millisecond), world.advancePlayerMovement)
+ advanceNavigationForTest(t, world, now.Add(time.Second), world.advancePlayerMovement)
if pet.position != start || !pet.pet.paused || len(output.packets) != 1 ||
binary.BigEndian.Uint32(output.packets[0][29:33]) != 0 {
t.Fatal("unavailable owner did not halt the native pet exactly once", pet.position, start, len(output.packets))
}
client.loading = false
- world.advancePlayerMovement(now.Add(1250 * time.Millisecond))
+ advanceNavigationForTest(t, world, now.Add(1250 * time.Millisecond), world.advancePlayerMovement)
pet.pet.expiresAt = now.Add(1500 * time.Millisecond)
- world.advancePlayerMovement(pet.pet.expiresAt)
+ advanceNavigationForTest(t, world, pet.pet.expiresAt, world.advancePlayerMovement)
stopped := pet.position
- world.advancePlayerMovement(now.Add(2 * time.Second))
+ advanceNavigationForTest(t, world, now.Add(2 * time.Second), world.advancePlayerMovement)
if start == stopped || pet.position != stopped || !pet.pet.paused || pet.followTarget != 1 ||
pet.movement.velocity != [3]float32{} {
diff --git a/server/pet_wait_test.go b/server/pet_wait_test.go
@@ -18,7 +18,7 @@ func TestPetWaitHoldsItsCommandedPositionUntilFollow(t *testing.T) {
now := time.Now()
if scenario == "moving" {
world.handlePetCommand(client, petFollowRequest(1)[20:])
- world.advancePlayerMovement(now.Add(time.Second))
+ advanceNavigationForTest(t, world, now.Add(time.Second), world.advancePlayerMovement)
if pet.movement.speed == 0 {
t.Fatal("fixture pet must be moving before wait")
}
@@ -32,7 +32,7 @@ func TestPetWaitHoldsItsCommandedPositionUntilFollow(t *testing.T) {
err := world.handlePetCommand(client, request)
player.position = [3]float32{30, 0, 0}
for tick := 1; tick <= 100; tick++ {
- world.advancePlayerMovement(now.Add(time.Second + time.Duration(tick)*100*time.Millisecond))
+ advanceNavigationForTest(t, world, now.Add(time.Second + time.Duration(tick)*100*time.Millisecond), world.advancePlayerMovement)
}
if err != nil || pet.followTarget != 0 || pet.motion != nil || pet.position != start ||
@@ -48,7 +48,7 @@ func TestPetWaitHoldsItsCommandedPositionUntilFollow(t *testing.T) {
if err := world.handlePetCommand(client, petFollowRequest(1)[20:]); err != nil {
t.Fatal(err)
}
- world.advancePlayerMovement(now.Add(12 * time.Second))
+ advanceNavigationForTest(t, world, now.Add(12 * time.Second), world.advancePlayerMovement)
if pet.followTarget != 1 || pet.position == start || player.nano != 25 {
t.Fatal("valid follow did not replace wait", pet.followTarget, pet.position)
}
diff --git a/server/pets.go b/server/pets.go
@@ -211,7 +211,7 @@ func (server *server) removePet_locked(pet *character, updates map[*worldClient]
server.cancelCombat_locked(pet.id, updates)
owner := server.characters[pet.pet.owner]
delete(owner.pets, pet.id)
- delete(server.characters, pet.id)
+ server.removeNPC_locked(pet.id)
delete(server.savedNPCs, pet.id)
server.petExpiry = slices.DeleteFunc(server.petExpiry, func(other *character) bool { return other.id == pet.id })
for _, client := range server.clients {
diff --git a/server/player_collision_test.go b/server/player_collision_test.go
@@ -16,7 +16,7 @@ func newPlayerCollisionWorld(t *testing.T) *server {
if err != nil {
t.Fatal(err)
}
- t.Cleanup(func() { world.geometry.database.file.Close() })
+ t.Cleanup(func() { world.stopNavigation(); world.geometry.database.file.Close() })
world.terrain, err = readTerrain()
if err != nil {
t.Fatal(err)
diff --git a/server/player_movement.go b/server/player_movement.go
@@ -594,7 +594,9 @@ func (server *server) movePlayers() {
ticker := time.NewTicker(time.Second / 60)
defer ticker.Stop()
for now := range ticker.C {
+ started := time.Now()
server.advancePlayerMovement(now)
+ reportSimulationTick("player movement", now, started)
}
}
diff --git a/server/respawn.go b/server/respawn.go
@@ -55,7 +55,7 @@ func (server *server) advanceNPCRespawns(now time.Time) {
server.mobileNPCs[npc.playfield][index] = npc
}
}
- server.characters[npc.id] = npc
+ server.addNPC_locked(npc)
spawned = true
}
diff --git a/server/roaming.go b/server/roaming.go
@@ -17,12 +17,14 @@ type npcMotion struct {
returning bool
route [][3]float32
routeRetry time.Time
+ navigation *navigationJob
}
func (server *server) roamNPCs() {
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
for now := range ticker.C {
+ started := time.Now()
server.advanceMissions(now)
server.advanceCorpseExpiry(now)
server.advanceNPCRespawns(now)
@@ -32,6 +34,7 @@ func (server *server) roamNPCs() {
server.advanceNanos(now)
server.advanceCombat(now)
server.advanceRegeneration(now)
+ reportSimulationTick("NPC and actions", now, started)
}
}
@@ -51,87 +54,86 @@ func (server *server) advanceNPCs(now time.Time) {
}
// Dormant NPCs keep their state until a nearby player returns.
- for _, characters := range server.mobileNPCs {
- for _, character := range characters {
- if character.health == 0 || !server.npcActive_locked(character, now) {
- continue
- }
- if server.geometry.physical(character.playfield) {
- character.geometry = server.geometry
- }
- if character.movementRestricted() {
- server.stopNPCMotion_locked(character, clients)
- continue
- }
- if server.advanceNPCPursuit_locked(character, now, seconds, clients) {
- continue
- }
- if character.fighting != 0 || !character.motion.roaming {
- continue
- }
- if character.motion.nextMove.IsZero() {
- character.motion.nextMove = now.Add(time.Duration(1+character.id%32) * 250 * time.Millisecond)
- }
- if now.Before(character.motion.nextMove) {
- continue
- }
+ for _, character := range server.simulationNPCs_locked(now) {
+ if character.health == 0 || character.motion == nil || character.pet != nil {
+ continue
+ }
+ if server.geometry.physical(character.playfield) {
+ character.geometry = server.geometry
+ }
+ if character.movementRestricted() {
+ server.stopNPCMotion_locked(character, clients)
+ continue
+ }
+ if server.advanceNPCPursuit_locked(character, now, seconds, clients) {
+ continue
+ }
+ if character.fighting != 0 || !character.motion.roaming {
+ continue
+ }
+ if character.motion.nextMove.IsZero() {
+ character.motion.nextMove = now.Add(time.Duration(1+character.id%32) * 250 * time.Millisecond)
+ }
+ if now.Before(character.motion.nextMove) {
+ continue
+ }
- // Pick a nearby destination relative to home, so repeated walks never drift.
- started := !character.motion.moving
- if !character.motion.moving {
- angle := rand.Float64() * 2 * math.Pi
- distance := 4 * math.Sqrt(rand.Float64())
- character.motion.destination = [3]float32{
- character.motion.home[0] + float32(math.Sin(angle)*distance),
- character.motion.home[1],
- character.motion.home[2] + float32(math.Cos(angle)*distance),
- }
- // Buried waypoints make the native follower stop short on rising ground.
- if character.geometry.physical(character.playfield) {
- point, normal := character.motion.destination, [3]float32{}
- character.geometry.floor(character.playfield, server.terrain[character.playfield], point, &point, &normal)
- character.motion.destination[1] = point[1] + .01
- // Idle walks need a clear approach; try another destination after the pause.
- if _, clear := probeNPCWalk(*character, character.motion.destination); !clear {
- character.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
- continue
- }
- }
- character.motion.moving = true
+ // Pick a nearby destination relative to home, so repeated walks never drift.
+ started := !character.motion.moving
+ if !character.motion.moving {
+ angle := rand.Float64() * 2 * math.Pi
+ distance := 4 * math.Sqrt(rand.Float64())
+ character.motion.destination = [3]float32{
+ character.motion.home[0] + float32(math.Sin(angle)*distance),
+ character.motion.home[1],
+ character.motion.home[2] + float32(math.Cos(angle)*distance),
}
- if started {
- x := float64(character.motion.destination[0] - character.position[0])
- z := float64(character.motion.destination[2] - character.position[2])
- angle := math.Atan2(x, z)
- character.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))}
- character.movement.action(character, 22)
- server.queueCombat_locked(clients, character, character, npcRoutePacket(character, character.position))
- continue
+ // Buried waypoints make the native follower stop short on rising ground.
+ if character.geometry.physical(character.playfield) {
+ point, normal := character.motion.destination, [3]float32{}
+ character.geometry.floor(character.playfield, server.terrain[character.playfield], point, &point, &normal)
+ character.motion.destination[1] = point[1] + .01
+ // Idle walks need a clear approach; try another destination after the pause.
+ if _, clear := probeNPCWalk(*character, character.motion.destination); !clear {
+ character.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
+ continue
+ }
}
+ character.motion.moving = true
+ }
+ if started {
+ x := float64(character.motion.destination[0] - character.position[0])
+ z := float64(character.motion.destination[2] - character.position[2])
+ angle := math.Atan2(x, z)
+ character.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))}
+ character.movement.action(character, 22)
+ server.queueCombat_locked(clients, character, character, npcRoutePacket(character, character.position))
+ continue
+ }
- // Use the same acceleration and waypoint arrival as the native vehicle.
- previous := character.position
- arrived, blocked := character.advanceNPCMotion(character.motion.destination, seconds)
- position := character.position
+ // Use the same acceleration and waypoint arrival as the native vehicle.
+ previous := character.position
+ arrived, blocked := character.advanceNPCMotion(character.motion.destination, seconds)
+ position := character.position
- // Preserve source offsets when physical scene geometry is unavailable.
- if ground := server.terrain[character.playfield]; ground != nil && !character.geometry.physical(character.playfield) {
- home, available := ground.elevation(character.motion.home[0], character.motion.home[2])
- if available {
- height, inside := ground.elevation(position[0], position[2])
- if inside {
- position[1] = character.motion.home[1] + height - home
- } else {
- position = previous
- arrived = true
- }
+ // Preserve source offsets when physical scene geometry is unavailable.
+ if ground := server.terrain[character.playfield]; ground != nil && !character.geometry.physical(character.playfield) {
+ home, available := ground.elevation(character.motion.home[0], character.motion.home[2])
+ if available {
+ height, inside := ground.elevation(position[0], position[2])
+ if inside {
+ position[1] = character.motion.home[1] + height - home
+ } else {
+ position = previous
+ arrived = true
}
}
- character.position = position
- if arrived || blocked {
- server.stopNPCMotion_locked(character, clients)
- character.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
- }
+ }
+ character.position = position
+ server.indexNPC_locked(character)
+ if arrived || blocked {
+ server.stopNPCMotion_locked(character, clients)
+ character.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
}
}
diff --git a/server/scene_geometry.go b/server/scene_geometry.go
@@ -7,6 +7,7 @@ import (
)
type sceneGeometry struct {
+ cache *sceneGeometry
database *gameDatabase
playfields map[uint32]scenePlayfield
mutex sync.Mutex
@@ -42,6 +43,9 @@ func readSceneGeometry(files fs.FS) (*sceneGeometry, error) {
}
func (geometry *sceneGeometry) model(identity uint32) collisionSphere {
+ if geometry.cache != nil {
+ return geometry.cache.model(identity)
+ }
geometry.mutex.Lock()
defer geometry.mutex.Unlock()
if sphere, loaded := geometry.models[identity]; loaded {
@@ -60,6 +64,9 @@ func (geometry *sceneGeometry) model(identity uint32) collisionSphere {
}
func (geometry *sceneGeometry) water(playfield uint32, ground *terrain) *sceneWater {
+ if geometry.cache != nil {
+ return geometry.cache.water(playfield, ground)
+ }
geometry.mutex.Lock()
defer geometry.mutex.Unlock()
if water, loaded := geometry.waters[playfield]; loaded {
@@ -81,6 +88,9 @@ func (geometry *sceneGeometry) water(playfield uint32, ground *terrain) *sceneWa
}
func (geometry *sceneGeometry) surface(identity uint32) *sceneSurface {
+ if geometry.cache != nil {
+ return geometry.cache.surface(identity)
+ }
geometry.mutex.Lock()
defer geometry.mutex.Unlock()
if surface, loaded := geometry.surfaces[identity]; loaded {
diff --git a/server/simulation.go b/server/simulation.go
@@ -14,6 +14,7 @@ func (server *server) startSimulation() {
// Call only before process exit: writers stay blocked after the final checkpoint.
func (server *server) shutdown() error {
+ server.stopNavigation()
server.updateMutex.Lock()
if err := server.flushPositions(time.Now().Add(20 * time.Second)); err != nil {
log.Printf("Saving positions on shutdown: %v", err)
diff --git a/server/simulation_timing.go b/server/simulation_timing.go
@@ -0,0 +1,38 @@
+package main
+
+import (
+ "log"
+ "runtime"
+ "sync"
+ "time"
+)
+
+// Report contention separately from the work performed by the lock holder.
+type simulationMutex struct {
+ mutex sync.Mutex
+ acquired time.Time
+ wait time.Duration
+}
+
+func (mutex *simulationMutex) Lock() {
+ started := time.Now()
+ mutex.mutex.Lock()
+ mutex.acquired = time.Now()
+ mutex.wait = mutex.acquired.Sub(started)
+}
+
+func (mutex *simulationMutex) Unlock() {
+ wait, held := mutex.wait, time.Since(mutex.acquired)
+ mutex.mutex.Unlock()
+ if wait >= 100*time.Millisecond || held >= 100*time.Millisecond {
+ pc, _, line, _ := runtime.Caller(1)
+ log.Printf("Slow simulation lock: caller=%s:%d wait=%s held=%s", runtime.FuncForPC(pc).Name(), line, wait, held)
+ }
+}
+
+func reportSimulationTick(name string, scheduled, started time.Time) {
+ delay, elapsed := started.Sub(scheduled), time.Since(started)
+ if delay >= 100*time.Millisecond || elapsed >= 100*time.Millisecond {
+ log.Printf("Slow simulation tick: phase=%s delay=%s elapsed=%s", name, max(0, delay), elapsed)
+ }
+}
diff --git a/server/state.go b/server/state.go
@@ -132,9 +132,9 @@ type server struct {
worldPort int
httpPort int
baseURL string
- mutex sync.Mutex
+ mutex simulationMutex
// Order entity-state packet batches; acquire before mutex.
- updateMutex sync.Mutex
+ updateMutex simulationMutex
nextCharacter uint32
nextNPC uint32
nextItem uint32
@@ -144,6 +144,12 @@ type server struct {
depletedResources map[uint32]bool
characters map[uint32]*character
mobileNPCs map[uint32][]*character
+ npcCells map[npcCell]map[uint32]*character
+ npcLocations map[uint32]npcCell
+ simulatedNPCs map[uint32]*character
+ navigation map[uint32]*zoneNavigator
+ navigationWorkers sync.WaitGroup
+ navigationStopped bool
npcRespawns []npcRespawn
petExpiry []*character
corpseExpiry []*character
@@ -218,7 +224,7 @@ func newServer() *server {
}
server.placeFallbackNPCs(spawns)
for _, spawn := range spawns {
- server.characters[spawn.id] = &spawn
+ server.addNPC_locked(&spawn)
server.nextNPC = max(server.nextNPC, spawn.id+1)
if spawn.motion != nil {
server.mobileNPCs[spawn.playfield] = append(server.mobileNPCs[spawn.playfield], &spawn)
diff --git a/server/users.go b/server/users.go
@@ -312,11 +312,13 @@ func (server *server) saveWorld() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for now := range ticker.C {
+ started := time.Now()
if err := server.checkpointWorld(now); err != nil {
log.Printf("Saving world: %v", err)
}
if err := server.flushPositions(now); err != nil {
log.Printf("Saving player positions: %v", err)
}
+ reportSimulationTick("checkpoint", now, started)
}
}
diff --git a/server/world_store.go b/server/world_store.go
@@ -44,6 +44,22 @@ type savedNPC struct {
NextSave time.Time
}
+type npcCheckpoint struct {
+ saved map[uint32]savedNPC
+ removed []uint32
+}
+
+func (server *server) applyNPCCheckpoint_locked(checkpoint npcCheckpoint) {
+ // Publish only after the transaction commits; failed writes retain their basis.
+ if server.savedNPCs == nil {
+ server.savedNPCs = make(map[uint32]savedNPC)
+ }
+ maps.Copy(server.savedNPCs, checkpoint.saved)
+ for _, id := range checkpoint.removed {
+ delete(server.savedNPCs, id)
+ }
+}
+
const npcColumns = "definition, present, respawn_at, leading_contributor, leading_team, idle_roaming, home_x, home_y, home_z, destination_x, destination_y, destination_z, next_move, moving, returning_home, has_corpse, looter, loot_team, credits, expires_at, loot_order"
func (state *npcState) fields() []any {
@@ -98,8 +114,24 @@ func writeNPCBatch(tx *sql.Tx, table, columns string, records [][]any) error {
return nil
}
-func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[uint32]bool) (map[uint32]savedNPC, error) {
- characters := maps.Clone(server.characters)
+func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[uint32]bool) (npcCheckpoint, error) {
+ characters, previousNPCs := server.characters, server.savedNPCs
+ if !store.checkpointAt.IsZero() && server.savedNPCs != nil {
+ // Only active actors and actors leaving their grace period can be due.
+ characters = make(map[uint32]*character, len(active)+len(server.activeNPCs))
+ previousNPCs = make(map[uint32]savedNPC, len(server.activeNPCs))
+ for id := range active {
+ characters[id] = server.characters[id]
+ }
+ for id := range server.activeNPCs {
+ if npc := server.characters[id]; npc != nil {
+ characters[id] = npc
+ }
+ previousNPCs[id] = server.savedNPCs[id]
+ }
+ } else if len(server.npcRespawns) != 0 || store.removedMission != nil {
+ characters = maps.Clone(server.characters)
+ }
deadlines := make(map[uint32]time.Time)
for _, respawn := range server.npcRespawns {
characters[respawn.npc.id] = respawn.npc
@@ -132,10 +164,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[u
if now.IsZero() {
now = time.Now()
}
- saved := maps.Clone(server.savedNPCs)
- if saved == nil {
- saved = make(map[uint32]savedNPC)
- }
+ checkpoint := npcCheckpoint{saved: make(map[uint32]savedNPC)}
for id, npc := range characters {
if !npc.npc {
continue
@@ -156,7 +185,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[u
if nextSave.IsZero() || !server.activeNPCs[id] && active[id] || !now.Before(nextSave) {
nextSave = now.Add(20*time.Second + time.Duration(rand.Int64N(int64(10*time.Second))))
}
- saved[id] = savedNPC{state, maps.Clone(npc.damageContributors), nextSave}
+ checkpoint.saved[id] = savedNPC{state, maps.Clone(npc.damageContributors), nextSave}
if !exists || previous.State.Character != state.Character {
characterRows = append(characterRows, append([]any{id}, state.Character.fields()...))
}
@@ -170,7 +199,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[u
}
if len(characterRows) == 100 || len(npcRows) == 100 {
if err := flush(); err != nil {
- return nil, err
+ return npcCheckpoint{}, err
}
}
// Effect time follows the same periodic checkpoint even when the NPC is still.
@@ -179,26 +208,26 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[u
}
}
if err := flush(); err != nil {
- return nil, err
+ return npcCheckpoint{}, err
}
// Referencing rows follow the actor batches in the same transaction.
for _, npc := range contributors {
if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", npc.id); err != nil {
- return nil, err
+ return npcCheckpoint{}, err
}
for contributor, damage := range npc.damageContributors {
if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", npc.id, contributor.player, contributor.team, damage); err != nil {
- return nil, err
+ return npcCheckpoint{}, err
}
}
}
for _, npc := range effects {
if err := writeActiveNanos(tx, npc, now); err != nil {
- return nil, err
+ return npcCheckpoint{}, err
}
}
- for id, previous := range server.savedNPCs {
+ for id, previous := range previousNPCs {
if characters[id] != nil {
continue
}
@@ -208,11 +237,11 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[u
continue
}
if _, err := tx.Exec("DELETE FROM characters WHERE id = ?", id); err != nil {
- return nil, err
+ return npcCheckpoint{}, err
}
- delete(saved, id)
+ checkpoint.removed = append(checkpoint.removed, id)
}
- return saved, nil
+ return checkpoint, nil
}
func (server *server) loadNPCs() (bool, error) {
@@ -267,7 +296,7 @@ func (server *server) loadNPCs() (bool, error) {
npc.corpse = &npcCorpse{looter: state.Corpse.Looter, team: state.Corpse.Team, credits: state.Corpse.Credits, expiresAt: state.Corpse.ExpiresAt, lootOrder: state.Corpse.LootOrder}
}
if state.Present {
- server.characters[npc.id] = npc
+ server.addNPC_locked(npc)
if npc.motion != nil && npc.health != 0 {
server.mobileNPCs[npc.playfield] = append(server.mobileNPCs[npc.playfield], npc)
}
@@ -327,10 +356,39 @@ func (server *server) flushWorld() error {
func (server *server) checkpointWorld(now time.Time) error {
server.mutex.Lock()
defer server.mutex.Unlock()
- store, err := server.itemStore_locked(&character{}, playerInventory{})
+ // The initial population needs the complete atomic world allocation once.
+ if server.savedNPCs == nil {
+ store, err := server.itemStore_locked(&character{}, playerInventory{})
+ if err != nil {
+ return err
+ }
+ store.checkpointAt = now
+ return server.writeItemStore_locked(store)
+ }
+
+ // Inventory changes already commit with their actions. Routine simulation
+ // checkpoints must not rebuild or validate every player's item ownership.
+ active := make(map[uint32]bool)
+ for id := range server.simulationNPCs_locked(now) {
+ active[id] = true
+ }
+ db, err := server.database()
if err != nil {
return err
}
- store.checkpointAt = now
- return server.writeItemStore_locked(store)
+ tx, err := db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ saved, err := server.writeNPCs_locked(tx, itemStore{checkpointAt: now}, active)
+ if err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ server.applyNPCCheckpoint_locked(saved)
+ server.activeNPCs = active
+ return nil
}
diff --git a/server/zoning.go b/server/zoning.go
@@ -216,7 +216,9 @@ func (server *server) checkZoneCrossings() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for now := range ticker.C {
+ started := time.Now()
server.advanceZoneCrossings(now)
+ reportSimulationTick("zone crossings", now, started)
}
}