aorecomp

Anarchy Online classic in the browser

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


commit 835c700c68ef9f576c2cee6cb08411c9b7a173d7
parent 5457f9d65e25e460fceb2154e631efd8b631ad87
Author: anon <anon@example.com>
Date:   Mon,  2 Nov 2026 11:22:57 +0000

Match NPC steering and route timing to native prediction

Diffstat:
MTODO.md | 32+++++++++++++++++++++++++-------
Mdocs/mission-encounters.md | 21++++++++++++++-------
Mdocs/npc-pursuit.md | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mserver/interest.go | 2+-
Mserver/interest_test.go | 14+++++++++-----
Mserver/mission_encounters_test.go | 2+-
Mserver/nano_buffs.go | 2+-
Mserver/nano_casting.go | 2++
Mserver/nano_control_movement_test.go | 14++++++++++----
Aserver/npc_motion.go | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/npc_motion_test.go | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/npc_navigation.go | 11+++++++++++
Mserver/npc_navigation_test.go | 31++++++++++++++++++++++++-------
Mserver/npc_pursuit.go | 122+++++++++++++++++++++++++++++++------------------------------------------------
Mserver/npc_pursuit_test.go | 41++++++++++++++++++++++++++---------------
Mserver/npc_shared_pursuit_test.go | 32++++++++++++++++++++------------
Mserver/roaming.go | 25+++++++++----------------
Mserver/roaming_test.go | 19++++++++++++-------
18 files changed, 495 insertions(+), 163 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -26,6 +26,8 @@ has a priority; completed checkboxes retain their existing evidence. - P0: close and verify the normal-play progression loop. Fix crashes, lost items, duplication and unusable progression encountered on that path before expanding it. + Also fix problems that give new players a terrible first impression of the game, + including visibly broken movement or presentation, even when progression works. - P1: make that loop a substantial game: repeatable terminal missions, useful early content and upgrades, combat/healing, profession essentials and team rewards. - P2: expand catalog, world and subsystem coverage after those playable paths work. @@ -33,8 +35,9 @@ has a priority; completed checkboxes retain their existing evidence. polish that do not currently block normal play. Promote a lower-priority issue immediately when it demonstrably blocks the chosen -playable path or threatens durable player state. Keep research bounded to the -next feature's actual dependencies; do not finish an entire catalog or every +playable path, threatens durable player state or gives new players a terrible +first impression. Keep research bounded to the next feature's actual dependencies; +do not finish an entire catalog or every movement edge case before shipping a useful, tested slice. Historical accuracy remains the target: label provisional rules and reject unsupported item contracts as a whole rather than silently granting partial effects. @@ -980,6 +983,19 @@ for exact records, protocol, tests and remaining reconstruction assumptions. Historical outdoor give-up rules, obstruction handling and species balance remain open; these checks do not establish canonical boss difficulty. See [NPC pursuit](docs/npc-pursuit.md). +- [x] [P0] Fix visibly uneven NPC movement. NPCs previously appeared to walk slowly, + then suddenly jump several meters when they stop. Reported examples are the + Wardroid and Organic Waste Collector in Omni Trade District. Reproduce these + cases and check movement speed, native prediction and authoritative poses + across starts, turns and stops. Check: roaming, pursuit and return movement + stay smooth at the intended speed, without a final position jump, on two WASM + clients and after reconnect. Add a focused regression for the recovered cause + and recheck the previously verified movement paths. Shared native steering, + route reconciliation, visible indoor shortcuts and retained floor-tangent + velocity now pass these checks. Two-client roaming, pursuit, indoor return + and reconnect captures have maximum stopped-pose errors below .16 metres, + with no metre-scale corrections. The full server suite, focused race checks + and vet pass. See [movement verification](docs/npc-pursuit.md#npc-starts-turns-and-stops). - [x] Keep admitted NPCs engaged while outside weapon range. Check fixed/roaming profiles at both Leet levels and the Salamander Boss, retained swing deadlines, no distant damage or repeated Attack/Stop traffic, valid-range resumption and @@ -1433,7 +1449,7 @@ introduction and starting-item gameplay remain open below. endpoint pairs. Keep unsupported effects explicit rather than granting partial bonuses silently. Audit the older Pre-Universe container action-8 fallback against the native action-6 gate. See [clothing](docs/clothing.md). -- [ ] [P2] Audit complete Omni-Med outfit appearance in the WASM client. The +- [ ] [P0] Fix shared green skin/outfit appearance in the WASM client. The purchase/wear run has correct slots and bonuses, but green arm/leg regions remain visible alongside white torso/boots. Check original texture categories, bare skin, both sleeve instances and skirt/trousers on owner and observer, @@ -1448,6 +1464,9 @@ introduction and starting-item gameplay remain open below. observer and cold captures in the shared investigation. Compare the owner's visible helmet with the observer's apparently uncovered head as well; see [Leather verification](docs/leather-armor.md#verification-scope). + The retained earned Enforcer also shows bright green arm/leg regions in + `local/earned-ninth-boundary/native-20261102-024758/initial/0/screen.png`. + This is a first-impression presentation defect under the P0 policy above. - [ ] [P1] Reconstruct the original Arrival Hall and training-ground introduction. Check all three factions' entry/exit flow, authored tutorial NPC identities, dialogues, starter instructions and camera state. Replace training NPC @@ -2169,10 +2188,9 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). 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. + Shared steering now rechecks the original indoor detour on two WASM clients, + including slope, turn, stop and reconnect, without the earlier metre-scale + correction. See [steering verification](docs/npc-pursuit.md#npc-starts-turns-and-stops). 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. diff --git a/docs/mission-encounters.md b/docs/mission-encounters.md @@ -41,8 +41,11 @@ Mission pursuit and return now share a bounded half-metre route search. Each candidate walks a copy of the actor through the same 60 Hz 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 +arrival above the destination floor. A shortcut must also have a clear segment +at .11 or 1.2 metres above its endpoints. This conservative routing policy keeps +occluded shortcuts out of the native follower, whose short visibility probes can +discard them even when a physical body eventually slides around the obstruction. +Search state distinguishes horizontal cells and floor height; a query considers at most 4096 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. @@ -51,8 +54,9 @@ 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 most 29 remaining points. New observers use -the same remaining route. Indoor close approach also requires a walkable final +carry at most 29 remaining points. Initial routes and new observers carry the +current position; ongoing route changes use the original zero-reconcile form +to preserve native prediction. Indoor close approach also requires a walkable final segment; exact native arrival/visibility parity remains unverified. Original KKR `FUN_10048430`, maintained as @@ -70,7 +74,8 @@ Evidence and exact addresses are retained in 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 +room geometry, returning within the native one-metre waypoint radius of home. +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, spawn-before-route replay for a late observer, death during @@ -86,8 +91,10 @@ updates are retained under `local/indoor-routing/`. There were no page exception The native final x=12.375 differs from server x=12.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`. +timing were not established by that endpoint check. The subsequent +[steering and stop checks](npc-pursuit.md#npc-starts-turns-and-stops) recheck the +same obstruction on two clients with shared force integration and visible +route segments. 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 character 5's complete character/player rows, eight item diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md @@ -8,7 +8,7 @@ continuing its approach until the target is within two metres. A dead, disconnected, loading or different-playfield target is replaced through the shared threat selector when another eligible participant remains. Otherwise -the living NPC runs back to its retained spawn position. An explicit idle-roaming +the living NPC runs back toward its retained spawn position. An explicit idle-roaming flag then selects wandering or remaining at that fixed post. 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 @@ -27,7 +27,7 @@ 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 this server's fixed RunSpeed 100 and run mode, represented on the -server as 4.5 metres/second. Selecting that default for admitted pursuit and return +server as a 4.5 metres/second speed cap. Selecting that default for admitted pursuit and return 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 @@ -36,7 +36,11 @@ 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 [indoor navigation](mission-encounters.md#indoor-navigation). -Each scheduler step remains capped at 0.25 seconds. +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 +accelerate through the shared vehicle integrator rather than moving instantly +at that cap. This substep cadence is server reconstruction policy, not a recovered +original-server scheduling frequency. 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 @@ -75,7 +79,11 @@ 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 and current position. +The server sends self as the route's target identity. New routes and observer +replays carry the current position. Ongoing route changes carry a zero reconcile +position: the original receiver skips relocation for that value while still +updating the route. Sending the current position on each target change repeatedly +teleported native prediction to the server pose. Straight routes contain two points: current position and destination. Indoor detours contain current position followed by up to 29 remaining waypoints; turns refresh that remaining route. Pursuit and return use run @@ -84,8 +92,22 @@ 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. +The native waypoint consumer discards points within one horizontal metre. The +server uses the same radius rather than forcing the exact endpoint after the +client has already stopped. Return therefore finishes near the retained home, +on the actual floor at that point. Pursuit checks its two-metre clear-approach +threshold after integrating the current interval, so its stop publishes the +current pose. A new pursuit publishes its initial route before advancing. + +Original `qqr.dll` SHA-256 +`c011e411b9cecfbde03c4b37fc988540a1246fafc9921c7cab7cb9ef2bb8d913` +supplies `Vehicle_t::SteeringDirArrive` at `0x10015fe0` and +`Vehicle_t::SteeringArrive` at `0x10015e90`. The latter scales velocity error by +four times body mass before the common force/speed caps and integration. The +server reuses its existing vehicle integrator for that force. Root application +and route cancellation clear its retained velocity as well as the moving flag; +a failed root transaction leaves both live values intact. Full procedure and +assembly records are retained under `local/npc-stop-jump/`. 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 @@ -180,3 +202,53 @@ 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. + +## NPC starts, turns and stops + +The Trade Wardroid and Organic Waste Collector reproduction exposed endpoint +corrections from advancing the server at constant speed to the exact goal while +native prediction accelerates and discards nearby waypoints. Pursuit also +published an already-advanced starting pose, relocated prediction on target +changes and stopped using the preceding tick's pose. Shared steering, the +original arrival radius and the route contract above address those causes. + +The original indoor side-passage reproducer exposed two further discrepancies. +Routing shortcuts must remain visible to the native follower, and integrated +velocity must retain its floor-tangent component for the next force/speed cap. +Otherwise the server pulls ahead over the tongue mesh. The collision substep +keeps its double-precision duration: converting a rounded float back to double +can incorrectly subdivide one 60Hz step into two collision passes and stall a +low-health return at an edge. The existing rejected-death regression catches +that case with its original time bound. + +Hardware-rendered WASM checks use the maintained game harness, ordinary native +inputs, read-only C snapshots and authoritative server poses. Two controlled +Trade observers watch the four original Wardroid/collector placements through +at least three stops each before and after page reconnect. A separate ordinary +Leet encounter exercises approach, retreat, stop and return after reconnect. +The indoor check repeats the original obstructed route with two observers, +then verifies both reconnects. That controlled navigation fixture temporarily +roots the returning NPC to permit observation; it does not establish earned +progress, encounter balance or an authored root duration. + +Raw packet streams, frame timestamps, screenshots, source/client hashes and +assertion results are retained under `local/npc-stop-jump/`. Browser request +completion time is not a reliable short-interval movement clock; pursuit and +indoor measurements timestamp the native snapshot callback itself. Vertical +falling is evaluated separately from the horizontal running cap. The original +compact movement packet's position quantization remains visible in final poses. +The final-source Trade run records 133 samples and 50 observed stops, with each +actor stopping at least three times per client before and after reconnect; +maximum final pose error is .159 metres. The pursuit run records 86 frames/77 +steps with .126-metre stopped pose errors. The indoor run records 386 samples, +including both delivered stop poses and both reconnects, with .092-metre maximum +stopped pose error. All three runs have no browser exceptions. The largest +measured movement beyond the applicable speed cap is below .023 metres; +callback timestamps are used for pursuit/indoor intervals. +The final `go test ./server/...` run passes 1,753 top-level tests and 17,112 +individual test results, with four explicit skips, in 2,098.68 seconds for the +server package. The focused race run passes 169 top-level tests/502 results in +200.859 seconds, including the original-time-bound low-health return. Vet passes. +Source and published client hashes match the native fixtures and these checks. +Broader layouts, strong-slow/body combinations, species speeds and original +server leash/navigation policy remain separate fidelity work. diff --git a/server/interest.go b/server/interest.go @@ -52,7 +52,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim } } if other.motion != nil && other.motion.moving { - updates = append(updates, npcRoutePacket(other)) + updates = append(updates, npcRoutePacket(other, other.position)) } } if client.ready && len(spawned) != 0 { diff --git a/server/interest_test.go b/server/interest_test.go @@ -143,11 +143,15 @@ func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) { npc.motion.moving = true npc.motion.nextMove = now npc.motion.destination = npc.position - npc.motion.destination[0] -= 1 + npc.motion.destination[0] -= 3 } done := make(chan struct{}) - go func() { world.advanceNPCs(now.Add(250 * time.Millisecond)); close(done) }() + go func() { + world.advanceNPCs(now.Add(250 * time.Millisecond)) + world.advanceNPCs(now.Add(500 * time.Millisecond)) + close(done) + }() spawn, err := readPacket(client) if err != nil { t.Fatal(err) @@ -157,15 +161,15 @@ func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) { t.Fatal(err) } <-done - world.advanceNPCs(now.Add(500 * time.Millisecond)) + world.advanceNPCs(now.Add(750 * time.Millisecond)) if binary.BigEndian.Uint32(spawn[20:]) != 0x271b3a6b || binary.BigEndian.Uint32(spawn[28:]) != 1000000 { t.Fatalf("entering NPC spawn: %x", spawn) } - if binary.BigEndian.Uint32(motion[20:]) != 0x260f3671 || binary.BigEndian.Uint32(motion[28:]) != 1000000 || motion[48] != 22 || math.Float32frombits(binary.BigEndian.Uint32(motion[49:])) != 1549.875 { + if binary.BigEndian.Uint32(motion[20:]) != 0x260f3671 || binary.BigEndian.Uint32(motion[28:]) != 1000000 || motion[48] != 22 || math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(motion[49:]))-1549.887)) > .001 { t.Fatalf("entering NPC motion: %x", motion) } - if world.characters[1000001].position[0] != 1999.25 { + if world.characters[1000001].position[0] >= 1999.5 || world.characters[1000001].position[0] <= 1999 { t.Fatal("unobserved NPC stopped roaming on the server") } } diff --git a/server/mission_encounters_test.go b/server/mission_encounters_test.go @@ -201,7 +201,7 @@ func TestMissionEncounterPursuitCrossesPortalAndReturnsWithoutDatabaseChurn(t *t } if far[2] < 41 || far[2] > 43 || math.Abs(float64(far[1]-.011)) > .02 || npc.fighting != 0 || npc.motion.moving || npc.motion.returning || - surfaceDistanceSquared(npc.position, npc.motion.home) >= .01 || storedZ != npc.motion.home[2] { + math.Hypot(float64(npc.position[0]-npc.motion.home[0]), float64(npc.position[2]-npc.motion.home[2])) >= 1 || storedZ != npc.motion.home[2] { t.Fatal("indoor pursuit escaped its floor, failed to return or persisted each tick", far, npc.position, npc.motion, storedZ) } }) diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -387,7 +387,7 @@ func (server *server) removeNano_locked(player *character, index int, now time.T func (server *server) finishResourceChange_locked(updates map[*worldClient][][]byte, player *character, previous character, now time.Time) { if player.npc { if previous.motion != nil && previous.motion.moving && !player.motion.moving { - server.queueCombat_locked(updates, player, player, npcRoutePacket(player), npcMovementPacket(player, 22)) + server.queueCombat_locked(updates, player, player, npcRoutePacket(player, player.position), npcMovementPacket(player, 22)) } return } diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -308,6 +308,8 @@ func (server *server) advanceNanos(now time.Time) { motion := *victim.motion motion.moving = false victim.motion, victim.running = &motion, false + victim.movement.velocity = [3]float32{} + victim.movement.speed = 0 } victim.updateMovementPermission(target, now) diff --git a/server/nano_control_movement_test.go b/server/nano_control_movement_test.go @@ -33,6 +33,8 @@ func TestControlRootStopsRoamingPursuitAndReturnUntilExpiry(t *testing.T) { t.Run(mode, func(t *testing.T) { world, _ := newControlPursuitWorld(t) target := world.characters[1000000] + target.movement.velocity = [3]float32{4.5, 0, 0} + target.movement.speed = 4.5 at := castTestBuff(t, world, 1, target.id, 42110) world.lastNPCUpdate = at if mode != "pursuit" { @@ -51,7 +53,7 @@ func TestControlRootStopsRoamingPursuitAndReturnUntilExpiry(t *testing.T) { world.advanceNPCs(at.Add(time.Duration(tick) * 250 * time.Millisecond)) } - if target.position != before || target.motion.moving || !target.movementRestricted() { + if target.position != before || target.motion.moving || !target.movementRestricted() || target.movement.velocity != [3]float32{} || target.movement.speed != 0 { t.Fatal("root moved in simulation", mode, target.position, target.motion) } deadline := target.activeNanos[0].expiresAt @@ -70,7 +72,7 @@ func TestControlSnareUsesSignedRunningSpeedAndLeavesWalkingUnchanged(t *testing. for _, scenario := range []struct { program, profession uint32 position float64 - }{{82518, 4, 2}, {82528, 8, 2.05}, {82463, 8, 1.025}} { + }{{82518, 4, 1.2666667}, {82528, 8, 1.28}, {82463, 8, 1.0066667}} { for _, returning := range []bool{false, true} { t.Run(fmt.Sprintf("%d/return=%t", scenario.program, returning), func(t *testing.T) { world, _ := newControlPursuitWorld(t) @@ -96,6 +98,7 @@ func TestControlSnareUsesSignedRunningSpeedAndLeavesWalkingUnchanged(t *testing. delete(world.fighting, target.id) target.motion.returning = false target.running = false + target.movement.velocity = [3]float32{1.5, 0, 0} target.motion.destination = [3]float32{21, 0, 0} target.motion.nextMove = at before := target.position[0] @@ -131,6 +134,8 @@ func TestFailedRootCastCannotLeakStoppedMovementThroughSharedState(t *testing.T) t.Run(failure.name, func(t *testing.T) { world, _ := newControlPursuitWorld(t) player, target, client := world.characters[1], world.characters[1000000], world.clients[1] + target.movement.velocity = [3]float32{4.5, 0, 0} + target.movement.speed = 4.5 before := player.nano if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 42110})[20:]); err != nil { t.Fatal(err) @@ -142,7 +147,7 @@ func TestFailedRootCastCannotLeakStoppedMovementThroughSharedState(t *testing.T) world.advanceNanos(deadline) - if !target.motion.moving || !target.running || target.movementRestricted() || len(target.activeNanos) != 0 || len(target.threat) != 0 || player.nano != before || client.nanoCast != nil { + if !target.motion.moving || !target.running || target.movementRestricted() || len(target.activeNanos) != 0 || len(target.threat) != 0 || player.nano != before || client.nanoCast != nil || target.movement.velocity != [3]float32{4.5, 0, 0} || target.movement.speed != 4.5 { t.Fatal("failed root mutated live movement, taunt, effect or cost", target.motion, target.activeNanos, target.threat, player.nano, before) } if _, err := world.db.Exec("DROP TRIGGER fail_root"); err != nil { @@ -150,7 +155,7 @@ func TestFailedRootCastCannotLeakStoppedMovementThroughSharedState(t *testing.T) } castTestBuff(t, world, 1, target.id, 42110) cold := newTestInventoryServer(t).characters[target.id] - if !target.movementRestricted() || !cold.movementRestricted() || target.motion.moving || cold.motion.moving || player.nano != before-17 || target.threat[1] != 13 { + if !target.movementRestricted() || !cold.movementRestricted() || target.motion.moving || cold.motion.moving || player.nano != before-17 || target.threat[1] != 13 || target.movement.velocity != [3]float32{} || target.movement.speed != 0 { t.Fatal("retried root was not committed exactly once", target.activeNanos, target.threat, player.nano) } }) @@ -185,6 +190,7 @@ func TestFailedRootExpiryKeepsAuthoritativeMovementBlockedUntilRemovalCommits(t } world.advanceNanos(deadline.Add(500 * time.Millisecond)) world.advanceNPCs(deadline.Add(750 * time.Millisecond)) + world.advanceNPCs(deadline.Add(time.Second)) if target.movementRestricted() || target.position == before || !target.motion.moving { t.Fatal("successful retry did not resume pursuit", target.position, target.activeNanos) } diff --git a/server/npc_motion.go b/server/npc_motion.go @@ -0,0 +1,79 @@ +package main + +import "math" + +func (npc *character) pursuitArrived(destination [3]float32) bool { + // client/game/kkr.dll/lifted-0023.c / sub_36048430 checks range and clear approach. + if npc.movement.falling || surfaceDistanceSquared(npc.position, destination) >= 4 { + return false + } + if npc.geometry == nil || npc.geometry.mission(npc.playfield) == nil { + return true + } + arrived, clear := indoorWalk(*npc, destination) + return clear && surfaceDistanceSquared(arrived.position, destination) < .01 +} + +func (npc *character) advanceNPCMotion(destination [3]float32, seconds float64) (arrived, blocked bool) { + // client/game/kkr.dll/lifted-0023.c / sub_36048430 discards nearby waypoints. + // client/game/qqr.dll/lifted-0007.c / sub_42015E90 supplies the arrival force. + 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 + for range frames { + 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 { + break + } + npc.motion.route = npc.motion.route[1:] + if len(npc.motion.route) == 0 { + return true, false + } + } + if len(npc.motion.route) != 0 { + destination = npc.motion.route[0] + } + delta := [3]float32{destination[0] - npc.position[0], destination[1] - npc.position[1], destination[2] - npc.position[2]} + if delta[0]*delta[0]+delta[2]*delta[2] < 1 { + return true, false + } + + // Integrate the native acceleration instead of marching at the speed cap. + distance := vectorLength(delta) + force := [3]float32{} + for axis := range force { + force[axis] = 4 * bodyMass * (delta[axis]/distance*min(speed, 4*distance) - npc.movement.velocity[axis]) + } + 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 { + 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 + for axis := range position { + position[axis] += npc.movement.velocity[axis] * step + } + npc.movement.previousPosition = npc.position + if indoor { + npc.walkIndoor(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 + } + } else { + npc.position = position + } + if npc.movement.velocity[0] != 0 || npc.movement.velocity[2] != 0 { + angle := math.Atan2(float64(npc.movement.velocity[0]), float64(npc.movement.velocity[2])) + npc.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))} + } + } + return false, false +} diff --git a/server/npc_motion_test.go b/server/npc_motion_test.go @@ -0,0 +1,125 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "math" + "testing" + "time" +) + +func TestNPCRoamingMatchesNativeAccelerationAndWaypointArrival(t *testing.T) { + for _, scenario := range []struct { + name string + destination float32 + position float32 + moving bool + }{ + {"accelerating", 11, 1.1, true}, + {"near waypoint", 1.125, 1, false}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, _, start := newNPCPursuitWorld(t) + world.characters[1000000].fighting = 0 + world.characters[1000000].motion.destination = [3]float32{scenario.destination, 0, 0} + world.characters[1000000].motion.moving = true + world.characters[1000000].motion.nextMove = start + + world.advanceNPCs(start.Add(250 * time.Millisecond)) + + if math.Abs(float64(world.characters[1000000].position[0]-scenario.position)) > .0001 || world.characters[1000000].motion.moving != scenario.moving { + t.Fatalf("native acceleration/arrival: position=%v moving=%t", world.characters[1000000].position, world.characters[1000000].motion.moving) + } + }) + } +} + +func TestNPCPursuitStartsItsRouteBeforeAdvancing(t *testing.T) { + world, conn, start := newNPCPursuitWorld(t) + + world.advanceNPCs(start.Add(250 * time.Millisecond)) + + if world.characters[1000000].position != [3]float32{1, 0, 0} || !world.characters[1000000].motion.moving { + t.Fatalf("pursuit started with a position jump: %v", world.characters[1000000].position) + } + if len(conn.packets) != 1 || math.Float32frombits(binary.BigEndian.Uint32(conn.packets[0][42:46])) != 1 { + t.Fatalf("route does not begin at the published position: %x", conn.packets) + } +} + +func TestNPCPursuitStopsAfterAdvancingTheCurrentInterval(t *testing.T) { + world, conn, start := newNPCPursuitWorld(t) + world.characters[1].position = [3]float32{3.5, 0, 0} + world.characters[1000000].motion.destination = [3]float32{3.5, 0, 0} + world.characters[1000000].motion.moving = true + world.characters[1000000].running = true + world.characters[1000000].movement.velocity = [3]float32{4.5, 0, 0} + + world.advanceNPCs(start.Add(250 * time.Millisecond)) + + if math.Abs(float64(world.characters[1000000].position[0]-2.125)) > .0001 || world.characters[1000000].motion.moving || world.characters[1000000].fighting != 1 { + t.Fatalf("pursuit arrival was deferred to an outdated pose: position=%v moving=%t fighting=%d", world.characters[1000000].position, world.characters[1000000].motion.moving, world.characters[1000000].fighting) + } + if len(conn.packets) != 2 || math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(conn.packets[0][42:46]))-2.125)) > .0001 { + t.Fatalf("stop did not publish the current pose: %x", conn.packets) + } +} + +func TestNPCPursuitRouteChangesPreserveNativePosition(t *testing.T) { + world, conn, start := newNPCPursuitWorld(t) + world.advanceNPCs(start.Add(250 * time.Millisecond)) + world.characters[1].position = [3]float32{21, 0, 1} + + world.advanceNPCs(start.Add(500 * time.Millisecond)) + + if len(conn.packets) != 2 || !bytes.Equal(conn.packets[1][42:54], make([]byte, 12)) { + t.Fatalf("changing direction relocated the native actor: %x", conn.packets) + } + if math.Float32frombits(binary.BigEndian.Uint32(conn.packets[1][70:74])) != 21 || math.Float32frombits(binary.BigEndian.Uint32(conn.packets[1][78:82])) != 1 { + t.Fatalf("route lost the new target position: %x", conn.packets[1]) + } +} + +func TestNPCMotionStopsBeforeLeavingTheTerrainGrid(t *testing.T) { + for _, pursuing := range []bool{false, true} { + t.Run(fmt.Sprintf("pursuing=%t", pursuing), func(t *testing.T) { + world, _, start := newNPCPursuitWorld(t) + npc := world.characters[1000000] + world.terrain = map[uint32]*terrain{950: {width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 1, scale: 1, heights: make([]byte, 9)}} + npc.position = [3]float32{1.95, 0, 0} + npc.motion.destination = [3]float32{4, 0, 0} + npc.motion.moving = true + npc.motion.nextMove = start + npc.running = pursuing + npc.movement.velocity = [3]float32{4.5, 0, 0} + if !pursuing { + npc.fighting = 0 + } + + world.advanceNPCs(start.Add(250 * time.Millisecond)) + + if npc.position != [3]float32{1.95, 0, 0} || npc.motion.moving || npc.movement.velocity != [3]float32{} { + t.Fatal("movement left the terrain grid", npc.position, npc.motion) + } + }) + } +} + +func TestNPCMotionRetainsItsGroundTangentVelocity(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 + + for tick := 1; tick <= 7; tick++ { + world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond)) + } + + if math.Abs(float64(npc.movement.velocity[1])) <= 1 || npc.movement.velocity[2] >= 4.3 { + t.Fatal("climbing lost its vertical velocity before the next speed-cap calculation", npc.position, npc.movement.velocity) + } +} diff --git a/server/npc_navigation.go b/server/npc_navigation.go @@ -28,6 +28,17 @@ func (npc *character) walkIndoor(position [3]float32, seconds float64) { } func indoorWalk(npc character, destination [3]float32) (character, bool) { + // Keep routing shortcuts visible above the floor as well as physically walkable. + origin, end := npc.position, destination + origin[1] += .11 + end[1] += .11 + if !npc.geometry.lineOfSight(npc.playfield, origin, end) { + origin[1] = npc.position[1] + 1.2 + end[1] = destination[1] + 1.2 + if !npc.geometry.lineOfSight(npc.playfield, origin, end) { + return npc, false + } + } 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. diff --git a/server/npc_navigation_test.go b/server/npc_navigation_test.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/binary" "fmt" + "math" "slices" "testing" "time" @@ -44,7 +45,7 @@ func TestMissionNPCWalksAroundTheTongueAfterDescending(t *testing.T) { 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) { + if returning && (npc.motion.returning || npc.motion.moving || math.Hypot(float64(npc.position[0]-npc.motion.home[0]), float64(npc.position[2]-npc.motion.home[2])) >= 1) { t.Fatal("obstacle route did not finish the return home", npc.position, npc.motion) } }) @@ -81,14 +82,30 @@ func TestMissionNPCDetoursIntoTheSidePassage(t *testing.T) { 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) + if returning && (npc.motion.returning || npc.motion.moving || math.Hypot(float64(npc.position[0]-npc.motion.home[0]), float64(npc.position[2]-npc.motion.home[2])) >= 1) { + t.Fatal("detour did not reach the retained home's native arrival radius", npc.position, npc.motion) } }) } } } +func TestMissionNPCDetourDoesNotCutAcrossTheSidePassageWall(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) < 2 || npc.motion.route[0][0] < 15 { + t.Fatal("detour requires sliding along the passage wall", npc.motion.route) + } +} + func TestMissionNPCRouteFollowsAChangingTarget(t *testing.T) { world, _, _ := enteredMissionEncounterWorld(t) player, npc := world.characters[1], world.characters[2000003] @@ -213,7 +230,7 @@ func TestMissionNPCColdLoadReplansTheReturnWithoutObservers(t *testing.T) { } 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 { + math.Hypot(float64(restored.position[0]-restored.motion.home[0]), float64(restored.position[2]-restored.motion.home[2])) >= 1 || restored.health != npc.health || restored.fighting != 0 { t.Fatal("cold return restored transient waypoints, lost its home or healed", restored.position, restored.motion) } } @@ -247,7 +264,7 @@ func TestMissionNPCNewObserverReceivesTheRemainingDetourAfterSpawn(t *testing.T) } } if !slices.Equal(keys, []uint32{0x271b3a6b, 0x1d3c0f1c, 0x260f3671, 0x28494070}) || - binary.BigEndian.Uint32(route[54:58]) != 3 || len(npc.motion.route) != 2 { + binary.BigEndian.Uint32(route[54:58]) != 5 || len(npc.motion.route) != 4 { t.Fatal("new observer received a stale straight route or incorrect spawn order", keys, len(npc.motion.route)) } } @@ -309,8 +326,8 @@ func TestMissionNPCFailedDeathCancelsItsDetourAndReturnsAlive(t *testing.T) { } if !cancelled || npc.health != 1 || npc.corpse != nil || npc.motion.moving || npc.motion.returning || - len(npc.motion.route) != 0 || surfaceDistanceSquared(npc.position, npc.motion.home) >= .01 { - t.Fatal("failed death did not cancel the old detour and return a living NPC", npc.health, npc.position, npc.motion) + len(npc.motion.route) != 0 || math.Hypot(float64(npc.position[0]-npc.motion.home[0]), float64(npc.position[2]-npc.motion.home[2])) >= 1 { + t.Fatal("failed death did not cancel the old detour and return a living NPC", npc.health, npc.position, npc.motion, npc.movement.velocity, npc.movement.normal, npc.movement.falling) } for _, packet := range output.packets { if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[24:28]) == npc.id && binary.BigEndian.Uint32(packet[29:33]) == 99 { diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go @@ -26,46 +26,13 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se } if npc.fighting != 0 { destination = predictedPosition_locked(target, 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 && !npc.movement.falling { - 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 - } - } - } - } - - // Running uses the same signed RunSpeed scalar as the native actor. - x, z := float64(destination[0]-npc.position[0]), float64(destination[2]-npc.position[2]) - distance := math.Hypot(x, z) - step := float64(npc.runningMovementSpeed(false)) * 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 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 { - height, inside := ground.elevation(position[0], position[2]) - if !inside { + if !npc.motion.moving && npc.pursuitArrived(destination) { server.stopNPCMotion_locked(npc, updates) return true } - position[1] = npc.motion.home[1] + height - home } } + changed := !npc.motion.moving || npc.motion.destination != destination if indoor { replan := len(npc.motion.route) == 0 && !now.Before(npc.motion.routeRetry) @@ -87,46 +54,51 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se 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 - } - 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 - } - 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 + } + + // Publish the starting pose before either side advances the new route. + npc.running = true + if !npc.motion.moving { + npc.motion.destination = destination + npc.motion.moving = true + server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc, npc.position)) + return true + } + routeLength := len(npc.motion.route) + previous := npc.position + arrived, blocked := npc.advanceNPCMotion(destination, seconds) + if blocked { + server.stopNPCMotion_locked(npc, updates) + npc.motion.routeRetry = now.Add(time.Second) + return true + } + changed = changed || len(npc.motion.route) != routeLength + if arrived && npc.movement.falling { + npc.walkIndoor(npc.position, seconds) + } + + // Preserve the authored outdoor ground offset after integrating motion. + if ground := server.terrain[npc.playfield]; ground != nil { + home, available := ground.elevation(npc.motion.home[0], npc.motion.home[2]) + if available { + height, inside := ground.elevation(npc.position[0], npc.position[2]) + if !inside { + npc.position = previous + server.stopNPCMotion_locked(npc, updates) + return true } + npc.position[1] = npc.motion.home[1] + height - home } - } else { - 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))} + + // A moving actor's stop uses the pose at this tick, after integrating its interval. + if npc.fighting != 0 && npc.pursuitArrived(destination) { + server.stopNPCMotion_locked(npc, updates) + return true } // Complete the return before allowing another idle roaming destination. - if npc.fighting == 0 && !npc.movement.falling && surfaceDistanceSquared(npc.position, destination) < .01 { + if npc.fighting == 0 && !npc.movement.falling && arrived { server.stopNPCMotion_locked(npc, updates) npc.motion.returning = false npc.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second) @@ -134,9 +106,9 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se } npc.motion.destination = destination npc.motion.moving = true - npc.running = true if changed { - server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc)) + // A zero reconcile position changes the route without relocating the actor. + server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc, [3]float32{})) } return true } @@ -148,11 +120,13 @@ func (server *server) stopNPCMotion_locked(npc *character, updates map[*worldCli } npc.motion.moving = false npc.running = false + npc.movement.velocity = [3]float32{} + npc.movement.speed = 0 // Clear the waypoint controller, then restore walking for idle roaming. - server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc), npcMovementPacket(npc, 22)) + server.queueCombat_locked(updates, npc, npc, npcRoutePacket(npc, npc.position), npcMovementPacket(npc, 22)) } -func npcRoutePacket(npc *character) []byte { +func npcRoutePacket(npc *character, reconcilePosition [3]float32) []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.motion.moving { @@ -169,7 +143,7 @@ func npcRoutePacket(npc *character) []byte { body = binary.BigEndian.AppendUint32(body, value) } body = append(body, control) - for _, value := range npc.position { + for _, value := range reconcilePosition { body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) } body = binary.BigEndian.AppendUint32(body, count) diff --git a/server/npc_pursuit_test.go b/server/npc_pursuit_test.go @@ -35,16 +35,21 @@ func TestNPCPursuitRetainsAttackDeadlineAndOnlyHitsInsideRange(t *testing.T) { 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} { + if world.characters[1].health != 100 || world.characters[1000000].nextAttack != deadline || world.characters[1000000].fighting != 1 || world.characters[1000000].position[0] <= 1 || world.characters[1000000].position[0] >= 10 { 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++ { + tick := 9 + for ; tick <= 40 && world.characters[1].health == 100; tick++ { + now := start.Add(time.Duration(tick) * 250 * time.Millisecond) + world.advanceNPCs(now) + world.advanceCombat(now) + } + deadline = world.characters[1000000].nextAttack + for ; tick <= 50; 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].motion.moving || world.characters[1000000].running || world.characters[1000000].fighting != 1 || world.characters[1000000].nextAttack != start.Add(5750*time.Millisecond) { + if world.characters[1].health < 92 || world.characters[1].health > 96 || world.characters[1000000].position[0] <= 19 || world.characters[1000000].position[0] >= 21 || world.characters[1000000].motion.moving || world.characters[1000000].running || world.characters[1000000].fighting != 1 || world.characters[1000000].nextAttack != deadline { t.Fatalf("arrival did not resume normal combat: player=%+v npc=%+v", world.characters[1], world.characters[1000000]) } } @@ -57,7 +62,7 @@ func TestNPCPursuitPublishesNativeWaypointRouteToBothObservers(t *testing.T) { 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 { + 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])) != 1 || math.Float32frombits(binary.BigEndian.Uint32(first.packets[0][70:74])) != 21 { t.Fatalf("native route or recipients: %x %x", first.packets, second.packets) } } @@ -70,7 +75,7 @@ func TestNPCPursuitChangesDirectionForMovingTargetWithoutRestartingAttack(t *tes 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].motion.destination != [3]float32{2.125, 0, 20} { + if world.characters[1000000].position[0] <= 1 || world.characters[1000000].position[0] >= 1.05 || world.characters[1000000].position[2] <= 0 || world.characters[1000000].position[2] >= .5 || world.characters[1000000].nextAttack != deadline || len(conn.packets) != 2 || world.characters[1000000].motion.destination != [3]float32{2.125, 0, 20} { t.Fatalf("target direction was not refreshed: %+v packets=%x", world.characters[1000000], conn.packets) } } @@ -79,9 +84,11 @@ func TestNPCPursuitReturnsHomeAfterTargetLossWithoutHealingOrTeleporting(t *test for _, scenario := range []string{"disconnect", "loading", "death", "zone"} { t.Run(scenario, func(t *testing.T) { world, conn, start := newNPCPursuitWorld(t) - world.advanceNPCs(start.Add(250 * time.Millisecond)) - world.advanceNPCs(start.Add(500 * time.Millisecond)) + for tick := 1; tick <= 4; tick++ { + world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond)) + } world.characters[1000000].health = 50 + position := world.characters[1000000].position switch scenario { case "disconnect": delete(world.clients, 1) @@ -94,14 +101,18 @@ func TestNPCPursuitReturnsHomeAfterTargetLossWithoutHealingOrTeleporting(t *test } conn.packets = nil - world.advanceNPCs(start.Add(750 * time.Millisecond)) - if world.characters[1000000].position != [3]float32{2.125, 0, 0} || !world.characters[1000000].motion.returning || world.characters[1000000].fighting != 0 || world.characters[1000000].health != 50 { + world.advanceNPCs(start.Add(1250 * time.Millisecond)) + if math.Abs(float64(world.characters[1000000].position[0]-position[0])) > 1.125 || !world.characters[1000000].motion.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)) + finished := start.Add(1250 * time.Millisecond) + for tick := 6; tick <= 40 && world.characters[1000000].motion.returning; tick++ { + finished = start.Add(time.Duration(tick) * 250 * time.Millisecond) + world.advanceNPCs(finished) + } + world.advanceRegeneration(finished) - if world.characters[1000000].position != [3]float32{1, 0, 0} || world.characters[1000000].motion.returning || world.characters[1000000].motion.moving || world.characters[1000000].running || world.characters[1000000].health != 50 || len(world.fighting) != 0 || !world.characters[1000000].motion.nextMove.After(start.Add(time.Second)) { + if math.Abs(float64(world.characters[1000000].position[0]-1)) >= 1 || world.characters[1000000].motion.returning || world.characters[1000000].motion.moving || world.characters[1000000].running || world.characters[1000000].health != 50 || len(world.fighting) != 0 || !world.characters[1000000].motion.nextMove.After(finished) { t.Fatalf("return did not finish cleanly: %+v", world.characters[1000000]) } }) @@ -164,7 +175,7 @@ func TestNPCPursuitJoiningObserverGetsSpawnBeforeRouteAndAttack(t *testing.T) { 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 { + 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.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(observer.packets[2][42:46]))-1.3)) > .0001 { t.Fatalf("join order or current route: %x", observer.packets) } } diff --git a/server/npc_shared_pursuit_test.go b/server/npc_shared_pursuit_test.go @@ -3,6 +3,7 @@ package main import ( "ao/server/gamedata" "fmt" + "math" "testing" "time" ) @@ -22,23 +23,27 @@ func TestAdmittedNPCProfilesSharePursuitAndReturn(t *testing.T) { npc.motion.roaming = roaming deadline := npc.nextAttack - world.advanceNPCs(start.Add(250 * time.Millisecond)) + for tick := 1; tick <= 4; tick++ { + world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond)) + } - if npc.position != [3]float32{2.125, 0, 0} || !npc.running || !npc.motion.moving || npc.fighting != 1 || npc.nextAttack != deadline { + if npc.position[0] <= 2 || npc.position[0] >= 4 || !npc.running || !npc.motion.moving || npc.fighting != 1 || npc.nextAttack != deadline { t.Fatal("admitted profile did not pursue through the shared motion path", npc.position, npc.fighting, npc.nextAttack) } world.characters[1].health = 0 - world.advanceNPCs(start.Add(500 * time.Millisecond)) - world.advanceNPCs(start.Add(750 * time.Millisecond)) + for tick := 5; tick <= 40 && (npc.fighting != 0 || npc.motion.returning); tick++ { + world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond)) + } - if npc.position != [3]float32{1, 0, 0} || npc.running || npc.motion.moving || npc.motion.returning || npc.fighting != 0 || !npc.nextAttack.IsZero() { + if math.Abs(float64(npc.position[0]-1)) >= 1 || npc.motion.home != [3]float32{1, 0, 0} || npc.running || npc.motion.moving || npc.motion.returning || npc.fighting != 0 || !npc.nextAttack.IsZero() { t.Fatal("admitted profile did not stop and return to its retained home", npc.position, npc.motion, npc.fighting) } + position := npc.position world.advanceNPCs(start.Add(time.Minute)) - if npc.position != [3]float32{1, 0, 0} || npc.motion.moving != roaming || npc.running { + if npc.position != position || npc.motion.moving != roaming || npc.running { t.Fatal("return did not preserve its idle placement policy") } }) @@ -70,8 +75,9 @@ func TestFixedNPCPursuitUsesRemainingThreatAfterTargetLoss(t *testing.T) { world.characters[1].health = 0 world.advanceNPCs(start.Add(500 * time.Millisecond)) + world.advanceNPCs(start.Add(750 * time.Millisecond)) - if npc.position != [3]float32{2.125, 0, 1.125} || npc.fighting != 2 || npc.nextAttack != deadline || npc.motion.returning || !npc.running { + if npc.position[0] <= 1 || npc.position[0] >= 1.05 || npc.position[2] <= 0 || npc.position[2] >= .5 || npc.fighting != 2 || npc.nextAttack != deadline || npc.motion.returning || !npc.running { t.Fatal("motion discarded remaining threat or restarted its attack clock", npc.position, npc.fighting, npc.nextAttack) } } @@ -89,11 +95,11 @@ func TestFixedNPCPursuitRespectsRootAndSnare(t *testing.T) { world.advanceNPCs(at.Add(250 * time.Millisecond)) - want := float32(2) + want := float32(1.2666667) if program == 42110 { want = 1 } - if npc.position != [3]float32{want, 0, 0} || npc.motion.moving != (program != 42110) || npc.fighting != 1 { + if math.Abs(float64(npc.position[0]-want)) > .0001 || npc.position[1] != 0 || npc.position[2] != 0 || npc.motion.moving != (program != 42110) || npc.fighting != 1 { t.Fatal("fixed encounter bypassed the shared movement control", npc.position, npc.motion) } if program == 42110 { @@ -101,8 +107,9 @@ func TestFixedNPCPursuitRespectsRootAndSnare(t *testing.T) { world.advanceNanos(deadline) world.lastNPCUpdate = deadline world.advanceNPCs(deadline.Add(250 * time.Millisecond)) + world.advanceNPCs(deadline.Add(500 * time.Millisecond)) - if npc.position != [3]float32{2.125, 0, 0} || !npc.motion.moving || !npc.running { + if math.Abs(float64(npc.position[0]-1.3)) > .0001 || !npc.motion.moving || !npc.running { t.Fatal("root expiry did not resume fixed-encounter pursuit", npc.position, npc.motion) } } @@ -135,9 +142,10 @@ func TestFixedNPCColdLoadReturnsWithoutRestoringCombat(t *testing.T) { cold := newTestInventoryServer(t) cold.lastNPCUpdate = time.Now() cold.advanceNPCs(cold.lastNPCUpdate.Add(250 * time.Millisecond)) + cold.advanceNPCs(cold.lastNPCUpdate.Add(250 * time.Millisecond)) restored := cold.characters[npc.id] - want := float32(4.375) + want := float32(5.2) if state == "home" { want = 1 } @@ -145,7 +153,7 @@ func TestFixedNPCColdLoadReturnsWithoutRestoringCombat(t *testing.T) { want = 5.5 } if restored.motion == nil || restored.motion.roaming || restored.motion.home != [3]float32{1, 0, 0} || restored.fighting != 0 || - restored.position != [3]float32{want, 0, 0} || restored.health != 50 || restored.motion.returning != (before != restored.motion.home) || len(cold.mobileNPCs[952]) != 1 { + math.Abs(float64(restored.position[0]-want)) > .0001 || restored.position[1] != 0 || restored.position[2] != 0 || restored.health != 50 || restored.motion.returning != (before != restored.motion.home) || len(cold.mobileNPCs[952]) != 1 { t.Fatal("cold fixed encounter lost home, moved through a root or resumed stale combat", restored.position, restored.motion, restored.fighting) } }) diff --git a/server/roaming.go b/server/roaming.go @@ -87,27 +87,20 @@ func (server *server) advanceNPCs(now time.Time) { } character.motion.moving = true } - x := float64(character.motion.destination[0] - character.position[0]) - z := float64(character.motion.destination[2] - character.position[2]) - distance := math.Hypot(x, z) - angle := math.Atan2(x, z) - character.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))} if started { + x := float64(character.motion.destination[0] - character.position[0]) + z := float64(character.motion.destination[2] - character.position[2]) + angle := math.Atan2(x, z) + character.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))} character.running = false - server.queueCombat_locked(clients, character, character, npcRoutePacket(character)) + server.queueCombat_locked(clients, character, character, npcRoutePacket(character, character.position)) continue } - // The original vehicle walks at 1.5 metres per second between commands. - step := 1.5 * seconds - arrived := distance <= step + // Use the same acceleration and waypoint arrival as the native vehicle. + previous := character.position + arrived, _ := character.advanceNPCMotion(character.motion.destination, seconds) position := character.position - if distance <= step { - position = character.motion.destination - } else { - position[0] += float32(x / distance * step) - position[2] += float32(z / distance * step) - } // Follow changes in terrain height while preserving the authored ground offset. if ground := server.terrain[character.playfield]; ground != nil { @@ -117,7 +110,7 @@ func (server *server) advanceNPCs(now time.Time) { if inside { position[1] = character.motion.home[1] + height - home } else { - position = character.position + position = previous arrived = true } } diff --git a/server/roaming_test.go b/server/roaming_test.go @@ -166,7 +166,7 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) { 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} { + if world.characters[1000000].position[0] <= 52.5 || world.characters[1000000].position[0] >= 52.55 || world.characters[1000000].position[1] != 14 || world.characters[1000000].position[2] != 56 { t.Fatalf("walking speed did not match the original client: %v", world.characters[1000000].position) } } @@ -206,7 +206,7 @@ func TestJoiningPlayerReceivesOngoingNPCMovement(t *testing.T) { } } -func TestRoamingStopsAndPausesAtDestination(t *testing.T) { +func TestRoamingStopsWithinNativeWaypointRadiusAndPauses(t *testing.T) { data := testNPCData() data.Playfields[0].Districts[0].Groups[0].PlacementStatus = "authored_point" useNPCData(t, data) @@ -243,8 +243,8 @@ func TestRoamingStopsAndPausesAtDestination(t *testing.T) { <-done world.advanceNPCs(now.Add(250 * time.Millisecond)) - 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].motion.moving { - t.Fatal("NPC did not stop at its destination") + 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, 14, 56} || world.characters[1000000].motion.moving { + t.Fatal("NPC did not stop within the native waypoint radius") } if world.characters[1000000].motion.nextMove.Before(now.Add(3 * time.Second)) { t.Fatal("NPC did not pause between walks") @@ -299,12 +299,17 @@ func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) { t.Fatal(err) } now := time.Now() - world.characters[1000000].motion.destination = [3]float32{52.25, 14, 56} + world.characters[1000000].motion.destination = [3]float32{53.25, 14, 56} world.characters[1000000].motion.moving = true world.characters[1000000].motion.nextMove = now done := make(chan struct{}) - go func() { world.advanceNPCs(now); close(done) }() + go func() { + world.advanceNPCs(now) + world.advanceNPCs(now.Add(250 * time.Millisecond)) + world.advanceNPCs(now.Add(500 * time.Millisecond)) + close(done) + }() packet, err := readPacket(client) if err != nil { t.Fatal(err) @@ -315,7 +320,7 @@ func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) { } <-done - 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 { + if binary.BigEndian.Uint32(walk[36:40]) != 22 || world.characters[1000000].position[0] <= 52 || world.characters[1000000].position[0] >= 53.25 || math.Abs(float64(world.characters[1000000].position[1]-14-(world.characters[1000000].position[0]-52)*.5)) > .0001 || math.Float32frombits(binary.BigEndian.Uint32(packet[53:57])) != world.characters[1000000].position[1] { t.Fatalf("NPC did not follow the slope: %v", world.characters[1000000].position) } }