commit 6979ef844909369bf07c7c8a62640ba189e0eb47
parent 63cb61926089c378a90b32b6b6693dbc07f63eb2
Author: anon <anon@example.com>
Date: Sat, 17 Oct 2026 03:51:30 +0000
Stream nearby NPCs to reduce client entity work
Diffstat:
7 files changed, 287 insertions(+), 40 deletions(-)
diff --git a/server/interest.go b/server/interest.go
@@ -0,0 +1,40 @@
+package main
+
+import "time"
+
+func (server *server) updateNPCInterest_locked(client *worldClient, now time.Time) [][]byte {
+ player := server.characters[client.id]
+ position := predictedPosition_locked(player, client, now)
+ var updates [][]byte
+
+ // Retain a margin beyond the 500-metre minimap query and avoid boundary churn.
+ // Original ddr.dll N3Msg_GetMapCharacters call: 0x2B05634A.
+ for id := range client.npcs {
+ other := server.characters[id]
+ if other != nil && other.playfield == player.playfield {
+ x, z := other.position[0]-position[0], other.position[2]-position[2]
+ if x*x+z*z <= 600*600 {
+ continue
+ }
+ }
+ updates = append(updates, n3Packet(0x36510078, 50000, id, nil))
+ delete(client.npcs, id)
+ }
+
+ // Send current state before motion when an NPC enters this observer's vicinity.
+ for id, other := range server.characters {
+ if !other.npc || other.playfield != player.playfield || client.npcs[id] {
+ continue
+ }
+ x, z := other.position[0]-position[0], other.position[2]-position[2]
+ if x*x+z*z > 550*550 {
+ continue
+ }
+ client.npcs[id] = true
+ updates = append(updates, characterPacket(other))
+ if other.roaming != nil && other.roaming.moving {
+ updates = append(updates, npcMovementPacket(other, 1))
+ }
+ }
+ return updates
+}
diff --git a/server/interest_test.go b/server/interest_test.go
@@ -0,0 +1,203 @@
+package main
+
+import (
+ "encoding/binary"
+ "math"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestLoginIncludesMinimapNPCsButNotDistantPopulation(t *testing.T) {
+ for _, target := range []bool{false, true} {
+ t.Run(map[bool]string{false: "original", true: "1491"}[target], func(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "[52, 14, 56]", "[1500, 1000, 1000]\n - [1550, 0, 1000]\n - [1551, 0, 1000]"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.position = [3]float32{1000, 0, 1000}
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
+ offset := 20
+ if target {
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ offset = 16
+ }
+
+ client.Write(cookie)
+ seen := make(map[uint32]bool)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(packet[offset:]) == 0x271b3a6b {
+ seen[binary.BigEndian.Uint32(packet[offset+8:])] = true
+ }
+ if binary.BigEndian.Uint32(packet[offset:]) == 0x5f52412e {
+ break
+ }
+ }
+
+ if len(seen) != 3 || !seen[1] || !seen[1000000] || !seen[1000001] {
+ t.Fatalf("spawned identities: %v", seen)
+ }
+ if len(world.characters) != 4 {
+ t.Fatal("distant NPC was removed from the world")
+ }
+ })
+ }
+}
+
+func TestHeldMovementStreamsNPCBeforeMinimapRange(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "[52, 14, 56]", "[1000, 0, 1551]"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.position = [3]float32{1000, 0, 1000}
+ client := connectZoningClient(t, world, true)
+ client.Write(targetPacket(npcMovementPacket(player, 1)))
+ ping := systemPacket(1, nil)
+ binary.BigEndian.PutUint16(ping[2:4], 11)
+ client.Write(ping)
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
+ world.mutex.Lock()
+ started := world.clients[1].movementStarted
+ world.mutex.Unlock()
+
+ done := make(chan struct{})
+ go func() { world.advanceNPCs(started.Add(time.Second)); close(done) }()
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+ world.advanceNPCs(started.Add(2 * time.Second))
+
+ if binary.BigEndian.Uint32(packet[16:]) != 0x271b3a6b || binary.BigEndian.Uint32(packet[24:]) != 1000000 {
+ t.Fatalf("entering NPC spawn: %x", packet)
+ }
+ if player.position != [3]float32{1000, 0, 1000} {
+ t.Fatal("interest prediction changed the authoritative player position")
+ }
+}
+
+func TestNPCInterestRetainsBoundaryMarginAndRespawns(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "[52, 14, 56]", "[1500, 0, 1000]"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.position = [3]float32{1000, 0, 1000}
+ client := connectZoningClient(t, world, false)
+ now := time.Now()
+
+ player.position[0] = 900
+ world.advanceNPCs(now)
+ player.position[0] = 899
+ done := make(chan struct{})
+ go func() { world.advanceNPCs(now); close(done) }()
+ removed, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+ player.position[0] = 949
+ world.advanceNPCs(now)
+ player.position[0] = 950
+ done = make(chan struct{})
+ go func() { world.advanceNPCs(now); close(done) }()
+ spawn, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+
+ if binary.BigEndian.Uint32(removed[20:]) != 0x36510078 || binary.BigEndian.Uint32(removed[28:]) != 1000000 {
+ t.Fatalf("departing NPC removal: %x", removed)
+ }
+ if binary.BigEndian.Uint32(spawn[20:]) != 0x271b3a6b || binary.BigEndian.Uint32(spawn[28:]) != 1000000 {
+ t.Fatalf("returning NPC spawn: %x", spawn)
+ }
+}
+
+func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) {
+ data := strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point")
+ useNPCData(t, strings.ReplaceAll(data, "[52, 14, 56]", "[1550.25, 0, 1000]\n - [2000, 0, 1000]"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.position = [3]float32{1000, 0, 1000}
+ client := connectZoningClient(t, world, false)
+ now := time.Now()
+ world.lastNPCUpdate = now
+ for _, npc := range world.roamingNPCs[950] {
+ npc.roaming.moving = true
+ npc.roaming.nextMove = now
+ npc.roaming.destination = npc.position
+ npc.roaming.destination[0] -= 1
+ }
+
+ done := make(chan struct{})
+ go func() { world.advanceNPCs(now.Add(250 * time.Millisecond)); close(done) }()
+ spawn, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ motion, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+ world.advanceNPCs(now.Add(500 * time.Millisecond))
+
+ if binary.BigEndian.Uint32(spawn[20:]) != 0x271b3a6b || binary.BigEndian.Uint32(spawn[28:]) != 1000000 {
+ t.Fatalf("entering NPC spawn: %x", spawn)
+ }
+ if binary.BigEndian.Uint32(motion[20:]) != 0x54111123 || binary.BigEndian.Uint32(motion[28:]) != 1000000 || binary.BigEndian.Uint32(motion[36:]) != 1 || math.Float32frombits(binary.BigEndian.Uint32(motion[40:])) != 1549.875 {
+ t.Fatalf("entering NPC motion: %x", motion)
+ }
+ if world.characters[1000001].position[0] != 1999.25 {
+ t.Fatal("unobserved NPC stopped roaming on the server")
+ }
+}
+
+func TestReloadRemovesOnlyKnownNPCsAndAddsNearbyReplacements(t *testing.T) {
+ data := strings.ReplaceAll(editedNPCData, "[52, 14, 56]", "[1000, 0, 1000]\n - [2000, 0, 1000]")
+ useNPCData(t, data)
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.position = [3]float32{1000, 0, 1000}
+ client := connectZoningClient(t, world, false)
+ data = strings.ReplaceAll(data, "[1000, 0, 1000]\n - [2000, 0, 1000]", "[2000, 0, 1000]\n - [1000, 0, 1000]")
+ if err := os.WriteFile("data/npc_spawns.yaml", []byte(data), 0644); err != nil {
+ t.Fatal(err)
+ }
+ response := httptest.NewRecorder()
+
+ done := make(chan struct{})
+ go func() {
+ world.reloadNPCData(response, httptest.NewRequest("POST", "/reload-npcs", nil))
+ close(done)
+ }()
+ removed, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ spawn, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+
+ if response.Code != http.StatusSeeOther || binary.BigEndian.Uint32(removed[20:]) != 0x36510078 || binary.BigEndian.Uint32(removed[28:]) != 1000000 {
+ t.Fatalf("known NPC removal: HTTP %d, %x", response.Code, removed)
+ }
+ if binary.BigEndian.Uint32(spawn[20:]) != 0x271b3a6b || binary.BigEndian.Uint32(spawn[28:]) != 1000003 || len(world.characters) != 3 {
+ t.Fatalf("nearby replacement: %x, population %d", spawn, len(world.characters))
+ }
+}
diff --git a/server/main.go b/server/main.go
@@ -282,18 +282,15 @@ func (server *server) serveWorldConnection(conn net.Conn) error {
}
server.clients[character.id] = client
client.id = character.id
+ client.npcs = make(map[uint32]bool)
updates := [][]byte{playfieldPacket(character), characterPacket(character)}
for id, other := range server.characters {
- if id != character.id && other.playfield == character.playfield && (server.clients[id] != nil || other.npc) {
+ if id != character.id && other.playfield == character.playfield && server.clients[id] != nil {
updates = append(updates, characterPacket(other))
- if other.roaming != nil && other.roaming.moving {
- updates = append(updates, npcMovementPacket(other, 1))
- }
- if !other.npc {
- updates = append(updates, n3Packet(0x570c2039, 50000, other.id, nil))
- }
+ updates = append(updates, n3Packet(0x570c2039, 50000, other.id, nil))
}
}
+ updates = append(updates, server.updateNPCInterest_locked(client, time.Now())...)
updates = append(updates, fullCharacterPacket(character))
updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked()))
spawn := characterPacket(character)
diff --git a/server/npcs.go b/server/npcs.go
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"os"
+ "time"
"go.yaml.in/yaml/v3"
)
@@ -93,10 +94,8 @@ func (server *server) reloadNPCData(w http.ResponseWriter, r *http.Request) {
return
}
server.mutex.Lock()
- updates := make(map[uint32][][]byte)
for id, character := range server.characters {
if character.npc {
- updates[character.playfield] = append(updates[character.playfield], n3Packet(0x36510078, 50000, id, nil))
delete(server.characters, id)
}
}
@@ -109,19 +108,18 @@ func (server *server) reloadNPCData(w http.ResponseWriter, r *http.Request) {
if spawn.roaming != nil {
server.roamingNPCs[spawn.playfield] = append(server.roamingNPCs[spawn.playfield], &spawn)
}
- updates[spawn.playfield] = append(updates[spawn.playfield], characterPacket(&spawn))
}
- clients := make(map[*worldClient]uint32)
- for id, client := range server.clients {
+ clients := make(map[*worldClient][][]byte)
+ for _, client := range server.clients {
if client.ready {
- clients[client] = server.characters[id].playfield
+ clients[client] = server.updateNPCInterest_locked(client, time.Now())
}
}
server.mutex.Unlock()
- // Remove the old instances before sending replacements to each visible zone.
- for client, playfield := range clients {
- for _, packet := range updates[playfield] {
+ // Remove known old instances before sending nearby replacements.
+ for client, packets := range clients {
+ for _, packet := range packets {
if err := client.send(packet); err != nil {
log.Printf("Reload NPC data: %v", err)
client.conn.Close()
diff --git a/server/npcs_test.go b/server/npcs_test.go
@@ -108,9 +108,16 @@ func TestPopulationsAreSharedAndZoneScoped(t *testing.T) {
t.Fatal(err)
}
}
+ // Finish initialization before the next player broadcasts its arrival.
+ ping := systemPacket(1, nil)
+ binary.BigEndian.PutUint16(ping[2:4], 11)
+ client.Write(ping)
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
}
- if len(populations[0]) != 50 || len(populations[1]) != 50 || len(populations[2]) != 58 || len(populations[3]) != 88 || len(populations[4]) != 1842 {
+ if len(populations[0]) != 50 || len(populations[1]) != 50 || len(populations[2]) != 58 || len(populations[3]) != 88 || len(populations[4]) != 10 {
t.Fatalf("population counts: %d, %d, %d, %d, %d", len(populations[0]), len(populations[1]), len(populations[2]), len(populations[3]), len(populations[4]))
}
var leet []byte
@@ -137,7 +144,7 @@ func TestPopulationsAreSharedAndZoneScoped(t *testing.T) {
}
}
-func TestEveryAuthoredPopulationIsSent(t *testing.T) {
+func TestEveryAuthoredPopulationIsPreserved(t *testing.T) {
var catalog []struct {
Playfield uint32
Count int
@@ -150,23 +157,13 @@ func TestEveryAuthoredPopulationIsSent(t *testing.T) {
var guard, highLevel []byte
for _, playfield := range catalog {
- player := world.newCharacter()
- player.playfield = playfield.Playfield
- client, connection := net.Pipe()
- client.SetDeadline(time.Now().Add(5 * time.Second))
- go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
- cookie := make([]byte, 12)
- binary.BigEndian.PutUint32(cookie, player.id)
- client.Write(systemPacket(0x1b, cookie))
count := 0
- for _, packet := range readWorldUpdates(t, client) {
- if binary.BigEndian.Uint32(packet[20:24]) != 0x271b3a6b || binary.BigEndian.Uint32(packet[37:41])&1 == 0 {
+ for _, npc := range world.characters {
+ if !npc.npc || npc.playfield != playfield.Playfield {
continue
}
count++
- if binary.BigEndian.Uint32(packet[41:45]) != playfield.Playfield || binary.BigEndian.Uint32(packet[12:16]) != player.id {
- t.Fatalf("incorrect NPC zone or recipient: %x", packet)
- }
+ packet := characterPacket(npc)
name := string(packet[70 : 69+int(packet[69])])
if playfield.Playfield == 950 && name == "Placeholder OTBG" {
guard = packet
@@ -175,7 +172,6 @@ func TestEveryAuthoredPopulationIsSent(t *testing.T) {
highLevel = packet
}
}
- client.Close()
if count != playfield.Count {
t.Fatalf("playfield %d: got %d NPCs, disc requests %d", playfield.Playfield, count, playfield.Count)
}
diff --git a/server/roaming.go b/server/roaming.go
@@ -35,17 +35,17 @@ func (server *server) advanceNPCs(now time.Time) {
return
}
- clients := make(map[*worldClient]uint32)
+ clients := make(map[*worldClient][][]byte)
zones := make(map[uint32]bool)
for id, client := range server.clients {
if client.ready {
- clients[client] = server.characters[id].playfield
+ clients[client] = nil
zones[server.characters[id].playfield] = true
}
}
// Only visit roaming creatures in zones with ready observers.
- updates := make(map[uint32][][]byte)
+ updates := make(map[uint32][]byte)
for zone := range zones {
for _, character := range server.roamingNPCs[zone] {
if character.roaming.nextMove.IsZero() {
@@ -73,7 +73,7 @@ func (server *server) advanceNPCs(now time.Time) {
angle := math.Atan2(x, z)
character.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))}
if started {
- updates[character.playfield] = append(updates[character.playfield], npcMovementPacket(character, 1))
+ updates[character.id] = npcMovementPacket(character, 1)
continue
}
@@ -108,15 +108,27 @@ func (server *server) advanceNPCs(now time.Time) {
}
character.position = position
if action != 0 {
- updates[character.playfield] = append(updates[character.playfield], npcMovementPacket(character, action))
+ updates[character.id] = npcMovementPacket(character, action)
}
}
}
+
+ // Only known NPCs receive motion; new arrivals get a spawn and current motion.
+ for client := range clients {
+ for id := range client.npcs {
+ if packet := updates[id]; packet != nil {
+ clients[client] = append(clients[client], packet)
+ }
+ }
+ if !client.loading {
+ clients[client] = append(clients[client], server.updateNPCInterest_locked(client, now)...)
+ }
+ }
server.mutex.Unlock()
- // Every observer receives the same entity position, orientation and movement control.
- for client, zone := range clients {
- for _, packet := range updates[zone] {
+ // Nearby observers receive the same entity position, orientation and movement control.
+ for client, packets := range clients {
+ for _, packet := range packets {
if err := client.send(packet); err != nil {
log.Printf("NPC roaming: %v", err)
client.conn.Close()
diff --git a/server/state.go b/server/state.go
@@ -34,6 +34,7 @@ type worldClient struct {
target bool
forward float32
movementStarted time.Time
+ npcs map[uint32]bool
}
func (client *worldClient) send(packet []byte) error {