commit f504f5dcc14720e9b9feafe13e9d23fd6ecf1994
parent e33cfc38af1d1c72b5d5f690ca5bb38818c668db
Author: anon <anon@example.com>
Date: Wed, 28 Oct 2026 16:07:51 +0000
Route mission NPCs around indoor obstructions
Diffstat:
8 files changed, 497 insertions(+), 51 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1732,14 +1732,27 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
and the one-life policy are reconstruction choices. GPU WASM checks cover
a controlled full-health fight, shared100XP/loot/cash, native pickup, corpse
expiry, cold population recovery and abandonment with exact item accounting.
- Combat LOS and general navigation remain open. See
+ Shared combat visibility now rejects obstructions; broader encounter and
+ navigation coverage remains separate. See
[mission encounters](docs/mission-encounters.md).
-- [ ] [P0] Route indoor combatants around actual mesh obstructions. Shared body,
- room, floor and wall handling now bounds pursuit and return; it does not find
- detours. The entrance Leet now spawns on the actual tongue-mesh surface;
- both its route and the z28-to-z43 portal route pass. Native waypoint
- retry/discard does not step up; recover or reconstruct reusable detours
- without enlarging bodies or tunnelling through walls. Cover small/large bodies, disconnected rooms and return routes.
+- [x] [P0] Route indoor combatants around actual mesh obstructions. A bounded
+ shared search probes candidate steps with the actor's original body, room,
+ floor, wall, slope and gravity handling. Pursuit and exact return-home routes
+ now detour through the original side passage; no body enlargement or wall
+ bypass is used. Tests cover small/large admitted bodies, moving targets,
+ disconnected rooms, root cancellation, 30-point native packet bounds,
+ both observers, cold replanning and zero routine position writes. GPU
+ WASM follows the three-point detour to its retained home. The half-metre
+ search and its bounds are reconstruction policy, not a recovered original
+ server algorithm. See [indoor navigation](docs/mission-encounters.md#indoor-navigation).
+- [ ] [P1] Match authoritative NPC motion to the native waypoint follower.
+ The native indoor detour reached home, but lagged the server before a turn
+ correction (about three metres in the retained capture). Recover and compare
+ acceleration, braking, waypoint arrival and floor integration across
+ observer/server clocks; do not mask drift with frequent absolute resets.
+ Extend routing to more original layouts, narrow passages, overlapping floors,
+ live body changes and strong snares. Profile failed searches and simultaneous
+ combatants before increasing mission populations or search bounds.
- [x] Redeem all six original faction mission/bravery token templates through
descriptor-driven owned Use. Evaluate current level and faction, preserve the
original Clan/Omni level50 difference, and atomically consume the physical
diff --git a/docs/mission-encounters.md b/docs/mission-encounters.md
@@ -28,7 +28,7 @@ transferred to a player retain their identities and ownership. Successful
objective settlement retains the population until the assignment's existing
deadline, including surviving enemies and dead remains; it does not reset them.
-## Indoor movement limits
+## Indoor navigation
Indoor pursuit now applies the shared model-specific collision body, room veto,
swept walls, sphere response and floors. Small time steps, gravity and slope
@@ -37,11 +37,23 @@ in memory until the existing periodic NPC checkpoint. Both the entrance and
z28-to-z43 routes cross the actual inter-room portal and return home without per-tick writes. The entrance spawn is grounded on
the tongue mesh at y1.476895, rather than the lower floor beneath that scenery.
-Straight steering still has no detour planner. Native testing exposed an
-authored entrance spawn below the tongue mesh; correcting its vertical placement
-lets shared collision handling traverse the rib in both directions. General
-obstacle routes remain a separate navigation task. Making a Leet use a
-humanoid collision sphere or skipping walls would conceal missing route behavior.
+Mission pursuit and return now share a bounded half-metre route search. Each
+candidate walks a copy of the actor through the same 60Hz physical integration
+used for live motion. Room transitions, original collision bodies, slopes,
+walls and gravity decide reachability. Natural settling handles a horizontal
+arrival above the destination floor. Only physically walkable shortcuts remove
+intermediate points. Search state distinguishes horizontal cells and floor
+height; a query considers at most4096 nodes. Failed queries retry after one
+second instead of repeating on every scheduler tick. These sampling and budget
+choices are reconstruction policy, not recovered original server rules.
+
+Routes remain in memory. A target moving one metre from the planned endpoint
+causes replanning; roots and motion cancellation discard cached waypoints.
+Cold loading reconstructs a route from the persisted pose and home. The live
+actor consumes waypoints within its movement-time budget, and native packets
+carry its current position plus at most29 remaining points. New observers use
+the same remaining route. Indoor close approach also requires a walkable final
+segment; exact native arrival/visibility parity remains unverified.
Original KKR `FUN_10048430`, maintained as
`client/game/kkr.dll/lifted-0023.c:sub_36048430`, does not establish an original
@@ -55,6 +67,33 @@ Evidence and exact addresses are retained in
`local/npc-pursuit-research/followSteering.json` and
`local/mission-encounter-research/integration-audit.md`.
+The original side-passage regression starts at(15,.011,15) and ends at
+(12.5,.011,34). Straight steering stalls near(14.018,.011,20.092). Both the Leet
+and the admitted Salamander Boss body now reach the destination through actual
+room geometry, including exact return-home completion. Existing tongue-mesh
+and inter-room round trips remain covered. Additional regressions cover a
+moving target, disconnected rooms, rooted route cancellation, bounded packets
+to two observers, cold return without observers and zero per-tick position writes.
+
+An isolated GPU WASM visitor accepted mission58 normally. A controlled
+fixture then placed only its NPC1068664 at the regression start, with the
+destination as its retained home and a temporary root to allow observation.
+After expiry, the original client consumed a three-point route, crossed the
+obstruction and reached home;452 native position samples and all three route
+updates are retained under `local/indoor-routing/`. There were no page exceptions.
+The native final x12.375 differs from server x12.491 by the existing movement
+packet quantization. The native follower lagged before the turn, then received
+an approximately three-metre correction. Acceleration, braking and waypoint
+timing parity remain open; reaching the endpoint does not establish smooth or
+canonical motion. Both actors are visible in `native-return-visible.png`.
+
+The fixture's poses/home were restored, the root expired, and the owned browser
+closed. The earned character5's complete character/player rows, eight item
+instances, learned nanos and contracts were unchanged. No rewards or combat
+balance outcome is claimed for this controlled navigation check. On the local
+machine, isolated first-tick detour searches took about49ms at100HP and87ms
+at1HP; these are observations, not a population-scale performance guarantee.
+
## Completion token evidence
Mission completion XP/token eligibility remains unresolved. Ordinary kill XP
@@ -114,10 +153,10 @@ retirement is additionally covered by the Go fault/retry tests. No browser
exceptions or adapter aborts were recorded. Existing unattributed404 console
messages remain in the captured logs.
-Fighting around raised scenery also exposed the existing lack of combat LOS
-rejection. A small actor below the tongue could fight a player above it; its
-corpse was easier to select from the other side. This remains P0 work alongside
-general detour routing, separately from the corrected authored entrance spawn.
+Fighting around raised scenery exposed missing combat LOS rejection in that
+earlier capture. Shared [combat visibility](combat-visibility.md) now supplies
+the obstruction checks, separately from the authored entrance placement and
+the bounded detour routing described above.
A final cold restart restored the test character's original raw Body
Development5 and normal HP while retaining200XP,44credits after the next request
diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md
@@ -31,10 +31,11 @@ server as 4.5 metres/second. Selecting that default for admitted pursuit and ret
is provisional; it is not an original-server species 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 still steers straight toward the destination without detour planning.
+outdoor server controller still steers straight toward its destination.
Outdoor terrain-height interpolation preserves the authored spawn offset.
-Indoor pursuit now uses shared collision bodies, walls, room veto, floor and
-gravity in small steps; see [mission movement limits](mission-encounters.md#indoor-movement-limits).
+Indoor pursuit now plans bounded detours through shared collision bodies,
+walls, room veto, floor and gravity in small steps; see
+[indoor navigation](mission-encounters.md#indoor-navigation).
Each scheduler step remains capped at 0.25 seconds.
Return to the retained spawn is an explicit reconstruction policy. A bounded
@@ -42,7 +43,7 @@ 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. Unprofiled
appearance stand-ins do not acquire combat pursuit. Proximity aggression,
-outdoor obstruction rejection and general obstacle navigation remain separate TODOs.
+outdoor obstruction rejection and broader navigation fidelity remain separate TODOs.
Motion state retains home, destination, idle-wandering eligibility and return
progress independently of combat capability. It uses the existing periodic NPC
@@ -74,13 +75,17 @@ forwards the movement control, clears the NPC's old PathGuide, and calls
`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
+The server sends self as the route's target identity and current position.
+Straight routes contain two points: current position and destination. Indoor
+detours contain current position followed by up to29 remaining waypoints;
+turns refresh that remaining route. 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.
+Native detour captures expose a remaining lag/correction mismatch before
+turns; endpoint arrival does not establish native acceleration or timing parity.
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
diff --git a/server/npc_navigation.go b/server/npc_navigation.go
@@ -0,0 +1,122 @@
+package main
+
+import (
+ "container/heap"
+ "math"
+)
+
+// Candidate routes and live movement use identical body, slope and wall handling.
+func (npc *character) walkIndoor(position [3]float32, seconds float64) {
+ previous := npc.position
+ frames := max(1, int(math.Ceil(seconds*60)))
+ frameSeconds := float32(seconds) / float32(frames)
+ for range frames {
+ before := npc.position
+ displacement := [3]float32{(position[0] - previous[0]) / float32(frames), 0, (position[2] - previous[2]) / float32(frames)}
+ if npc.movement.normal[1] > .001 {
+ displacement[1] = -(npc.movement.normal[0]*displacement[0] + npc.movement.normal[2]*displacement[2]) / npc.movement.normal[1]
+ }
+ for axis := range npc.position {
+ npc.position[axis] += displacement[axis]
+ }
+ if npc.movement.falling {
+ npc.movement.verticalVelocity = max(float32(-50), npc.movement.verticalVelocity-20*frameSeconds)
+ npc.position[1] += npc.movement.verticalVelocity * frameSeconds
+ }
+ npc.alignSurface(before, false)
+ }
+}
+
+func indoorWalk(npc character, destination [3]float32) (character, bool) {
+ distance := math.Hypot(float64(destination[0]-npc.position[0]), float64(destination[2]-npc.position[2]))
+ npc.walkIndoor(destination, distance/float64(npc.runningMovementSpeed(false)))
+ // A descent may reach the horizontal goal before gravity reaches its floor.
+ for settle := 0; npc.movement.falling && settle < 8; settle++ {
+ npc.walkIndoor(npc.position, .25)
+ }
+ x, z := npc.position[0]-destination[0], npc.position[2]-destination[2]
+ return npc, x*x+z*z < .0025
+}
+
+type navigationNode struct {
+ actor character
+ parent *navigationNode
+ x, z int
+ cost float64
+ priority float64
+}
+
+type navigationQueue []*navigationNode
+
+func (queue navigationQueue) Len() int { return len(queue) }
+func (queue navigationQueue) Less(i, j int) bool { return queue[i].priority < queue[j].priority }
+func (queue navigationQueue) Swap(i, j int) { queue[i], queue[j] = queue[j], queue[i] }
+func (queue *navigationQueue) Push(value any) { *queue = append(*queue, value.(*navigationNode)) }
+func (queue *navigationQueue) Pop() any {
+ last := len(*queue) - 1
+ node := (*queue)[last]
+ *queue = (*queue)[:last]
+ return node
+}
+
+func indoorRoute(npc *character, destination [3]float32) [][3]float32 {
+ // This bounded half-metre search is reconstruction policy, not a recovered
+ // original server algorithm. Probe copies never alter the live actor or DB.
+ if npc.geometry.mission(npc.playfield).roomAt(destination) == nil {
+ return nil
+ }
+ if arrived, ok := indoorWalk(*npc, destination); ok && surfaceDistanceSquared(arrived.position, destination) < .01 {
+ return [][3]float32{destination}
+ }
+ start := &navigationNode{actor: *npc}
+ 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++ {
+ node := heap.Pop(&queue).(*navigationNode)
+ if surfaceDistanceSquared(node.actor.position, destination) < 1 {
+ if arrived, ok := indoorWalk(node.actor, destination); ok && surfaceDistanceSquared(arrived.position, destination) < .01 {
+ points := [][3]float32{destination}
+ for at := node; at.parent != nil; at = at.parent {
+ points = append(points, at.actor.position)
+ }
+ for i, j := 0, len(points)-1; i < j; i, j = i+1, j-1 {
+ points[i], points[j] = points[j], points[i]
+ }
+ // Keep only shortcuts that the same physical actor can walk.
+ var route [][3]float32
+ actor := *npc
+ for len(points) != 0 {
+ for i := len(points) - 1; i >= 0; i-- {
+ arrived, ok := indoorWalk(actor, points[i])
+ if ok && surfaceDistanceSquared(arrived.position, points[i]) < .01 {
+ route = append(route, points[i])
+ actor, points = arrived, points[i+1:]
+ break
+ }
+ if i == 0 {
+ return nil
+ }
+ }
+ }
+ return route
+ }
+ }
+ for _, offset := range [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}} {
+ x, z := node.x+offset[0], node.z+offset[1]
+ point := [3]float32{npc.position[0] + float32(x)*.5, node.actor.position[1], npc.position[2] + float32(z)*.5}
+ actor, ok := indoorWalk(node.actor, point)
+ if !ok {
+ continue
+ }
+ key := [3]int{x, int(math.Round(float64(actor.position[1]) * 2)), z}
+ cost := node.cost + math.Sqrt(float64(surfaceDistanceSquared(node.actor.position, actor.position)))
+ if previous, exists := costs[key]; exists && previous <= cost {
+ continue
+ }
+ costs[key] = cost
+ heap.Push(&queue, &navigationNode{actor: actor, parent: node, x: x, z: z, cost: cost,
+ priority: cost + math.Sqrt(float64(surfaceDistanceSquared(actor.position, destination)))})
+ }
+ }
+ return nil
+}
diff --git a/server/npc_navigation_test.go b/server/npc_navigation_test.go
@@ -0,0 +1,218 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "testing"
+ "time"
+)
+
+func TestMissionNPCWalksAroundTheTongueAfterDescending(t *testing.T) {
+ for _, returning := range []bool{false, true} {
+ t.Run(fmt.Sprintf("returning=%t", returning), func(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position = [3]float32{15, .011, 15}
+ npc.fighting = player.id
+ world.fighting[npc.id] = npc
+ start := time.Now()
+ world.lastNPCUpdate = start
+ if _, err := world.db.Exec("CREATE TABLE navigation_writes (count INTEGER); INSERT INTO navigation_writes VALUES (0); CREATE TRIGGER count_navigation_writes AFTER UPDATE OF position_x,position_y,position_z ON characters WHEN NEW.id=2000003 BEGIN UPDATE navigation_writes SET count=count+1; END"); err != nil {
+ t.Fatal(err)
+ }
+
+ for tick := 1; tick <= 48; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+ lower := npc.position
+ player.position = [3]float32{15, .011, 28}
+ if returning {
+ player.health = 0
+ }
+ for tick := 49; tick <= 144; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ var writes int
+ if err := world.db.QueryRow("SELECT count FROM navigation_writes").Scan(&writes); err != nil {
+ t.Fatal(err)
+ }
+ if lower[2] >= 17 || npc.position[2] < 26 || npc.position[1] > .1 ||
+ world.geometry.mission(npc.playfield).roomAt(npc.position) == nil || writes != 0 {
+ t.Fatal("indoor actor failed to walk back around scenery without position writes", lower, npc.position, writes)
+ }
+ if returning && (npc.motion.returning || npc.motion.moving || surfaceDistanceSquared(npc.position, npc.motion.home) >= .01) {
+ t.Fatal("obstacle route did not finish the return home", npc.position, npc.motion)
+ }
+ })
+ }
+}
+
+func TestMissionNPCDetoursIntoTheSidePassage(t *testing.T) {
+ for _, monster := range []uint32{17655, 30354} {
+ for _, returning := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%d/returning=%t", monster, returning), func(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ npc.monsterData, npc.body = monster, playerCollisionBody{}
+ if monster == 30354 {
+ npc.level, npc.combatProfile = 4, gamedata.NPCCombatProfiles[30354][4]
+ }
+ npc.position = [3]float32{15, .011, 15}
+ player.position = [3]float32{12.5, .011, 34}
+ if returning {
+ npc.motion.home, npc.motion.returning = player.position, true
+ } else {
+ npc.fighting = player.id
+ world.fighting[npc.id] = npc
+ }
+ start := time.Now()
+ world.lastNPCUpdate = start
+ deadline := start.Add(time.Second)
+ npc.nextAttack = deadline
+
+ for tick := 1; tick <= 96; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if surfaceDistanceSquared(npc.position, player.position) >= 4 || npc.position[2] < 32 || npc.nextAttack != deadline {
+ t.Fatal("NPC followed the obstructed straight line instead of a walkable detour", npc.position)
+ }
+ if returning && (npc.motion.returning || npc.motion.moving || surfaceDistanceSquared(npc.position, npc.motion.home) >= .01) {
+ t.Fatal("detour did not reach the exact retained home", npc.position, npc.motion)
+ }
+ })
+ }
+ }
+}
+
+func TestMissionNPCRouteFollowsAChangingTarget(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ npc.position = [3]float32{15, .011, 15}
+ player.position = [3]float32{12.5, .011, 34}
+ npc.fighting = player.id
+ world.fighting[npc.id] = npc
+ start := time.Now()
+ world.lastNPCUpdate = start
+ world.advanceNPCs(start.Add(250 * time.Millisecond))
+
+ for tick := 2; tick <= 9; tick++ {
+ player.position[0] += .25
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+ for tick := 10; tick <= 96; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if surfaceDistanceSquared(npc.position, player.position) >= 4 || npc.motion.moving || npc.fighting != player.id {
+ t.Fatal("cached route ignored a target moving in small increments", npc.position, npc.motion)
+ }
+}
+
+func TestMissionNPCLongRoutePublishesBoundedWaypointsToBothObservers(t *testing.T) {
+ world, _, first := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position = [3]float32{15, .011, 43}
+ npc.fighting = player.id
+ world.fighting[npc.id] = npc
+ npc.motion.destination, npc.motion.moving = player.position, true
+ for point := 1; point <= 40; point++ {
+ npc.motion.route = append(npc.motion.route, [3]float32{15, .011, 28 + float32(point)*.375})
+ }
+ second := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 65536, position: player.position}
+ world.clients[2] = &worldClient{id: 2, conn: second, target: true, ready: true, npcs: map[uint32]bool{npc.id: true}}
+ start := time.Now()
+ world.lastNPCUpdate = start
+
+ world.advanceNPCs(start.Add(250 * time.Millisecond))
+
+ var routes [2][]byte
+ for index, output := range []*combatTestConn{first, second} {
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x260f3671 && binary.BigEndian.Uint32(packet[24:28]) == npc.id {
+ routes[index] = packet
+ }
+ }
+ }
+ if len(routes[0]) != 420 || len(routes[1]) != 420 || binary.BigEndian.Uint16(routes[0][6:8]) != 418 || !bytes.Equal(routes[0][16:], routes[1][16:]) || binary.BigEndian.Uint32(routes[0][54:58]) != 30 || len(npc.motion.route) <= 29 {
+ t.Fatal("native route exceeded its 30-point capacity or missed an observer", len(routes[0]), len(routes[1]), len(npc.motion.route))
+ }
+}
+
+func TestMissionNPCDoesNotCrossDisconnectedRooms(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position = [3]float32{15, .011, 43}
+ scene := world.geometry.mission(npc.playfield)
+ scene.links = nil
+ npc.fighting = player.id
+ world.fighting[npc.id] = npc
+ start := time.Now()
+ world.lastNPCUpdate = start
+ before := npc.position
+
+ world.advanceNPCs(start.Add(250 * time.Millisecond))
+ retry := npc.motion.routeRetry
+ world.advanceNPCs(start.Add(500 * time.Millisecond))
+
+ 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)
+ }
+}
+
+func TestMissionNPCRootClearsPendingDetour(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ npc.position = [3]float32{15, .011, 15}
+ player.position = [3]float32{12.5, .011, 34}
+ npc.fighting = player.id
+ world.fighting[npc.id] = npc
+ start := time.Now()
+ world.lastNPCUpdate = start
+ world.advanceNPCs(start.Add(250 * time.Millisecond))
+ 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))
+
+ 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)
+ }
+}
+
+func TestMissionNPCColdLoadReplansTheReturnWithoutObservers(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ npc := world.characters[2000003]
+ npc.position = [3]float32{15, .011, 15}
+ npc.motion.home = [3]float32{12.5, .011, 34}
+ npc.motion.returning = true
+ start := time.Now()
+ world.lastNPCUpdate = start
+ world.advanceNPCs(start.Add(250 * time.Millisecond))
+ if len(npc.motion.route) == 0 {
+ t.Fatal("fixture did not start an obstacle return")
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+
+ cold := reloadMissionEntranceWorld(t)
+ restored := cold.characters[npc.id]
+ cached := len(restored.motion.route)
+ cold.lastNPCUpdate = start
+ for tick := 1; tick <= 96; tick++ {
+ cold.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if cached != 0 || restored.motion.returning || restored.motion.moving || len(restored.motion.route) != 0 ||
+ surfaceDistanceSquared(restored.position, restored.motion.home) >= .01 || restored.health != npc.health || restored.fighting != 0 {
+ t.Fatal("cold return restored transient waypoints, lost its home or healed", restored.position, restored.motion)
+ }
+}
diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go
@@ -12,6 +12,10 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
if npc.combatProfile == nil || npc.fighting == 0 && !npc.motion.returning {
return false
}
+ indoor := server.geometry != nil && server.geometry.mission(npc.playfield) != nil
+ if indoor {
+ npc.geometry = server.geometry
+ }
destination := npc.motion.home
if npc.fighting != 0 {
target := server.characters[npc.fighting]
@@ -25,8 +29,15 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
// 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 && !npc.movement.falling {
- server.stopNPCMotion_locked(npc, updates)
- return true
+ clear := true
+ if indoor {
+ arrived, ok := indoorWalk(*npc, destination)
+ clear = ok && surfaceDistanceSquared(arrived.position, destination) < .01
+ }
+ if clear {
+ server.stopNPCMotion_locked(npc, updates)
+ return true
+ }
}
}
}
@@ -43,7 +54,7 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
position[2] += float32(z / distance * step)
}
- // Match roaming's terrain-height policy without inventing wall navigation.
+ // Match roaming's terrain-height policy for outdoor actors.
if ground := server.terrain[npc.playfield]; ground != nil {
home, available := ground.elevation(npc.motion.home[0], npc.motion.home[2])
if available {
@@ -55,32 +66,59 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
position[1] = npc.motion.home[1] + height - home
}
}
- previous := npc.position
- npc.position = position
- if server.geometry != nil && server.geometry.mission(npc.playfield) != nil {
- // Indoor actors use the same body, room veto, swept walls and floors as players.
- npc.geometry = server.geometry
- npc.position = previous
- frames := max(1, int(math.Ceil(seconds*60)))
- frameSeconds := float32(seconds) / float32(frames)
- for range frames {
- before := npc.position
- displacement := [3]float32{}
- for _, axis := range []int{0, 2} {
- displacement[axis] = (position[axis] - previous[axis]) / float32(frames)
+ changed := !npc.motion.moving || npc.motion.destination != destination
+ if indoor {
+ replan := 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
+ }
+ if replan {
+ npc.motion.route = indoorRoute(npc, destination)
+ if len(npc.motion.route) == 0 {
+ npc.motion.routeRetry = now.Add(time.Second)
+ } else {
+ npc.motion.routeRetry = time.Time{}
}
- if npc.movement.normal[1] > .001 {
- displacement[1] = -(npc.movement.normal[0]*displacement[0] + npc.movement.normal[2]*displacement[2]) / npc.movement.normal[1]
+ changed = true
+ }
+ if len(npc.motion.route) == 0 {
+ npc.walkIndoor(npc.position, seconds)
+ server.stopNPCMotion_locked(npc, updates)
+ npc.motion.destination = destination
+ return true
+ }
+ for seconds > 0 && len(npc.motion.route) != 0 {
+ waypoint := npc.motion.route[0]
+ x, z = float64(waypoint[0]-npc.position[0]), float64(waypoint[2]-npc.position[2])
+ duration := math.Hypot(x, z) / float64(npc.runningMovementSpeed(false))
+ if math.Hypot(x, z) < .05 {
+ duration = seconds
}
- for axis := range npc.position {
- npc.position[axis] += displacement[axis]
+ travel := math.Min(seconds, duration)
+ position = waypoint
+ if travel < duration {
+ ratio := float32(travel / duration)
+ position[0] = npc.position[0] + float32(x)*ratio
+ position[2] = npc.position[2] + float32(z)*ratio
}
- if npc.movement.falling {
- npc.movement.verticalVelocity = max(float32(-50), npc.movement.verticalVelocity-20*frameSeconds)
- npc.position[1] += npc.movement.verticalVelocity * frameSeconds
+ npc.walkIndoor(position, travel)
+ seconds -= travel
+ if surfaceDistanceSquared(npc.position, waypoint) < .01 {
+ npc.motion.route = npc.motion.route[1:]
+ changed = true
+ } else {
+ // A body change or live collision invalidates the cached route.
+ dx, dz := npc.position[0]-position[0], npc.position[2]-position[2]
+ if dx*dx+dz*dz >= .0025 || duration == 0 {
+ server.stopNPCMotion_locked(npc, updates)
+ npc.motion.routeRetry = now.Add(time.Second)
+ return true
+ }
+ break
}
- npc.alignSurface(before, false)
}
+ } else {
+ npc.position = position
}
if distance != 0 {
angle := math.Atan2(x, z)
@@ -88,13 +126,12 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
}
// Complete the return before allowing another idle roaming destination.
- if npc.fighting == 0 && !npc.movement.falling && distance <= step && surfaceDistanceSquared(npc.position, destination) < .01 {
+ if npc.fighting == 0 && !npc.movement.falling && surfaceDistanceSquared(npc.position, destination) < .01 {
server.stopNPCMotion_locked(npc, updates)
npc.motion.returning = false
npc.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
return true
}
- changed := !npc.motion.moving || npc.motion.destination != destination
npc.motion.destination = destination
npc.motion.moving = true
npc.running = true
@@ -105,6 +142,7 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
}
func (server *server) stopNPCMotion_locked(npc *character, updates map[*worldClient][][]byte) {
+ npc.motion.route = nil
if !npc.motion.moving {
return
}
@@ -119,6 +157,9 @@ func npcRoutePacket(npc *character) []byte {
targetType, targetID, control, count := uint32(0), uint32(0), byte(19), uint32(0)
if npc.motion.moving {
targetType, targetID, control, count = 50000, npc.id, 22, 2
+ if len(npc.motion.route) != 0 {
+ count = uint32(1 + min(29, len(npc.motion.route)))
+ }
if npc.running {
control = 23
}
@@ -133,7 +174,11 @@ func npcRoutePacket(npc *character) []byte {
}
body = binary.BigEndian.AppendUint32(body, count)
if npc.motion.moving {
- for _, position := range [][3]float32{npc.position, npc.motion.destination} {
+ points := [][3]float32{npc.position, npc.motion.destination}
+ if len(npc.motion.route) != 0 {
+ points = append(points[:1], npc.motion.route[:min(29, len(npc.motion.route))]...)
+ }
+ for _, position := range points {
for _, value := range position {
body = binary.BigEndian.AppendUint32(body, math.Float32bits(value))
}
diff --git a/server/roaming.go b/server/roaming.go
@@ -15,6 +15,8 @@ type npcMotion struct {
nextMove time.Time
moving bool
returning bool
+ route [][3]float32
+ routeRetry time.Time
}
func (server *server) roamNPCs() {
diff --git a/server/world_store.go b/server/world_store.go
@@ -196,7 +196,9 @@ func (server *server) loadNPCs() (bool, error) {
npc.combatProfile = npcCombatProfile(npc.npcDefinitionID, npc.monsterData, npc.level)
npc.leadingContributor = state.LeadingContributor
if state.IdleRoaming || npc.combatProfile != nil {
- npc.motion = &npcMotion{state.IdleRoaming, state.Motion.Home, state.Motion.Destination, state.Motion.NextMove, state.Motion.Moving, state.Motion.Returning}
+ npc.motion = &npcMotion{roaming: state.IdleRoaming, home: state.Motion.Home,
+ destination: state.Motion.Destination, nextMove: state.Motion.NextMove,
+ moving: state.Motion.Moving, returning: state.Motion.Returning}
// Combat targets are transient; displaced combatants return before idling.
if npc.combatProfile != nil && npc.health != 0 {
npc.motion.moving, npc.running = false, false