commit 1a44747956849a516fa3be506ddf5125b92450db
parent b1c1c6cdb906730f97fc8a60f4b3fcaca7fba4ba
Author: anon <anon@example.com>
Date: Mon, 2 Nov 2026 23:54:21 +0000
Use native surface physics for outdoor NPC movement
Diffstat:
10 files changed, 421 insertions(+), 42 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -740,7 +740,7 @@ for exact records, protocol, tests and remaining reconstruction assumptions.
## NPC profiles and behavior
-- [ ] [P1] Verify playable placement for generated district-center fallbacks.
+- [x] [P1] Verify playable placement for generated district-center fallbacks.
A native melee attempt against `950/district/5/group/0/district_center_fallback`
near X138/Z98 left the player around Y13.45 and the NPC around Y10.8, with no
damage during the attempt. Check the actual terrain/static geometry and
@@ -753,10 +753,16 @@ for exact records, protocol, tests and remaining reconstruction assumptions.
district cells for all 23 admitted fallback combatants; authored points and
raw records stay unchanged. A controlled two-client WASM check verifies real
selection, walking and melee at the repaired shore spawn, with matching HP.
- Keep this open: a deterministic ordinary four-metre roaming route returns
- that Leet to the pond through the existing terrain-offset movement path.
- Resolve roaming/pursuit water eligibility before claiming usable wandering;
- original sampling remains provisional. See [fallback placement](docs/npc-placement.md).
+ Outdoor motion now uses shared body/floor/water contact and native swimming
+ controls instead of preserving a submerged terrain offset. A controlled
+ four-metre idle route, both page reloads, dry return, ordinary melee and living
+ pursuit agree on two native replicas; Go also checks cold return without an
+ observer. Original sampling remains provisional. See
+ [fallback placement](docs/npc-placement.md).
+- [ ] [P2] Recover original fallback sampling and outdoor NPC route eligibility.
+ Check district placement, water boundaries and aquatic/flying distinctions
+ against period server evidence. Native swimming support establishes vehicle
+ behavior, not the original server's destination-selection policy.
- [ ] [P1] Incorporate the reviewed NPC mappings from the NPC mapping research.
Read its `README.md` and `reports/all-npc-code-assignments.json`, then merge
relevant changes surgically into the current checkout. Preserve per-context
diff --git a/docs/npc-placement.md b/docs/npc-placement.md
@@ -40,16 +40,38 @@ The two-client WASM check uses controlled default level-1 players and holds idle
while isolating initial placement. Real first-person camera input selects the
downhill Leet; ordinary walking enters range and Q starts/stops combat. The
single five-point hit leaves both native replicas and the server at 95/100 HP.
-This is neither earned progression nor proof of usable wandering. The related
+This isolates initial placement from wandering and earned progression. The related
Go selection passes in 15.004s; focused race checks pass in 107.346s; vet and
Node syntax checks pass. The final native run takes 25.46s, or 33.086s including
Go. Reviewed screenshots, complete traces, independent verification and earlier
failed trials are under `local/fallback-placement/`; the successful capture is
`20261102-152355/`.
-The placement TODO remains open. A deterministic follow-up through
-`advanceNPCs` gives the first Leet an ordinary four-metre idle destination
-`[134,14,98]`. The existing terrain-offset movement reaches approximately
-`[133.01001,11.892994,98]` under water at Y13.520653. Ground/water eligibility
-for roaming and pursuit remains unresolved; moving the initial home alone
-does not solve that path. See `roaming-followup.log` and its retained reproducer.
+A follow-up through `advanceNPCs` gives the first Leet an ordinary four-metre
+idle destination `[134,14,98]`. The terrain-offset shortcut formerly reached
+approximately `[133.01001,11.892994,98]` under water at Y13.520653. Outdoor NPC
+motion now uses the same body, floor, gravity and water alignment as the native
+vehicle. Swimming mode 4 selects the existing Swimming-based speed and rejects
+walk/run toggles until water exit. This repairs both roaming and pursuit
+without introducing a species water ban. See [surface motion](npc-pursuit.md#outdoor-surface-and-water-contact).
+
+Three focused Go regressions reproduce submerged roaming/pursuit before the
+change and verify surface contact, retained encounter state and cold return
+without observers afterward. A two-client WASM fixture selects that one idle
+destination and holds subsequent idle choices; it does not teleport the NPC.
+Both players are controlled level-10 characters with default skills, permitting
+the ordinary encounter to continue without a survival grind. The Leet stops
+at `[133.00801,13.480606,98]` in swimming mode. Both page reloads retain that
+contact and mode. Return leaves water in walking mode near the unchanged home;
+real mouse selection, walking and Q then deliver a five-point hit. The living
+NPC pursues the player into the pond, with both native replicas retaining
+95/100 HP and matching the server's swimming mode and surface contact.
+
+The selected phase comparisons are within .146 metres; asynchronous intermediate
+samples reach .338 metres and do not establish identical frame-by-frame paths.
+Both complete traces have empty error lists and zero dropped events. Screenshots,
+source evidence, independent verification and failed trials are retained under
+`local/npc-water-motion/`, with final capture `20261102-154544/`.
+The placement/interaction defect is resolved; original random sampling and
+outdoor destination eligibility, including aquatic/flying distinctions, remain
+a separate historical-policy TODO.
diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md
@@ -32,9 +32,10 @@ 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
outdoor server controller still steers straight toward its destination.
-Outdoor terrain-height interpolation preserves the authored spawn offset.
-Indoor pursuit now plans bounded detours through shared collision bodies,
-walls, room veto, floor and gravity in small steps; see
+Physical outdoor and indoor scenes use shared collision bodies, floor, water
+and gravity; terrain-height offsets remain only when physical geometry is
+unavailable. Indoor pursuit plans bounded detours through walls and room veto
+in small steps; see
[indoor navigation](mission-encounters.md#indoor-navigation).
Each scheduler step remains capped at 0.25 seconds, with force/velocity integration
subdivided at 60Hz. Walking retains its native 1.5 metres/second cap. Both modes
@@ -47,7 +48,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 broader navigation fidelity remain separate TODOs.
+outdoor detour planning 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
@@ -58,6 +59,47 @@ return until expiry, and the normal signed run-speed rule applies to snares.
Dead remains stay where they fell; the separately committed replacement life
starts at home and inherits the same idle policy.
+## Outdoor surface and water contact
+
+Original KKR `NPCVehicle_t` at `0x1004aac0` derives through the character vehicle
+at `0x100476e0`. Its vtable at `0x10170f30` retains the shared surface callbacks;
+the active check at `0x1004aef0` skips ordinary idle physics while continuing
+path/follow/jump/fall work. QQR `Vehicle_t::EnsureSurfaceAlignment` at
+`0x10012a50` supplies body contact, water clearance, smoothing and gravity.
+The maintained KKR source `client/game/kkr.dll/lifted-0023.c`,
+`sub_36048200`/`sub_36048210`, forwards water entry/exit actions 24/31.
+The original NPC is observed in swimming mode 4 with Swimming 5; it is not
+subject to a universal native prohibition on entering water.
+
+The server applies that existing physical path to outdoor roaming, pursuit and
+return. Each substep selects its speed from the current movement mode, so water
+entry immediately changes the cap. Walk/run requests use the same action
+admission as the native state machine: swimming rejects those toggles and
+retains its prior preference until exit. Route stops clear velocity and apply
+the controls already sent to observers. A body blocked by geometry stops its
+idle route rather than continuing through it; outdoor detours remain unplanned.
+These changes use in-memory motion and the existing periodic checkpoints.
+
+A native floor contact at the pond includes a water-minus-1.2 clamp. Starting
+at its quantized Y12.3125, one shared alignment step gives Y12.437904, matching
+the original native NPC's Y12.4379053. An idle actor need not finish rising;
+an active route continues toward the water contact. This explains the earlier
+partial lift without adding a special NPC liquid offset. The controlled
+two-client roaming/reload/return/melee/pursuit check and cold Go regression are
+described in [fallback placement](npc-placement.md). Original server water
+eligibility and random destination selection remain unresolved; native vehicle
+behavior alone does not establish those policies. Source records are retained
+in `local/npc-water-motion/qqr-evidence.json` and `kkr-evidence.json`.
+
+The existing two-client Wardroid/collector stop regression also passes with
+these outdoor consumers: 140 samples, 52 observed stops, and at least three
+stops per original actor/client before and after reconnect. Fifty subsequent
+settled comparisons have a maximum .159-metre error. One asynchronous first
+stop comparison is .218 metres before delivery and .113 metres in the next
+snapshot. Both browser error lists are empty; this older harness's event rings
+overflow, so its separately saved motion samples establish the stop checks.
+The water scenario above retains both complete event traces.
+
## Native route contract
Original 14.9.1 `kkr.dll` SHA-256:
diff --git a/server/browser_npc_water_test.go b/server/browser_npc_water_test.go
@@ -0,0 +1,112 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserNPCOutdoorWaterMotion(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for the focused outdoor NPC water check")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/npc-water-motion", time.Now().Format("20060102-150405"))
+ world, npc, _ := newNPCOutdoorSurfaceWorld(t)
+ world.clients = make(map[uint32]*worldClient)
+ players := []*character{world.characters[1], world.newCharacter()}
+ for index, player := range players {
+ player.name, player.level = fmt.Sprint("Watermotion", index), 10
+ player.health = player.maximumHealth()
+ player.position = [3]float32{126, 20, 98 + float32(index)*4}
+ point, normal := player.position, [3]float32{}
+ world.geometry.floor(950, world.terrain[950], player.position, &point, &normal)
+ player.position[1] = point[1] + .01
+ player.rotation = [4]float32{0, .70710677, 0, .70710677}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("water-motion-", index))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"enemy": npc.id, "owner": players[0].id, "position": npc.position,
+ "home": npc.motion.home, "destination": npc.motion.destination, "moving": npc.motion.moving,
+ "returning": npc.motion.returning, "mode": npc.movement.components[0], "deepWater": npc.movement.deepWater,
+ "health": npc.health, "fighting": npc.fighting, "ownerHealth": players[0].health,
+ "ownerPosition": predictedPosition_locked(players[0], time.Now()), "ownerFighting": players[0].fighting})
+ })
+ // Choose one ordinary four-metre idle route without moving or healing its actor.
+ mux.HandleFunc("POST /test-roam", func(w http.ResponseWriter, r *http.Request) {
+ world.updateMutex.Lock()
+ defer world.updateMutex.Unlock()
+ world.mutex.Lock()
+ npc.motion.destination = [3]float32{134, 14, 98}
+ npc.motion.moving, npc.motion.nextMove = true, time.Now()
+ npc.movement.action(npc, 22)
+ packet := npcRoutePacket(npc, npc.position)
+ world.mutex.Unlock()
+ world.broadcast(950, 0, packet)
+ w.WriteHeader(http.StatusNoContent)
+ })
+ mux.HandleFunc("POST /test-return", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ npc.motion.returning = true
+ world.mutex.Unlock()
+ w.WriteHeader(http.StatusNoContent)
+ })
+ host := httptest.NewServer(mux)
+ defer host.Close()
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case now := <-ticker.C:
+ world.advancePlayerMovement(now)
+ world.advanceNPCs(now)
+ world.advanceCombat(now)
+ world.mutex.Lock()
+ if !npc.motion.moving && !npc.motion.returning && npc.fighting == 0 {
+ npc.motion.nextMove = now.Add(time.Hour)
+ }
+ world.mutex.Unlock()
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ defer func() { cancel(); <-stopped }()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_npc_water.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ cancel()
+ <-stopped
+ t.Logf("Browser artifacts: %s", output)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ if npc.health >= 100 || npc.movement.components[0] != 4 || !npc.movement.deepWater || players[0].health == 0 {
+ t.Fatal("native ordinary hit and pursuit did not retain the living water encounter")
+ }
+}
diff --git a/server/npc_motion.go b/server/npc_motion.go
@@ -20,13 +20,15 @@ func (npc *character) advanceNPCMotion(destination [3]float32, seconds float64)
frames := max(1, int(math.Ceil(seconds*60)))
step := float32(seconds) / float32(frames)
bodyMass, carriedMass := npc.movementMass()
- speed := float32(1.5)
- if npc.running {
- speed = npc.runningMovementSpeed(false)
- }
- forceLimit := min(float32(10000), 2*(bodyMass+float32(carriedMass)*float32(.001))*speed)
- indoor := npc.geometry != nil && npc.geometry.mission(npc.playfield) != nil
+ physical := npc.geometry.physical(npc.playfield)
for range frames {
+ speed := float32(1.5)
+ if npc.movement.components[0] == 4 {
+ speed = npc.swimmingMovementSpeed()
+ } else if npc.running {
+ speed = npc.runningMovementSpeed(false)
+ }
+ forceLimit := min(float32(10000), 2*(bodyMass+float32(carriedMass)*float32(.001))*speed)
for len(npc.motion.route) != 0 {
x, z := npc.motion.route[0][0]-npc.position[0], npc.motion.route[0][2]-npc.position[2]
if x*x+z*z >= 1 {
@@ -53,7 +55,7 @@ func (npc *character) advanceNPCMotion(destination [3]float32, seconds float64)
}
npc.movement.integrateForce(force, step, bodyMass, speed, forceLimit)
// Retain the floor tangent for the next force and speed-cap calculation.
- if indoor && npc.movement.normal[1] > .001 {
+ if physical && npc.movement.normal[1] > .001 {
npc.movement.velocity[1] = float32(-(float64(npc.movement.normal[2])*float64(npc.movement.velocity[2]) + float64(npc.movement.normal[0])*float64(npc.movement.velocity[0])) / float64(npc.movement.normal[1]))
}
position := npc.position
@@ -61,8 +63,8 @@ func (npc *character) advanceNPCMotion(destination [3]float32, seconds float64)
position[axis] += npc.movement.velocity[axis] * step
}
npc.movement.previousPosition = npc.position
- if indoor {
- npc.walkIndoor(position, seconds/float64(frames))
+ if physical {
+ npc.walkSurface(position, seconds/float64(frames))
x, z := npc.position[0]-position[0], npc.position[2]-position[2]
if x*x+z*z >= .0025 {
return false, true
diff --git a/server/npc_navigation.go b/server/npc_navigation.go
@@ -6,7 +6,7 @@ import (
)
// Candidate routes and live movement use identical body, slope and wall handling.
-func (npc *character) walkIndoor(position [3]float32, seconds float64) {
+func (npc *character) walkSurface(position [3]float32, seconds float64) {
previous := npc.position
frames := max(1, int(math.Ceil(seconds*60)))
frameSeconds := float32(seconds) / float32(frames)
@@ -40,10 +40,10 @@ 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)))
+ npc.walkSurface(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)
+ npc.walkSurface(npc.position, .25)
}
x, z := npc.position[0]-destination[0], npc.position[2]-destination[2]
return npc, x*x+z*z < .0025
diff --git a/server/npc_outdoor_surface_test.go b/server/npc_outdoor_surface_test.go
@@ -0,0 +1,83 @@
+package main
+
+import (
+ "math"
+ "testing"
+ "time"
+)
+
+func newNPCOutdoorSurfaceWorld(t *testing.T) (*server, *character, time.Time) {
+ t.Helper()
+ world := newTestServer(t)
+ var npc *character
+ for _, actor := range world.characters {
+ if actor.npcDefinitionID == "950/district/5/group/0/district_center_fallback" && (npc == nil || actor.id < npc.id) {
+ npc = actor
+ }
+ }
+ player := world.newCharacter()
+ player.position = [3]float32{138, 13.5, 98}
+ world.characters = map[uint32]*character{player.id: player, npc.id: npc}
+ world.mobileNPCs = map[uint32][]*character{950: {npc}}
+ world.clients[player.id] = &worldClient{id: player.id, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{npc.id: true}}
+ now := time.Now()
+ world.lastNPCUpdate = now
+ npc.motion.nextMove = now.Add(time.Hour)
+ return world, npc, now
+}
+
+func TestNPCOutdoorRoamingUsesNativeWaterContact(t *testing.T) {
+ world, npc, now := newNPCOutdoorSurfaceWorld(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))
+ }
+
+ 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} {
+ t.Fatal("roaming followed submerged terrain instead of the native water contact", npc.position, npc.movement)
+ }
+}
+
+func TestNPCOutdoorPursuitUsesNativeWaterContact(t *testing.T) {
+ world, npc, now := newNPCOutdoorSurfaceWorld(t)
+ npc.fighting = 1
+ npc.nextAttack = now.Add(time.Second)
+ deadline, health := npc.nextAttack, npc.health
+
+ for step := 1; step <= 20; step++ {
+ world.advanceNPCs(now.Add(time.Duration(step) * 250 * time.Millisecond))
+ }
+
+ if npc.position[0] < 132 || npc.position[1] < 13.4 || npc.position[1] > 13.6 || !npc.movement.deepWater || npc.movement.components[0] != 4 ||
+ npc.fighting != 1 || npc.nextAttack != deadline || npc.health != health {
+ t.Fatal("pursuit lost its native water contact or encounter state", npc.position, npc.movement, npc.fighting)
+ }
+}
+
+func TestNPCOutdoorReturnLeavesWaterAndRetainsHomeAfterColdLoad(t *testing.T) {
+ world, npc, now := newNPCOutdoorSurfaceWorld(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))
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ cold.geometry, cold.terrain = world.geometry, world.terrain
+ cold.lastNPCUpdate = now.Add(5 * time.Second)
+ returning := cold.characters[npc.id]
+ returning.motion.returning = true
+
+ for step := 21; step <= 80; step++ {
+ cold.advanceNPCs(now.Add(time.Duration(step) * 250 * time.Millisecond))
+ }
+
+ if returning.motion.returning || returning.motion.moving || returning.movement.deepWater || returning.movement.components[0] != 2 ||
+ math.Abs(float64(returning.position[0]-130)) >= 1 || returning.position[1] < 13.3 || returning.motion.home != [3]float32{130, 14, 98} || returning.health != 100 {
+ t.Fatal("cold return did not leave water at its retained home", returning.position, returning.motion, returning.movement)
+ }
+}
diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go
@@ -13,9 +13,6 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
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]
@@ -49,7 +46,7 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
changed = true
}
if len(npc.motion.route) == 0 {
- npc.walkIndoor(npc.position, seconds)
+ npc.walkSurface(npc.position, seconds)
server.stopNPCMotion_locked(npc, updates)
npc.motion.destination = destination
return true
@@ -57,7 +54,9 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
}
// Publish the starting pose before either side advances the new route.
- npc.running = true
+ if !npc.running && npc.movement.action(npc, 23) {
+ changed = true
+ }
if !npc.motion.moving {
npc.motion.destination = destination
npc.motion.moving = true
@@ -74,11 +73,11 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
}
changed = changed || len(npc.motion.route) != routeLength
if arrived && npc.movement.falling {
- npc.walkIndoor(npc.position, seconds)
+ npc.walkSurface(npc.position, seconds)
}
- // Preserve the authored outdoor ground offset after integrating motion.
- if ground := server.terrain[npc.playfield]; ground != nil {
+ // Preserve source offsets when physical scene geometry is unavailable.
+ if ground := server.terrain[npc.playfield]; ground != nil && !npc.geometry.physical(npc.playfield) {
home, available := ground.elevation(npc.motion.home[0], npc.motion.home[2])
if available {
height, inside := ground.elevation(npc.position[0], npc.position[2])
@@ -119,9 +118,10 @@ func (server *server) stopNPCMotion_locked(npc *character, updates map[*worldCli
return
}
npc.motion.moving = false
- npc.running = false
npc.movement.velocity = [3]float32{}
npc.movement.speed = 0
+ npc.movement.action(npc, 19)
+ npc.movement.action(npc, 22)
// Clear the waypoint controller, then restore walking for idle roaming.
server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc, npc.position), npcMovementPacket(npc, 22))
}
diff --git a/server/roaming.go b/server/roaming.go
@@ -58,6 +58,9 @@ func (server *server) advanceNPCs(now time.Time) {
if character.health == 0 || !zones[zone] && character.fighting == 0 && !character.motion.returning {
continue
}
+ if server.geometry.physical(character.playfield) {
+ character.geometry = server.geometry
+ }
if character.movementRestricted() {
server.stopNPCMotion_locked(character, clients)
continue
@@ -92,18 +95,18 @@ func (server *server) advanceNPCs(now time.Time) {
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.running = false
+ 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, _ := character.advanceNPCMotion(character.motion.destination, seconds)
+ arrived, blocked := character.advanceNPCMotion(character.motion.destination, seconds)
position := character.position
- // Follow changes in terrain height while preserving the authored ground offset.
- if ground := server.terrain[character.playfield]; ground != nil {
+ // 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])
@@ -116,7 +119,7 @@ func (server *server) advanceNPCs(now time.Time) {
}
}
character.position = position
- if arrived {
+ if arrived || blocked {
server.stopNPCMotion_locked(character, clients)
character.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
}
diff --git a/tools/client/test_npc_water.mjs b/tools/client/test_npc_water.mjs
@@ -0,0 +1,109 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium',
+ args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+const games = [], evidence = {samples: []};
+const state = async () => (await games[0].page.request.get(url+'/test-state')).json();
+const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id);
+let enemy;
+async function observe(label, predicate) {
+ const deadline = Date.now()+20000;
+ for (;;) {
+ await Promise.all(games.map(game => game.snapshot()));
+ const sample = {time: Date.now(), server: await state(), clients: games.map(game => {
+ const npc = actor(game, enemy);
+ return {position: npc.position, mode: npc.stats[173], health: npc.stats[27]};
+ })};
+ evidence.samples.push(sample);
+ assert(games.every(game => game.errors.length === 0));
+ if (predicate(sample)) return sample;
+ assert(Date.now() < deadline, 'Timed out waiting for '+label);
+ }
+}
+const matches = sample => sample.clients.every(client =>
+ Math.hypot(...client.position.map((value, axis) => value-sample.server.position[axis])) < .2 && client.mode === sample.server.mode);
+try {
+ for (let index = 0; index < 2; ++index) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'water-motion-'+index, url}]);
+ const page = await context.newPage(), game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ }
+ const [owner] = games;
+ evidence.initial = await state();
+ enemy = evidence.initial.enemy;
+ assert.equal(evidence.initial.health, 100);
+ assert.equal((await owner.page.request.post(url+'/test-roam')).status(), 204);
+ evidence.roaming = await observe('roaming water entry on both replicas', sample => sample.server.position[0] > 132 &&
+ sample.server.mode === 4 && sample.server.deepWater && matches(sample));
+ evidence.roamed = await observe('roaming stops at the native water contact', sample => !sample.server.moving && matches(sample));
+ assert(evidence.roamed.server.position[1] > 13.4);
+ assert.equal(evidence.roamed.server.health, 100);
+ await owner.save(output+'/roamed');
+
+ for (const game of games) {
+ await game.page.reload();
+ await game.ready();
+ await game.wait('water actor replay', () => !!actor(game, enemy));
+ }
+ evidence.replayed = await observe('water mode and contact survive both page reloads', sample =>
+ !sample.server.moving && sample.server.mode === 4 && matches(sample));
+ assert.equal(evidence.replayed.server.health, 100);
+
+ assert.equal((await owner.page.request.post(url+'/test-return')).status(), 204);
+ evidence.returned = await observe('return leaves water and stops near home', sample => !sample.server.returning &&
+ !sample.server.moving && !sample.server.deepWater && sample.server.mode === 2 && matches(sample));
+ assert.equal(evidence.returned.server.health, 100);
+ await owner.save(output+'/returned');
+
+ // Frame and select with real first-person mouse input before the melee approach.
+ if (!owner.state.camera.firstPerson) await owner.key('F8');
+ const cameraPoint = await owner.point(512, 300);
+ let mouseY = cameraPoint.y, sequence = owner.sequence;
+ await owner.page.mouse.move(cameraPoint.x, mouseY);
+ await owner.page.mouse.down({button: 'right'});
+ try {
+ await owner.waitInput(sequence, 1025);
+ const deadline = Date.now()+10000;
+ for (;;) {
+ await owner.snapshot();
+ const y = actor(owner, enemy).screenPosition[1];
+ if (y >= 350 && y <= 540) break;
+ assert(Date.now() < deadline, 'Camera did not frame the returned Leet');
+ mouseY += y > 540 ? 20 : -20;
+ await owner.page.mouse.move(cameraPoint.x, mouseY, {steps: 2});
+ }
+ } finally {
+ sequence = owner.sequence;
+ await owner.page.mouse.up({button: 'right'});
+ }
+ await owner.waitInput(sequence, 1026);
+ await owner.click(...await owner.pick(50000, enemy));
+ await owner.wait('native selection', snapshot => snapshot.selected[1] === enemy);
+ const returned = (await state()).position;
+ await owner.walk(returned[0]-.75, returned[2]);
+ await owner.key('KeyQ');
+ evidence.hit = await observe('ordinary melee damages the returned actor', sample => sample.server.health < 100);
+ await owner.key('KeyQ');
+ await owner.wait('ordinary attack stops', () => owner.local().combatTarget === 0);
+ await owner.walk(138, 98);
+ evidence.pursuit = await observe('ordinary pursuit enters water on both replicas', sample => sample.server.position[0] > 134 &&
+ sample.server.mode === 4 && sample.server.deepWater && sample.server.fighting === sample.server.owner && matches(sample));
+ assert(evidence.pursuit.server.ownerHealth > 0);
+ assert(evidence.pursuit.clients.every(client => client.health === evidence.pursuit.server.health));
+ console.log('PASS: native roaming, water stop, dry return, ordinary melee and living pursuit agree on both replicas');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output+'/verification.json', JSON.stringify(evidence, null, 2));
+ await Promise.all(games.map((game, index) => game.save(output+'/final-'+index)));
+ } finally { await browser.close(); }
+}