aorecomp

Anarchy Online classic in the browser

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


commit 5d1c0d028c66d1595b30380a95b49fcf36f74a13
parent bf4d3000bc3fd03793cfe041dbaa52d757b3ca80
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 01:34:18 +0000

Implement Leet pursuit and return with native NPC routes

Diffstat:
MTODO.md | 8++++++--
Adocs/npc-pursuit.md | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 30+++++++++++++++++++++---------
Mserver/interest.go | 2+-
Mserver/interest_test.go | 2+-
Aserver/npc_pursuit.go | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/npc_pursuit_test.go | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/roaming.go | 42++++++++++++++++++------------------------
Mserver/roaming_test.go | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
9 files changed, 546 insertions(+), 47 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -144,9 +144,9 @@ its boundary checks and original-server evidence limits are recorded in checked resources and combat values rather than an assumed scaling formula. - [ ] Add a second species with different behavior or equipment. Check: changing one species' profile does not change the other species. -- [ ] Pursue a target across open ground. Check: an engaged creature follows a +- [x] Pursue a target across open ground. Check: an engaged creature follows a moving player and resumes attacks only when in range. -- [ ] Return a creature home after pursuit ends. Check: it disengages, returns +- [x] Return a creature home after pursuit ends. Check: it disengages, returns to its home area and can participate in a new encounter. - [ ] Give one hostile creature proximity aggression. Check: an eligible nearby player is attacked while an ineligible or out-of-range player is not. @@ -161,6 +161,10 @@ The supported Leet uses the recovered native NPC health branch, with one retained recovery clock across combat transitions and quiet observer corrections. Its evidence, automated/native checks and original-server policy limits are in [NPC health recovery](docs/npc-regeneration.md). NPC nano recovery remains open. +The mobile level-1 Leet now pursues a moving target and returns after concrete +target loss. Native waypoint routes also drive idle walking. Evidence, checks +and the provisional speed/return policy are in [Leet pursuit](docs/npc-pursuit.md). +Historical outdoor give-up timing and obstacle navigation remain open. ## Death and recovery diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md @@ -0,0 +1,132 @@ +# Leet pursuit and return + +The mobile level-1 Leet profile (MonsterData 17655) pursues its current player +target across open ground. Losing melee range no longer discards its attack +deadline. It can deliver a bite only inside the recovered weapon range, while +continuing its approach until the target is within two metres. + +A dead, disconnected, loading or different-playfield target ends pursuit. The +living Leet runs back to its retained spawn position, then resumes idle roaming. +Returning neither refills health nor resets the recovery clock. Another player +can engage it during the return; that hit replaces the return route with the +normal combat flow. Dead remains never return or continue following. + +## Evidence and policy limits + +The shipped 14.9.1 help file +`cd_image/text/help/How do I play this Game Alone.txt`, paragraph at line 23, +describes pulling monsters to a mission entrance and says outdoor monsters give +up sooner without continued attacks. This establishes pursuit and a qualitative +outdoor disengagement distinction. It supplies no speed, leash distance, +timeout or return-home formula. The local wiki and bounded period-source search +did not recover those numeric rules for Leets. + +The server therefore handles concrete target loss without claiming a historical +outdoor give-up timer. Distance/time leashing remains unimplemented. Straight +routes use the native default RunSpeed 100 and run mode, represented on the +server as 4.5 metres/second. Selecting that default for Leet pursuit and return +is provisional; it is not an original-server Leet speed measurement. The +close-approach threshold comes from native NPC steering `FUN_10048430`, whose +near-target branch checks squared distance below 4 and line of sight. The +server currently assumes open ground; it has no obstruction or navigation +mesh check. Its existing terrain-height interpolation preserves the authored +spawn offset, and each scheduler step remains capped at 0.25 seconds. + +Return to the retained spawn is an explicit reconstruction policy. A bounded +source search found no period Leet rule proving that exact destination or its +timing. Return continues without observers. Health uses the separate +[recovery rule](npc-regeneration.md), including while returning. Fixed posts, +unprofiled creatures, other species and other levels acquire neither pursuit +nor return. Proximity aggression, threat-based target changes, obstruction +rejection and obstacle navigation remain separate TODOs. + +## Native route contract + +Original 14.9.1 `kkr.dll` SHA-256: +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +`FollowTargetIIR_c` uses key `0x260f3671`. Reader `FUN_1007e540` consumes: + +| Field | Wire representation | +| --- | --- | +| Follow target | Two uint32 identity components | +| Auxiliary value | One float; its meaning remains unresolved; sent as zero | +| Movement control | One byte | +| Reconcile position | Three floats | +| Waypoint count | One signed int32 | +| Waypoints | Three floats each; native storage has 30 entries | + +`FUN_1007e690` resolves both actors, applies a nonzero reconcile position, +forwards the movement control, clears the NPC's old PathGuide, and calls +`FUN_10048260` with the target and waypoint array. The NPC steering caller +`FUN_1004af50` uses `FUN_10048430(0)` and `SteeringDirArrive`; this is a client +waypoint consumer, not evidence of original server route planning. + +The server sends self as the route's target identity, current position, and +two points: current position and destination. Pursuit and return use run +control 23; ordinary idle roaming uses walk control 22. The native setter +skips the starting point when a second point is present. A changed player +position refreshes the route; an unchanged destination does not produce +repeated absolute position resets. New observers get the current spawn and +combat profile before the current route and combat replay. + +Stopping sends an empty target and zero waypoints, followed by walk control 22. +Idle roaming also needs an explicit waypoint route: the native NPC steering +does not walk merely because a CharDCMove forward command was received. +Restoring walk mode keeps idle roaming at its existing speed. A newly engaged +NPC clears any return route before starting its new attack. StopFight remains +ordered before route cancellation and later quiet health corrections. + +REA records and procedure text are retained under +`local/npc-pursuit-research/`. The reader/activation record is +`follow1491Handlers.json`; the steering record is `followSteering.json`. +The source ledger is `server-policy-sources.json`. + +The reader/activation evidence ID is +`ev_8bcc339823b969bc5b5e36d6a434f625a11eee1b065ef8dcc4dfa51a8fc5cea5`; +NPC steering is +`ev_437e76236c9b5d2a0d7dd122ca12b1ff620178cda1d2209666b42e29d1f39ab9`; +its NPC/player callers are +`ev_1e75e2365d7f68786685da35877287cd6dc6aba5c507b06902338a1067098cc1`. + +## Verification + +An isolated native route experiment sent walk and run waypoint routes to two +published WASM clients. Both moved the Leet and reached the short route's +native arrival threshold, less than one metre from its endpoint. Clearing the +route removed the native follow pointer. No browser errors were recorded. +A longer route ended early near scene geometry; it does not establish general +navigation or collision fidelity. Captures are in `local/npc-pursuit-smoke/`. +The initial probe's field named `velocity` was not a verified velocity vector; +that labeling error is recorded in +`local/npc-pursuit-research/probe-field-correction.json`. Movement +observations use position and time, not those unidentified fields. + +Focused Go tests cover attack range and retained deadlines, a moving target, +identical route packets for two observers, return after target loss, continued +return without observers, a new encounter during return, corpse exclusion, +new-observer ordering and unchanged behavior for unverified profiles. + +The full `go test ./server/...` suite passed (120.670 seconds). Movement and +NPC recovery tests also passed five runs under the race detector (120.199 +seconds). Roaming socket fixtures finish native loading before expecting +routes and check the empty-route/walk-mode stop sequence. + +Two published WASM clients were then tested on the same normal development +server used for laptop previews, over HTTPS port 8443. The browser reported a +secure context, cross-origin isolation and SharedArrayBuffer availability. +Four 50-sample captures show idle walking, pursuit, return after a playfield +change, and resumed idle walking. The chase displaced the Leet about 15.7 +metres and ended with its route cleared near the player. The observer saw it +run back to the exact authored home position, then walk between idle points +with walk mode and an active native waypoint controller. Health stayed below +maximum throughout the return. The second character subsequently engaged the +same Leet in a new fight and defeated it. The client displayed stationary, +lootable remains and returned its weapon controller to idle. + +These normal-server captures, screenshots and assertion results are under +`local/development-smoke/`, including `verification.json`. Earlier isolated +captures under `local/npc-pursuit-smoke/` also retain explicit server state +during pursuit and return. Browser navigation alone was not used as proof of +disconnect: resumable sessions can outlive a page. Disconnect, loading and +target-death cases are covered by the Go tests; the controlled manual return +uses a real playfield change. diff --git a/server/combat.go b/server/combat.go @@ -214,6 +214,10 @@ func (server *server) startAttack_locked(attacker, target *character, now time.T if attacker.fighting == target.id { return } + if attacker.roaming != nil { + server.stopNPCMotion_locked(attacker, updates) + attacker.roaming.returning = false + } // AttackIIR exits the native sitting controller state before attacking. attacker.sitting = false attacker.fighting = target.id @@ -227,10 +231,6 @@ func (server *server) startAttack_locked(attacker, target *character, now time.T attack, _ := attacker.attackDelays() attacker.nextAttack = attacker.nextAttack.Add(attack) server.fighting[attacker.id] = attacker - if attacker.roaming != nil && attacker.roaming.moving { - attacker.roaming.moving = false - server.queueCombat_locked(updates, attacker, attacker, npcMovementPacket(attacker, 2)) - } server.queueCombat_locked(updates, attacker, target, attackPacket(attacker.id, target.id)) } @@ -243,6 +243,10 @@ func (server *server) stopAttack_locked(attacker *character, updates map[*worldC attacker.nextAttack = time.Time{} delete(server.fighting, attacker.id) server.queueCombat_locked(updates, attacker, attacker, stopFightPacket(attacker.id)) + if attacker.roaming != nil && attacker.combatProfile != nil && attacker.monsterData == 17655 && attacker.level == 1 { + server.stopNPCMotion_locked(attacker, updates) + attacker.roaming.returning = attacker.health != 0 && attacker.position != attacker.roaming.home + } } func (server *server) cancelCombat_locked(id uint32, updates map[*worldClient][][]byte) { @@ -287,10 +291,17 @@ func (server *server) advanceCombat(now time.Time) { available = available && client != nil && client.ready && !client.loading } } - if !available || !server.combatInRange_locked(attacker, target, now) { + if !available { server.stopAttack_locked(attacker, updates) continue } + if !server.combatInRange_locked(attacker, target, now) { + // The supported mobile Leet retains its attack clock while pursuing. + if attacker.roaming == nil || attacker.combatProfile == nil || attacker.monsterData != 17655 || attacker.level != 1 { + server.stopAttack_locked(attacker, updates) + } + continue + } if now.Before(attacker.nextAttack) { continue } @@ -327,10 +338,6 @@ func (server *server) finishDamage_locked(attacker, target *character, damage ui } } if target.health == 0 { - if target.roaming != nil && target.roaming.moving { - target.roaming.moving = false - server.queueCombat_locked(updates, target, target, npcMovementPacket(target, 2)) - } if !target.npc { client := server.clients[target.id] target.position = predictedPosition_locked(target, client, now) @@ -339,6 +346,11 @@ func (server *server) finishDamage_locked(attacker, target *character, damage ui client.backpacks = nil } server.cancelCombat_locked(target.id, updates) + if target.roaming != nil { + // A returning creature can die without an entry in the combat map. + server.stopNPCMotion_locked(target, updates) + target.roaming.returning = false + } server.queueCombat_locked(updates, target, target, deathPacket(target)) monster := gamedata.MonsterTemplates[target.monsterData] if target.npc && monster != nil && len(monster.DeathAnimations) != 0 { diff --git a/server/interest.go b/server/interest.go @@ -51,7 +51,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim } } if other.roaming != nil && other.roaming.moving { - updates = append(updates, npcMovementPacket(other, 1)) + updates = append(updates, npcRoutePacket(other)) } } if client.ready && len(spawned) != 0 { diff --git a/server/interest_test.go b/server/interest_test.go @@ -162,7 +162,7 @@ func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) { 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 { + if binary.BigEndian.Uint32(motion[20:]) != 0x260f3671 || binary.BigEndian.Uint32(motion[28:]) != 1000000 || motion[48] != 22 || math.Float32frombits(binary.BigEndian.Uint32(motion[49:])) != 1549.875 { t.Fatalf("entering NPC motion: %x", motion) } if world.characters[1000001].position[0] != 1999.25 { diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go @@ -0,0 +1,116 @@ +package main + +import ( + "encoding/binary" + "math" + "math/rand/v2" + "time" +) + +func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, seconds float64, updates map[*worldClient][][]byte) bool { + // Other species and levels retain their existing combat and roaming policy. + if npc.combatProfile == nil || npc.monsterData != 17655 || npc.level != 1 || npc.fighting == 0 && !npc.roaming.returning { + return false + } + destination := npc.roaming.home + if npc.fighting != 0 { + target := server.characters[npc.fighting] + client := server.clients[npc.fighting] + if target == nil || target.health == 0 || target.playfield != npc.playfield || client == nil || !client.ready || client.loading { + server.stopAttack_locked(npc, updates) + } else { + destination = predictedPosition_locked(target, client, now) + // Open-ground arrival threshold from NPC steering FUN_10048430. + x, y, z := destination[0]-npc.position[0], destination[1]-npc.position[1], destination[2]-npc.position[2] + if x*x+y*y+z*z < 4 { + server.stopNPCMotion_locked(npc, updates) + return true + } + } + } + + // Retain the native default RunSpeed 100: mode 3 advances at 4.5 m/s. + // Its use as the Leet's chase/return speed remains a reconstruction choice. + x, z := float64(destination[0]-npc.position[0]), float64(destination[2]-npc.position[2]) + distance := math.Hypot(x, z) + step := 4.5 * seconds + position := npc.position + if distance <= step { + position[0], position[2] = destination[0], destination[2] + } else { + position[0] += float32(x / distance * step) + position[2] += float32(z / distance * step) + } + + // Match roaming's terrain-height policy without inventing wall navigation. + if ground := server.terrain[npc.playfield]; ground != nil { + home, available := ground.elevation(npc.roaming.home[0], npc.roaming.home[2]) + if available { + height, inside := ground.elevation(position[0], position[2]) + if !inside { + server.stopNPCMotion_locked(npc, updates) + return true + } + position[1] = npc.roaming.home[1] + height - home + } + } + npc.position = position + if distance != 0 { + angle := math.Atan2(x, z) + npc.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))} + } + + // Complete the return before allowing another idle roaming destination. + if npc.fighting == 0 && distance <= step { + server.stopNPCMotion_locked(npc, updates) + npc.roaming.returning = false + npc.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) + return true + } + changed := !npc.roaming.moving || npc.roaming.destination != destination + npc.roaming.destination = destination + npc.roaming.moving = true + npc.running = true + if changed { + server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc)) + } + return true +} + +func (server *server) stopNPCMotion_locked(npc *character, updates map[*worldClient][][]byte) { + if !npc.roaming.moving { + return + } + npc.roaming.moving = false + npc.running = false + // Clear the waypoint controller, then restore walking for idle roaming. + server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc), npcMovementPacket(npc, 22)) +} + +func npcRoutePacket(npc *character) []byte { + // 14.9.1 kkr.dll FUN_1007e540 / FUN_1007e690, including the waypoint count. + targetType, targetID, control, count := uint32(0), uint32(0), byte(19), uint32(0) + if npc.roaming.moving { + targetType, targetID, control, count = 50000, npc.id, 22, 2 + if npc.running { + control = 23 + } + } + var body []byte + for _, value := range []uint32{targetType, targetID, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + body = append(body, control) + for _, value := range npc.position { + body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) + } + body = binary.BigEndian.AppendUint32(body, count) + if npc.roaming.moving { + for _, position := range [][3]float32{npc.position, npc.roaming.destination} { + for _, value := range position { + body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) + } + } + } + return n3Packet(0x260f3671, 50000, npc.id, body) +} diff --git a/server/npc_pursuit_test.go b/server/npc_pursuit_test.go @@ -0,0 +1,192 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "math" + "testing" + "time" +) + +func newNPCPursuitWorld() (*server, *combatTestConn, time.Time) { + world, conn := newCombatWorld() + start := time.Now() + world.characters[1].position = [3]float32{21, 0, 0} + npc := world.characters[1000000] + npc.monsterData, npc.level = 17655, 1 + npc.combatProfile = gamedata.NPCCombatProfiles[17655][1] + npc.roaming = &npcRoaming{home: npc.position} + npc.fighting = 1 + npc.nextAttack = start.Add(1750 * time.Millisecond) + world.fighting[npc.id] = npc + world.roamingNPCs = map[uint32][]*character{950: {npc}} + world.lastNPCUpdate = start + return world, conn, start +} + +func TestNPCPursuitRetainsAttackDeadlineAndOnlyHitsInsideRange(t *testing.T) { + world, _, start := newNPCPursuitWorld() + deadline := world.characters[1000000].nextAttack + + for tick := 1; tick <= 8; tick++ { + now := start.Add(time.Duration(tick) * 250 * time.Millisecond) + world.advanceNPCs(now) + world.advanceCombat(now) + } + if world.characters[1].health != 100 || world.characters[1000000].nextAttack != deadline || world.characters[1000000].fighting != 1 || world.characters[1000000].position != [3]float32{10, 0, 0} { + t.Fatal("pursuit hit from outside range or reset the attack deadline") + } + world.advanceNPCs(start.Add(2250 * time.Millisecond)) + world.advanceCombat(start.Add(2250 * time.Millisecond)) + for tick := 10; tick <= 18; tick++ { + world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond)) + } + + if world.characters[1].health < 92 || world.characters[1].health > 96 || world.characters[1000000].position != [3]float32{20.125, 0, 0} || world.characters[1000000].roaming.moving || world.characters[1000000].running || world.characters[1000000].fighting != 1 || world.characters[1000000].nextAttack != start.Add(5750*time.Millisecond) { + t.Fatalf("arrival did not resume normal combat: player=%+v npc=%+v", world.characters[1], world.characters[1000000]) + } +} + +func TestNPCPursuitPublishesNativeWaypointRouteToBothObservers(t *testing.T) { + world, first, start := newNPCPursuitWorld() + second := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950} + world.clients[2] = &worldClient{id: 2, conn: second, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + + world.advanceNPCs(start.Add(250 * time.Millisecond)) + + if len(first.packets) != 1 || len(second.packets) != 1 || !bytes.Equal(first.packets[0][16:], second.packets[0][16:]) || binary.BigEndian.Uint32(first.packets[0][16:20]) != 0x260f3671 || binary.BigEndian.Uint32(first.packets[0][24:28]) != 1000000 || binary.BigEndian.Uint16(first.packets[0][6:8]) != 82 || !bytes.Equal(first.packets[0][29:42], []byte{0, 0, 0xc3, 0x50, 0, 0x0f, 0x42, 0x40, 0, 0, 0, 0, 23}) || binary.BigEndian.Uint32(first.packets[0][54:58]) != 2 || math.Float32frombits(binary.BigEndian.Uint32(first.packets[0][42:46])) != 2.125 || math.Float32frombits(binary.BigEndian.Uint32(first.packets[0][70:74])) != 21 { + t.Fatalf("native route or recipients: %x %x", first.packets, second.packets) + } +} + +func TestNPCPursuitChangesDirectionForMovingTargetWithoutRestartingAttack(t *testing.T) { + world, conn, start := newNPCPursuitWorld() + deadline := world.characters[1000000].nextAttack + world.advanceNPCs(start.Add(250 * time.Millisecond)) + world.characters[1].position = [3]float32{2.125, 0, 20} + + world.advanceNPCs(start.Add(500 * time.Millisecond)) + + if world.characters[1000000].position != [3]float32{2.125, 0, 1.125} || world.characters[1000000].nextAttack != deadline || len(conn.packets) != 2 || world.characters[1000000].roaming.destination != [3]float32{2.125, 0, 20} { + t.Fatalf("target direction was not refreshed: %+v packets=%x", world.characters[1000000], conn.packets) + } +} + +func TestNPCPursuitReturnsHomeAfterTargetLossWithoutHealingOrTeleporting(t *testing.T) { + for _, scenario := range []string{"disconnect", "loading", "death", "zone"} { + t.Run(scenario, func(t *testing.T) { + world, conn, start := newNPCPursuitWorld() + world.advanceNPCs(start.Add(250 * time.Millisecond)) + world.advanceNPCs(start.Add(500 * time.Millisecond)) + world.characters[1000000].health = 50 + switch scenario { + case "disconnect": + delete(world.clients, 1) + case "loading": + world.clients[1].loading = true + case "death": + world.characters[1].health = 0 + case "zone": + world.characters[1].playfield = 705 + } + conn.packets = nil + + world.advanceNPCs(start.Add(750 * time.Millisecond)) + if world.characters[1000000].position != [3]float32{2.125, 0, 0} || !world.characters[1000000].roaming.returning || world.characters[1000000].fighting != 0 || world.characters[1000000].health != 50 { + t.Fatal("target loss teleported, healed, or retained the old fight") + } + world.advanceNPCs(start.Add(time.Second)) + world.advanceRegeneration(start.Add(time.Second)) + + if world.characters[1000000].position != [3]float32{1, 0, 0} || world.characters[1000000].roaming.returning || world.characters[1000000].roaming.moving || world.characters[1000000].running || world.characters[1000000].health != 50 || len(world.fighting) != 0 || !world.characters[1000000].roaming.nextMove.After(start.Add(time.Second)) { + t.Fatalf("return did not finish cleanly: %+v", world.characters[1000000]) + } + }) + } +} + +func TestNPCPursuitCanBeEngagedAgainDuringReturn(t *testing.T) { + world, conn, start := newNPCPursuitWorld() + world.advanceNPCs(start.Add(250 * time.Millisecond)) + world.advanceNPCs(start.Add(500 * time.Millisecond)) + world.clients[1].loading = true + world.advanceNPCs(start.Add(750 * time.Millisecond)) + world.clients[1].loading = false + world.characters[1].position = [3]float32{3, 0, 0} + conn.packets = nil + + err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + hit := world.characters[1].nextAttack + world.advanceCombat(hit) + + if err != nil || world.characters[1000000].roaming.returning || world.characters[1000000].roaming.moving || world.characters[1000000].fighting != 1 || world.characters[1000000].health == 100 || len(world.fighting) != 2 { + t.Fatalf("new encounter retained a return route: %+v err=%v", world.characters[1000000], err) + } +} + +func TestNPCPursuitDeathClearsRouteAndNeverReturnsCorpse(t *testing.T) { + for _, scenario := range []string{"pursuing", "returning"} { + t.Run(scenario, func(t *testing.T) { + world, conn, start := newNPCPursuitWorld() + world.advanceNPCs(start.Add(250 * time.Millisecond)) + world.advanceNPCs(start.Add(500 * time.Millisecond)) + if scenario == "returning" { + world.clients[1].loading = true + world.advanceNPCs(start.Add(750 * time.Millisecond)) + world.clients[1].loading = false + } + world.characters[1000000].health = 1 + world.characters[1].position = [3]float32{3, 0, 0} + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + hit := world.characters[1].nextAttack + + world.advanceCombat(hit) + position := world.characters[1000000].position + conn.packets = nil + world.advanceNPCs(hit.Add(time.Second)) + + if world.characters[1000000].health != 0 || world.characters[1000000].position != position || world.characters[1000000].roaming.returning || world.characters[1000000].roaming.moving || len(conn.packets) != 0 { + t.Fatalf("dead creature moved or retained pursuit: %+v packets=%x", world.characters[1000000], conn.packets) + } + }) + } +} + +func TestNPCPursuitJoiningObserverGetsSpawnBeforeRouteAndAttack(t *testing.T) { + world, _, start := newNPCPursuitWorld() + world.advanceNPCs(start.Add(250 * time.Millisecond)) + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} + + world.advanceNPCs(start.Add(500 * time.Millisecond)) + + if len(observer.packets) != 4 || binary.BigEndian.Uint32(observer.packets[0][16:20]) != 0x271b3a6b || binary.BigEndian.Uint32(observer.packets[1][16:20]) != 0x1d3c0f1c || binary.BigEndian.Uint32(observer.packets[2][16:20]) != 0x260f3671 || binary.BigEndian.Uint32(observer.packets[3][16:20]) != 0x28494070 || math.Float32frombits(binary.BigEndian.Uint32(observer.packets[2][42:46])) != 3.25 { + t.Fatalf("join order or current route: %x", observer.packets) + } +} + +func TestNPCPursuitDoesNotChangeOtherSpeciesOrLevels(t *testing.T) { + for _, scenario := range []string{"species", "level", "profile"} { + t.Run(scenario, func(t *testing.T) { + world, _, start := newNPCPursuitWorld() + switch scenario { + case "species": + world.characters[1000000].monsterData = 17657 + case "level": + world.characters[1000000].level = 2 + case "profile": + world.characters[1000000].combatProfile = nil + } + + world.advanceNPCs(start.Add(250 * time.Millisecond)) + world.advanceCombat(start.Add(250 * time.Millisecond)) + + if world.characters[1000000].position != [3]float32{1, 0, 0} || world.characters[1000000].fighting != 0 || world.characters[1000000].roaming.moving { + t.Fatalf("unverified profile acquired pursuit: %+v", world.characters[1000000]) + } + }) + } +} diff --git a/server/roaming.go b/server/roaming.go @@ -13,6 +13,7 @@ type npcRoaming struct { destination [3]float32 nextMove time.Time moving bool + returning bool } func (server *server) roamNPCs() { @@ -37,10 +38,6 @@ func (server *server) advanceNPCs(now time.Time) { server.mutex.Lock() seconds := math.Min(now.Sub(server.lastNPCUpdate).Seconds(), 0.25) server.lastNPCUpdate = now - if len(server.clients) == 0 { - server.mutex.Unlock() - return - } clients := make(map[*worldClient][][]byte) zones := make(map[uint32]bool) @@ -51,11 +48,16 @@ func (server *server) advanceNPCs(now time.Time) { } } - // Only visit roaming creatures in zones with ready observers. - updates := make(map[uint32][]byte) - for zone := range zones { - for _, character := range server.roamingNPCs[zone] { - if character.fighting != 0 || character.health == 0 { + // Idle roaming needs observers; active pursuit and returning home do not. + for zone, characters := range server.roamingNPCs { + for _, character := range characters { + if character.health == 0 || !zones[zone] && character.fighting == 0 && !character.roaming.returning { + continue + } + if server.advanceNPCPursuit_locked(character, now, seconds, clients) { + continue + } + if !zones[zone] || character.fighting != 0 { continue } if character.roaming.nextMove.IsZero() { @@ -83,19 +85,17 @@ 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.id] = npcMovementPacket(character, 1) + character.running = false + server.queueCombat_locked(clients, character, character, npcRoutePacket(character)) continue } // The original vehicle walks at 1.5 metres per second between commands. step := 1.5 * seconds - action := uint32(0) + arrived := distance <= step position := character.position if distance <= step { position = character.roaming.destination - character.roaming.moving = false - character.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) - action = 2 } else { position[0] += float32(x / distance * step) position[2] += float32(z / distance * step) @@ -110,26 +110,20 @@ func (server *server) advanceNPCs(now time.Time) { position[1] = character.roaming.home[1] + height - home } else { position = character.position - character.roaming.moving = false - character.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) - action = 2 + arrived = true } } } character.position = position - if action != 0 { - updates[character.id] = npcMovementPacket(character, action) + if arrived { + server.stopNPCMotion_locked(character, clients) + character.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) } } } // 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)...) } diff --git a/server/roaming_test.go b/server/roaming_test.go @@ -39,6 +39,17 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) { if player.id == 2 { readPacket(clients[0]) } + // Drain the ready broadcast to the first observer as well. + var peer sync.WaitGroup + if player.id == 2 { + peer.Add(1) + go func() { defer peer.Done(); readPacket(clients[0]) }() + } + client.Write(n3Packet(0x570c2039, 50000, player.id, nil)) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } + peer.Wait() // Finish connection initialization before expecting peer broadcasts. ping := systemPacket(1, nil) binary.BigEndian.PutUint16(ping[2:4], 11) @@ -71,15 +82,15 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) { <-done first, second := packets[0], packets[1] - if binary.BigEndian.Uint32(first[20:24]) != 0x54111123 || binary.BigEndian.Uint32(first[28:32]) != 1000000 { + if binary.BigEndian.Uint32(first[20:24]) != 0x260f3671 || binary.BigEndian.Uint32(first[28:32]) != 1000000 { t.Fatalf("creature movement: %x", first) } if !bytes.Equal(first[20:], second[20:]) || binary.BigEndian.Uint32(first[12:16]) != 1 || binary.BigEndian.Uint32(second[12:16]) != 2 { t.Fatal("players received different NPC motion") } - x := math.Float32frombits(binary.BigEndian.Uint32(first[40:44])) - 52 - z := math.Float32frombits(binary.BigEndian.Uint32(first[48:52])) - 56 - if x != 0 || z != 0 || binary.BigEndian.Uint32(first[36:40]) != 1 { + x := math.Float32frombits(binary.BigEndian.Uint32(first[49:53])) - 52 + z := math.Float32frombits(binary.BigEndian.Uint32(first[57:61])) - 56 + if x != 0 || z != 0 || first[48] != 22 || binary.BigEndian.Uint32(first[61:65]) != 2 { t.Fatalf("walk did not start at the current position: %x", first) } if world.characters[1000001].position != [3]float32{54, 14, 56} || world.characters[1000002].position != [3]float32{100, 14, 100} { @@ -104,6 +115,11 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) { binary.BigEndian.PutUint32(cookie, player.id) client.Write(systemPacket(0x1b, cookie)) readWorldUpdates(t, client) + // Finish native loading before expecting movement broadcasts. + client.Write(n3Packet(0x570c2039, 50000, player.id, nil)) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } // A reply after initialization also synchronizes the live fixture state. ping := systemPacket(1, nil) binary.BigEndian.PutUint16(ping[2:4], 11) @@ -139,7 +155,7 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) { client.Write(ping) <-done - if len(packets) != 1 || binary.BigEndian.Uint32(packets[0][36:40]) != 2 { + if len(packets) != 2 || binary.BigEndian.Uint32(packets[0][20:24]) != 0x260f3671 || binary.BigEndian.Uint32(packets[0][61:65]) != 0 || binary.BigEndian.Uint32(packets[1][36:40]) != 22 { t.Fatalf("received position resets during the walk: %x", packets) } if world.characters[1000000].position != [3]float32{53.5, 14, 56} { @@ -153,6 +169,7 @@ func TestJoiningPlayerReceivesOngoingNPCMovement(t *testing.T) { useNPCData(t, data) world := newTestServer(t) world.characters[1000000].position = [3]float32{53, 14, 56} + world.characters[1000000].roaming.destination = [3]float32{54.5, 14, 56} world.characters[1000000].roaming.moving = true player := world.newCharacter() client, connection := net.Pipe() @@ -164,14 +181,19 @@ func TestJoiningPlayerReceivesOngoingNPCMovement(t *testing.T) { client.Write(systemPacket(0x1b, cookie)) packets := readWorldUpdates(t, client) + // Finish native loading before expecting movement broadcasts. + client.Write(n3Packet(0x570c2039, 50000, player.id, nil)) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } var movement []byte for _, packet := range packets { - if binary.BigEndian.Uint32(packet[20:24]) == 0x54111123 && binary.BigEndian.Uint32(packet[28:32]) == 1000000 { + if binary.BigEndian.Uint32(packet[20:24]) == 0x260f3671 && binary.BigEndian.Uint32(packet[28:32]) == 1000000 { movement = packet } } - if movement == nil || binary.BigEndian.Uint32(movement[36:40]) != 1 || math.Float32frombits(binary.BigEndian.Uint32(movement[40:44])) != 53 { + if movement == nil || movement[48] != 22 || math.Float32frombits(binary.BigEndian.Uint32(movement[49:53])) != 53 || math.Float32frombits(binary.BigEndian.Uint32(movement[77:81])) != 54.5 { t.Fatalf("joining player did not receive ongoing movement: %x", movement) } } @@ -190,6 +212,11 @@ func TestRoamingStopsAndPausesAtDestination(t *testing.T) { binary.BigEndian.PutUint32(cookie, player.id) client.Write(systemPacket(0x1b, cookie)) readWorldUpdates(t, client) + // Finish native loading before expecting movement broadcasts. + client.Write(n3Packet(0x570c2039, 50000, player.id, nil)) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } now := time.Now() world.characters[1000000].roaming.destination = [3]float32{52.125, 14, 56} world.characters[1000000].roaming.moving = true @@ -201,10 +228,14 @@ func TestRoamingStopsAndPausesAtDestination(t *testing.T) { if err != nil { t.Fatal(err) } + walk, err := readPacket(client) + if err != nil { + t.Fatal(err) + } <-done world.advanceNPCs(now.Add(250 * time.Millisecond)) - if binary.BigEndian.Uint32(packet[36:40]) != 2 || world.characters[1000000].position != [3]float32{52.125, 14, 56} || world.characters[1000000].roaming.moving { + if binary.BigEndian.Uint32(packet[20:24]) != 0x260f3671 || binary.BigEndian.Uint32(packet[61:65]) != 0 || binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position != [3]float32{52.125, 14, 56} || world.characters[1000000].roaming.moving { t.Fatal("NPC did not stop at its destination") } if world.characters[1000000].roaming.nextMove.Before(now.Add(3 * time.Second)) { @@ -254,6 +285,11 @@ func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) { binary.BigEndian.PutUint32(cookie, player.id) client.Write(systemPacket(0x1b, cookie)) readWorldUpdates(t, client) + // Finish native loading before expecting movement broadcasts. + client.Write(n3Packet(0x570c2039, 50000, player.id, nil)) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } now := time.Now() world.characters[1000000].roaming.destination = [3]float32{52.25, 14, 56} world.characters[1000000].roaming.moving = true @@ -265,9 +301,13 @@ func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) { if err != nil { t.Fatal(err) } + walk, err := readPacket(client) + if err != nil { + t.Fatal(err) + } <-done - if world.characters[1000000].position != [3]float32{52.25, 14.125, 56} || math.Float32frombits(binary.BigEndian.Uint32(packet[44:48])) != 14.125 { + if binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position != [3]float32{52.25, 14.125, 56} || math.Float32frombits(binary.BigEndian.Uint32(packet[53:57])) != 14.125 { t.Fatalf("NPC did not follow the slope: %v", world.characters[1000000].position) } } @@ -287,6 +327,11 @@ func TestRoamingStopsAtTerrainBoundary(t *testing.T) { binary.BigEndian.PutUint32(cookie, player.id) client.Write(systemPacket(0x1b, cookie)) readWorldUpdates(t, client) + // Finish native loading before expecting movement broadcasts. + client.Write(n3Packet(0x570c2039, 50000, player.id, nil)) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } now := time.Now() world.characters[1000000].position = [3]float32{64, 20, 56} world.characters[1000000].roaming.destination = [3]float32{64.25, 14, 56} @@ -299,9 +344,13 @@ func TestRoamingStopsAtTerrainBoundary(t *testing.T) { if err != nil { t.Fatal(err) } + walk, err := readPacket(client) + if err != nil { + t.Fatal(err) + } <-done - if binary.BigEndian.Uint32(packet[36:40]) != 2 || world.characters[1000000].position != [3]float32{64, 20, 56} || world.characters[1000000].roaming.moving { + if binary.BigEndian.Uint32(packet[20:24]) != 0x260f3671 || binary.BigEndian.Uint32(packet[61:65]) != 0 || binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position != [3]float32{64, 20, 56} || world.characters[1000000].roaming.moving { t.Fatal("NPC walked beyond the terrain grid") } }