commit 8ad1ece4b9f8cc76255569e9b50568446aeda62e
parent 8c66a8c14379ed3dcd08e63104bc8a4ed7b9caba
Author: anon <anon@example.com>
Date: Mon, 26 Oct 2026 05:54:32 +0000
Simulate native player following in authoritative server state
Advance transient follow motion with the recovered arrival controller and
shared item mass, feeding range checks, cast gates and periodic checkpoints.
Replay held target input and current follow state to loading observers, and
serialize the complete native player vehicle state.
Preserve native manual cancellation and target-loss stop semantics. Document
verified open-ground behavior and the remaining collision, directional and
movement-prediction boundaries.
Diffstat:
15 files changed, 1214 insertions(+), 46 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1532,18 +1532,32 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
correction/path; it is distinct from the exported CharacterAction29 sender.
Source RTTI establishes PlayerVehicle steering for owners and remote players,
the four-unit offset, ordinary movement cancellation and preserved mouse20
- rotation. A response-only prototype proves native following but exposes stale
- Go positions until manual cancellation; it is not enabled in the server.
+ rotation. A response-only prototype exposed stale Go positions until manual
+ cancellation and established the need for the authoritative controller below.
Ordinary flat-ground acceleration/braking/integration equations and complete
source hashes are retained. See [player following](docs/player-follow.md).
-- [ ] Implement authoritative player following through its native FollowTarget
- request. Couple transient target/velocity state, shared native arrival physics,
- position consumers and periodic checkpoints before enabling the response.
- Preserve body-mass/total-mass force limits and native braking rather than
- fixed-speed steps. Check owner/observer/server positions during movement and
- arrival, late observation, target changes/chains/cycles, keyboard cancellation
+- [x] Implement the open-ground authoritative player-follow controller through
+ native FollowTarget. Transient target/velocity state, shared native arrival
+ physics, breed/sex body mass and generic carried-item mass feed position
+ consumers and periodic checkpoints. Movement cancellation, mouse20 retention,
+ target loss, cyclic snapshots, rooted suspension, cast admission/refunds and late
+ replay have regressions. Hardware compares owner/observer/server arrival positions
+ and verifies target-loss stops clear native throttle without changing run mode.
+ Scene collision and the full lifecycle matrix remain the next item.
+- [ ] Complete canonical player following. Recover native scene collision,
+ surface projection, slopes, falling/flight and platforms instead of relying on
+ the current NPC height-map policy. Replace the shared held-input predictor's
+ 20-second horizon and instant speed with native movement, including strafe/turn
+ state, so long uninterrupted targets do not freeze or lead their client pose.
+ Recover retained backward-direction steering when activating follow after
+ reverse movement; the current controller covers positive-direction following.
+ Verify live Chest VolumeMass after filling/emptying bags; its constructor's
+ zero is not proof of every later contents update. Check owner/observer/server
+ positions during movement and arrival, late observation, target changes/chains/cycles, keyboard cancellation
versus mouse20 rotation, roots/snares, terrain/flight, death/despawn, zoning,
- disconnect, reconnect/cold checkpoints and zero routine DB churn. Establish
+ disconnect, reconnect/cold checkpoints and zero routine DB churn. Include
+ stationary and roaming NPC targets in the hardware movement comparisons.
+ Establish
self/dead/unknown/different-zone target policies and reject forged ownership,
corrections and waypoints. The echo-only experiment is not completion.
- [ ] Establish the actual caller and server contract of the exported
diff --git a/docs/player-follow.md b/docs/player-follow.md
@@ -2,11 +2,148 @@
The ordinary 14.9.1 `/follow` command sends FollowTargetIIR_c, key `0x260f3671`.
It does not send the CharacterAction 29 constructed by the separately exported
-N3Msg_Follow method. Receiving and echoing the ordinary request enables native
-following for both the owner and observers, but does not update the server's
-position: the captured following session sent no movement snapshots while moving.
-Authoritative following remains unimplemented pending coupled motion,
-lifecycle and checkpoint handling.
+N3Msg_Follow method. The server now admits the ordinary request and advances
+transient authoritative follow motion using the recovered arrival controller.
+The client supplies no routine automatic position snapshots during following. Open-ground
+positive-direction movement is implemented; native scene collision, complete terrain/flight behavior
+and the full combined lifecycle matrix remain unfinished.
+
+## Server implementation
+
+`server/player_follow.go` validates the owned actor, captured scalar/control,
+zero correction and empty path. It admits living connected players and known
+living NPCs in the same playfield. A self-target is harmlessly stationary under
+the same controller. Dead, unavailable and different-zone targets are rejected;
+these eligibility policies are explicit implementation choices, not recovered
+historical server rules.
+
+Follow state lives with the actor in memory and is cleared on manual non20
+movement, target loss, death/loading and session replacement/disconnection.
+Mouse20 reanchors the pose while retaining the controller. Target changes retain
+velocity. Manual turn and walk/run events retain an actively moving follower's
+forward throttle before applying the ordinary input transition; arrived followers
+retain zero throttle. Source cases L06-L07 establish that these events clear the
+target without halting linear movement. Target loss sends CharDCMove stops 2 and 4: clearing the native target
+alone leaves its automatic throttle active. The matching direction event clears
+throttle and halts without changing preferred walk/run mode; the other is ignored.
+Complete receiver/listener/state-machine bodies are recorded in
+`local/player-follow-research/mass/cache/target-loss.md` (L01-L05).
+A 60 Hz simulation snapshots every target before moving any follower,
+so chains/cycles do not recurse or depend on Go map iteration. This tick rate is
+a server scheduling choice verified against native movement, not a recovered
+historical server frequency.
+
+Position consumers read the updated pose directly. Movement interrupts casts,
+checks trade/bank availability and participates in ordinary zone triggers.
+Cast admission also checks actual follow velocity: a moving follower cannot
+reserve nano, while an arrived follower can cast normally. Height-map projection
+subtracts heights before adding the delta to avoid floating-point noise moving
+a stationary actor and incorrectly interrupting its cast.
+The existing periodic checkpoint saves pose; follow ticks perform no routine
+database writes. Significant cast refunds retain their immediate transaction.
+Late observers receive the current velocity in the actor snapshot, then a
+CurrentMass update and FollowTarget immediately after both actors have spawned.
+It does not wait for the observer's own readiness while a moving actor has
+already started simulating. Readiness repeats the controller with its current
+pose correction to cover time spent loading. Initial and ready replay restore
+held forward/backward input and predicted poses for ordinary moving players
+before their followers. Otherwise a joining client would follow an old,
+stationary copy of the target. NPC interest entry also replays affected targets.
+
+Body mass comes from KKR SimpleChar initialization 3606dd00's breed/sex table,
+scaled by float32(0.001): Solitus 80/70, Opifex 75/65, Nanomage 75/60, Atrox 100.
+Movement refresh 36047e60 uses 10 only for an otherwise zero mass. Carried mass
+uses generic item stat 2, quantity and normalized stat 212 over ordinary inventory
+slots; equipped/bank items are excluded. A live Chest supplies VolumeMass 71,
+initialized to zero by its constructor. Later contents propagation remains an
+explicit research boundary; the server currently uses zero for Chests. Body mass
+is the force integration denominator; total mass sets its force cap. The server
+publishes CurrentMass 78 to observers, which have no copy of the owner's inventory,
+and refreshes it when an active follower's carried mass changes. That update is
+followed by the unchanged raw RunSpeed 156: CurrentMass alone does not rebuild
+the native vehicle cache. Stat dispatch 3606e4fe refreshes through 360480e0 and
+36047e60 before storing RunSpeed. The unchanged raw value avoids reading an
+uncommitted replacement or counting equipment/nano modifiers twice.
+
+Native physical start invokes PlayerVehicle 360481a0 and movement event 1,
+setting helper locomotion/direction to 3/1 and forward control to 1. Arrival Halt
+invokes 3604bc80/360481d0 and event 2, restoring 1/0 and forward control 0. Before
+the first moving outer Run, the running parameter cache therefore uses the
+reverse formula; subsequent movement uses the forward formula. The server
+preserves that first-step distinction. A moving snapshot supplies both helper
+bytes and its forward control, in addition to velocity.
+
+The recovered PlayerVehicle reader/writer requires 42 bytes: velocity 12,
+ten helper bytes, preferred mode 4 and four control floats 16. Empty NPCVehicle
+uses 28 bytes because its tail is a short waypoint count. The old shared
+28-byte player buffer caused tolerant native read failure, zero controls and
+stream status 3. Player snapshots now supply the complete buffer. Source bodies,
+writer/reader pairs and cache callback hashes are retained under
+`local/player-follow-research/mass/cache/`.
+
+Maintained encumbrance flag 36306612 starts zero in its guest mapping, with no
+direct setter recovered. The implementation does not invent an enabled overload
+penalty. Complete mass bodies, source hashes and initialization evidence are in
+`local/player-follow-research/mass/`. A read-only hardware measurement independently
+matches the native body masses 0.08000000566 and 0.07000000030 for the two visitors.
+
+The ground-height policy currently matches NPC roaming's archived height map.
+It does not implement native QQR scene geometry/surface collision. The full
+Follow TODO remains open for that boundary, slopes, gravity/flight, platform
+behavior and combined lifecycle/resource cases.
+The shared manual-input predictor also retains its existing 20-second horizon
+and instant-speed approximation, and does not reconstruct strafe/turn motion.
+These are outstanding general movement limitations, including follow targets.
+Retaining native backward-direction steering when follow starts after reverse
+movement also remains outside the current positive-direction controller.
+
+## Authoritative-controller verification
+
+The evidence and verification script are in `local/player-follow-authority/`.
+All GUI actions use the ordinary WASM client on the GPU. Native probes only
+read state; fixture changes use the public control editor. The successful final
+walking route lasts 19 seconds, below the shared input predictor's known
+20-second horizon. Earlier longer-held and stale-observer failures are retained
+as diagnostics and do not count as successful canonical movement.
+
+- Owner arrival differs from the authoritative server pose by 0.038 units.
+ A cold observer arrives within 0.036 units; its moving replay is within 0.122.
+ The remaining vertical difference is the native scene surface versus the
+ server's quantized height map. Weighted inventory refresh also matches native
+ mass/force parameters, including CurrentMass followed by the RunSpeed refresh.
+- Initial and ready replay both restore the target's held forward input before
+ the follower controller. Read-only native velocity/control probes verify that
+ the late target moves rather than remaining at its old anchor.
+- The 25.5-second owner sample has one action20 pose message near its start and
+ no subsequent movement snapshots. Server position therefore must advance
+ independently. Mouse rotation retains following; a normal movement key clears it.
+- A running follower stops when its target changes playfields. Native follow
+ pointer, throttle and velocity all clear; 20 subsequent samples over two seconds
+ keep exactly the same position. The two stop packets are verified on the wire.
+- Native Backspace and left-turn cancellation retain forward throttle, clear the
+ target and keep the public map estimate advancing with the client. A subsequent
+ W press/release clears throttle and velocity. Moving and arrived automated
+ cases separately cover forward/backward starts/stops and turn/walk/run events.
+- Automated cases cover untrusted/malformed requests, visibility/session gates,
+ acceleration, arrival/crossing, mass, cycles, retargeting, manual cancellation,
+ roots, late replay, casting admission/refunds, simultaneous trade movement and
+ periodic checkpoints without tick writes. A real stationary-terrain regression
+ first reproduced the rounding-induced false cast interruption, then passed.
+- Focused tests, race checks, vet and the complete suite are recorded separately
+ with source hashes in the evidence directory. An intermediate broad run exposed
+ old appearance assertions after the corrected 42-byte player vehicle; those
+ offsets were corrected before the final complete run.
+
+The final complete run covers every one of the 1,196 top-level server tests
+exactly once across four batches, plus gamedata and the exporter package:
+13,981 test/subtest results pass. Source hashes match the final tree. The final
+focused race run has 109 passing results; vet passes. Results are indexed in
+`verification.json` and `exact-suite-manifest.json` in the evidence directory.
+
+Browser page-error logs are empty. All nine owned player fixtures and their
+owned item were removed after closing their browsers; unrelated database rows
+were hashed unchanged and foreign-key/integrity checks passed. The sole LAN
+preview remains on HTTPS8443 with the tested controller.
## Request and receiver contract
@@ -64,8 +201,8 @@ target-clear packet. Destructor 0x36047964 also clears the target.
SCFU reader 0x36082da0 accepts an embedded follow identity and waypoint count/list
under flag 0x00010000, after active-nano restoration. Activation 0x360821d0 installs
-that target at 0x360828c6. Late-observer restoration must establish both actors
-before replaying following; the current Go snapshot does not supply this state.
+that target at 0x360828c6. Go instead queues the separate FollowTarget after all
+actor snapshots, establishing both identities before replaying the controller.
The exact historical server correction cadence and every reference-deletion
callback remain unestablished.
@@ -107,8 +244,9 @@ position changes once per outer Run, while force is recomputed per substep.
The default maximum substep is 0.4 seconds; nonpositive or greater-than-four
second intervals do not advance the integrator. A chosen Go tick rate must
be verified against actual native motion, including the full gravity, surface
-and collision branches. The encumbrance multiplier depends on a global flag
-whose effective live/default value remains unresolved.
+and collision branches. The encumbrance multiplier depends on a global flag;
+its maintained mapping starts zero, while the original live effective value
+and indirect setters remain unestablished.
The inspected following path has no automatic movement-message publisher.
All direct maintained calls to ordinary CharDCMove's constructor come from
@@ -116,11 +254,11 @@ N3Msg_MovmentChanged; extended action 20 comes from rotation input/flush. That
bounded source search alone cannot prove all possible outbound behavior, but
the hardware capture below confirms the missing snapshots in the tested flow.
-The server needs transient follow state and authoritative motion, shared with
-its position consumers and periodic checkpoints. It must retain rotation 20,
-cancel on other admitted movement, stop or suspend coherently for disappearing
-targets and movement restrictions, interrupt affected casts/trades/bank access,
-and handle target chains without recursive cycles or iteration-order dependence.
+The server uses transient follow state and authoritative motion, shared with
+its position consumers and periodic checkpoints. It retains rotation 20,
+cancels on other admitted movement, stops or suspends for disappearing targets
+and movement restrictions, interrupts affected casts/trades/bank access, and
+handles target chains without recursive cycles or iteration-order dependence.
Scene geometry and height/flight behavior require explicit validation. Durable
resource changes still commit immediately; routine follow positions do not
require per-tick database writes.
diff --git a/docs/server-action-coverage.md b/docs/server-action-coverage.md
@@ -58,11 +58,15 @@ pass. The overall complete-action-set TODO remains open.
The ordinary player `/follow` route is now independently captured and traced.
FollowTarget installs native PlayerVehicle steering for owners and observers;
-the follower sends no automatic movement snapshots in the verified long-walk
+the follower sends no regular automatic movement snapshots in the verified long-walk
flow. An echo-only prototype left Go's position frozen; a manual cancellation
packet finally reported a 12.1-unit change. It is retained as research, with
-native arrival-force/integration equations, and is not enabled in the server. Authoritative following and the
-distinct exported action29 path remain separate unchecked tasks.
+native arrival-force/integration equations. The production handler now couples
+the native response to transient authoritative arrival motion, mass, cancellation
+and periodic position checkpoints. Open-ground hardware comparisons verify that
+the server advances with both clients. Complete scene collision/terrain/flight
+and the distinct exported action29 path remain unchecked tasks; see
+[player following](player-follow.md).
## Camping cancellation
diff --git a/server/actor_speed_test.go b/server/actor_speed_test.go
@@ -27,12 +27,12 @@ func TestActorSpawnRunSpeedUsesNativeWidthsWithoutMovingMaterials(t *testing.T)
packet := targetPacket(characterPacket(player))
flags := binary.BigEndian.Uint32(packet[30:34])
- if (flags&0x2000 != 0) != scenario.wide || !bytes.Equal(packet[143:143+len(scenario.wire)], scenario.wire) {
- t.Fatalf("RunSpeed encoding: flags=%x field=%x", flags, packet[143:147])
+ if (flags&0x2000 != 0) != scenario.wide || !bytes.Equal(packet[157:157+len(scenario.wire)], scenario.wire) {
+ t.Fatalf("RunSpeed encoding: flags=%x field=%x", flags, packet[157:161])
}
- materials := 143 + len(scenario.wire)
+ materials := 157 + len(scenario.wire)
if binary.BigEndian.Uint32(packet[materials:]) != 10090 || bytes.Index(packet, []byte("arms\x00")) != materials+4 {
- t.Fatalf("RunSpeed width displaced the native material list: %x", packet[143:])
+ t.Fatalf("RunSpeed width displaced the native material list: %x", packet[157:])
}
for _, name := range []string{"hands", "body", "Material #2b", "Material #8"} {
if !bytes.Contains(packet, append([]byte(name), make([]byte, 32-len(name))...)) {
@@ -128,7 +128,7 @@ func TestLateActorSpawnKeepsTrainedSpeedSeparateFromEquipmentAndNanos(t *testing
}
if state.characters[1].stats.Speed.RunSpeed != 256 || state.characters[1].inventory.equipmentBonus(156) != 150 || state.characters[1].nanoBonus(156) != 10 ||
- len(spawn) < 145 || binary.BigEndian.Uint32(spawn[30:34])&0x2000 == 0 || !bytes.Equal(spawn[143:145], []byte{1, 0}) || wear != 1 || nanos != 1 {
+ len(spawn) < 159 || binary.BigEndian.Uint32(spawn[30:34])&0x2000 == 0 || !bytes.Equal(spawn[157:159], []byte{1, 0}) || wear != 1 || nanos != 1 {
t.Fatalf("late actor lost training or counted modifiers in its base: speed=%d wear=%d nanos=%d spawn=%x", state.characters[1].stats.Speed.RunSpeed, wear, nanos, spawn)
}
connection.Close()
diff --git a/server/appearance_test.go b/server/appearance_test.go
@@ -56,7 +56,7 @@ func TestPlayerAppearanceUsesEachNativeBreedAndSexTemplate(t *testing.T) {
packet := characterPacket(player)
- if binary.BigEndian.Uint32(packet[145:149]) != scenario.head {
+ if binary.BigEndian.Uint32(packet[159:163]) != scenario.head {
t.Fatal("explicit head mesh was replaced or truncated")
}
for index, name := range []string{"arms", "feet", "hands", "legs", "body"} {
@@ -100,7 +100,7 @@ func TestPlayerAppearancePersistsThroughControlEditAndRestart(t *testing.T) {
spawn := characterPacket(restored)
if response.Code != 303 || restored.headMesh != 40132 || restored.height != 110 || restored.appearance != 0x2c9 ||
- binary.BigEndian.Uint32(spawn[145:149]) != 40132 || binary.BigEndian.Uint16(spawn[111:113]) != 110 {
+ binary.BigEndian.Uint32(spawn[159:163]) != 40132 || binary.BigEndian.Uint16(spawn[111:113]) != 110 {
t.Fatalf("appearance changed across edit/restart: %d head=%d height=%d appearance=%x", response.Code, restored.headMesh, restored.height, restored.appearance)
}
}
@@ -173,7 +173,7 @@ func TestSolitusAppearanceUsesExplicitHeadMeshAndMatchingSkin(t *testing.T) {
packet := characterPacket(visitor)
- if binary.BigEndian.Uint32(packet[145:149]) != appearance.head || string(packet[188:194]) != "hands\x00" || binary.BigEndian.Uint32(packet[194:198]) != appearance.hands {
+ if binary.BigEndian.Uint32(packet[159:163]) != appearance.head || string(packet[202:208]) != "hands\x00" || binary.BigEndian.Uint32(packet[208:212]) != appearance.hands {
t.Fatalf("appearance %x has incorrect head or skin: %x", appearance.packed, packet)
}
}
diff --git a/server/interest.go b/server/interest.go
@@ -58,6 +58,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
if client.ready && len(spawned) != 0 {
// Rebuild fighting targets only after every new participant has spawned.
updates = append(updates, server.combatInterest_locked(client, spawned)...)
+ updates = append(updates, server.playerFollowReplay_locked(client, spawned)...)
}
return updates
}
diff --git a/server/main.go b/server/main.go
@@ -70,6 +70,7 @@ func main() {
go server.serveWorld()
go server.serveChat()
go server.roamNPCs()
+ go server.followPlayers()
go server.saveWorld()
go server.checkZoneCrossings()
@@ -271,6 +272,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
return
}
server.cancelPlayerTrade_locked(client)
+ character.follow = nil
client.ready = false
updates := make(map[*worldClient][][]byte)
server.cancelCombat_locked(character.id, updates)
@@ -351,6 +353,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
return err
}
}
+ character.follow = nil
server.clients[character.id] = client
for index := range character.activeNanos {
if character.activeNanos[index].expiresAt.IsZero() {
@@ -368,7 +371,9 @@ func (server *server) serveWorldClient(client *worldClient) error {
updates := [][]byte{playfieldPacket(character), characterPacket(character)}
for id, other := range server.characters {
if id != character.id && other.playfield == character.playfield && server.clients[id] != nil {
- updates = append(updates, characterPacket(other))
+ snapshot := *other
+ snapshot.position = predictedPosition_locked(other, server.clients[id], time.Now())
+ updates = append(updates, characterPacket(&snapshot))
if !server.clients[id].loading {
updates = append(updates, playerCombatStatPackets(other)...)
updates = append(updates, equippedItemPackets(other)...)
@@ -381,6 +386,8 @@ func (server *server) serveWorldClient(client *worldClient) error {
}
}
updates = append(updates, server.updateNPCInterest_locked(client, time.Now())...)
+ updates = append(updates, server.playerMovementReplay_locked(client, time.Now())...)
+ updates = append(updates, server.playerFollowReplay_locked(client, nil)...)
if client.target {
updates = append(updates, server.chatServerPacket(conn))
}
@@ -602,6 +609,10 @@ func (server *server) serveWorldClient(client *worldClient) error {
if err := server.handleMovement(client, body); err != nil {
return err
}
+ case 0x260f3671:
+ if err := server.handlePlayerFollow(client, body); err != nil {
+ return err
+ }
}
case 11:
// Return the client's ping with the reply subtype.
diff --git a/server/main_test.go b/server/main_test.go
@@ -357,14 +357,14 @@ func TestWorldCookieThenPing(t *testing.T) {
if hex.EncodeToString(updates[1][67:70]) != "031511" {
t.Fatalf("player appearance and name length: %x", updates[1][67:70])
}
- if hex.EncodeToString(updates[1][122:154]) != "0000001c00000000000000000000000002010001000100010001000000020000" {
- t.Fatalf("player vehicle state: %x", updates[1][122:154])
+ if hex.EncodeToString(updates[1][122:168]) != "0000002a000000000000000000000000020100010001000100010000000200000000000000000000000000000000" {
+ t.Fatalf("player vehicle state: %x", updates[1][122:168])
}
- if hex.EncodeToString(updates[1][37:41]) != "000002d8" || hex.EncodeToString(updates[1][154:158]) != "00009ee9" {
+ if hex.EncodeToString(updates[1][37:41]) != "000002d8" || hex.EncodeToString(updates[1][168:172]) != "00009ee9" {
t.Fatalf("player head mesh: %x", updates[1])
}
- if hex.EncodeToString(updates[1][159:163]) != "0000276a" || hex.EncodeToString(updates[1][197:215]) != "68616e647300000022450000000000000000" {
- t.Fatalf("original named hand texture: %x", updates[1][159:215])
+ if hex.EncodeToString(updates[1][173:177]) != "0000276a" || hex.EncodeToString(updates[1][211:229]) != "68616e647300000022450000000000000000" {
+ t.Fatalf("original named hand texture: %x", updates[1][173:229])
}
var leet []byte
for _, update := range updates {
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -155,6 +155,7 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error {
accepted := targetType == 50000 && binary.BigEndian.Uint32(body[28:32]) == 53019 &&
slices.Contains(player.inventory.LearnedNanos, program) && player.nanoRequirementsMet(program) &&
!player.sitting && !player.driving() && client.forward == 0 && !client.strafing && !client.turning && client.equipment == nil &&
+ (player.follow == nil || player.follow.velocity == [3]float32{}) &&
server.nanoTarget_locked(player, target, client, program, now)
var cost int32
if accepted {
diff --git a/server/player_follow.go b/server/player_follow.go
@@ -0,0 +1,331 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "fmt"
+ "math"
+ "time"
+)
+
+type playerFollow struct {
+ target uint32
+ velocity [3]float32
+ previousPosition [3]float32
+ updatedAt time.Time
+ carriedMass int32
+}
+
+func (server *server) handlePlayerFollow(client *worldClient, body []byte) error {
+ if len(body) != 45 {
+ return fmt.Errorf("invalid player follow length")
+ }
+ if !client.target || binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id ||
+ binary.BigEndian.Uint32(body[12:16]) != 1 || binary.BigEndian.Uint32(body[16:20]) != 50000 ||
+ binary.BigEndian.Uint32(body[24:28]) != 0x40200000 {
+ return nil
+ }
+ // Native /follow supplies no control, position correction or authored path.
+ for _, value := range body[28:] {
+ if value != 0 {
+ return nil
+ }
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ player := server.characters[client.id]
+ target := server.characters[binary.BigEndian.Uint32(body[20:24])]
+ if server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || player.sitting ||
+ !server.playerFollowTargetAvailable_locked(client, target) {
+ server.mutex.Unlock()
+ return nil
+ }
+ now := time.Now()
+ player.position = predictedPosition_locked(player, client, now)
+ if player.follow != nil {
+ player.follow.target = target.id
+ } else {
+ player.follow = &playerFollow{target: target.id, previousPosition: player.position, updatedAt: now}
+ // Installing a target preserves native velocity, including held forward input.
+ if client.forward != 0 {
+ speed := float32(1.5)
+ if player.running || player.flying() {
+ speed = player.runningMovementSpeed(client.forward < 0)
+ }
+ x, y, z, w := player.rotation[0], player.rotation[1], player.rotation[2], player.rotation[3]
+ player.follow.velocity = [3]float32{speed * client.forward * (2*x*z + 2*y*w), 0, speed * client.forward * (1 - 2*x*x - 2*y*y)}
+ if player.flying() {
+ player.follow.velocity[1] = speed * client.forward * (2*y*z - 2*x*w)
+ }
+ }
+ }
+ updates := make(map[*worldClient][][]byte)
+ _, player.follow.carriedMass = player.followMass()
+ server.queueCombat_locked(updates, player, target, playerFollowMassPackets(player)...)
+ server.queueCombat_locked(updates, player, target, playerFollowPacket(player.id, target.id))
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+ return nil
+}
+
+func (server *server) playerFollowTargetAvailable_locked(client *worldClient, target *character) bool {
+ if target == nil || target.health == 0 || target.playfield != server.characters[client.id].playfield {
+ return false
+ }
+ if target.npc {
+ return client.npcs[target.id]
+ }
+ other := server.clients[target.id]
+ return other != nil && other.ready && !other.loading
+}
+
+func playerFollowPacket(id, target uint32) []byte {
+ // KKR FollowTargetIIR_c::Activate (3607e690), control 0 leaves mode unchanged.
+ body := make([]byte, 29)
+ if target != 0 {
+ binary.BigEndian.PutUint32(body, 50000)
+ binary.BigEndian.PutUint32(body[4:], target)
+ }
+ binary.BigEndian.PutUint32(body[8:], 0x40200000)
+ return n3Packet(0x260f3671, 50000, id, body)
+}
+
+func playerFollowMassPackets(player *character) [][]byte {
+ // Stat78 alone does not refresh native vehicle parameters. Reapply raw156 after
+ // it: KKR 3606e4fe -> 360480e0 -> 36047e60 refreshes before storing the same value.
+ var packets [][]byte
+ for _, stat := range [][2]uint32{{78, uint32(player.follow.carriedMass)}, {156, uint32(player.baseStats().Speed.RunSpeed)}} {
+ body := binary.BigEndian.AppendUint32(nil, stat[0])
+ body = binary.BigEndian.AppendUint32(body, stat[1])
+ packets = append(packets, n3Packet(0x2b333d6e, 50000, player.id, body))
+ }
+ return packets
+}
+
+func (server *server) followPlayers() {
+ ticker := time.NewTicker(time.Second / 60)
+ defer ticker.Stop()
+ for now := range ticker.C {
+ server.advancePlayerFollowing(now)
+ }
+}
+
+func (server *server) advancePlayerFollowing(now time.Time) {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ updates := make(map[*worldClient][][]byte)
+ server.advancePlayerFollowing_locked(now, updates)
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+}
+
+func (server *server) advancePlayerFollowing_locked(now time.Time, updates map[*worldClient][][]byte) {
+ // Snapshot all targets before advancing any follower, including chains/cycles.
+ targets := make(map[uint32][3]float32)
+ for _, client := range server.clients {
+ player := server.characters[client.id]
+ if player.follow == nil {
+ continue
+ }
+ if target := server.characters[player.follow.target]; server.playerFollowTargetAvailable_locked(client, target) {
+ position := target.position
+ if !target.npc {
+ position = predictedPosition_locked(target, server.clients[target.id], now)
+ }
+ targets[target.id] = position
+ }
+ }
+ var moved []*worldClient
+ for id, client := range server.clients {
+ player := server.characters[id]
+ if player.follow == nil {
+ continue
+ }
+ target := server.characters[player.follow.target]
+ if !client.ready || client.loading || player.health == 0 || !server.playerFollowTargetAvailable_locked(client, target) {
+ player.follow = nil
+ client.forward = 0
+ client.movementStarted = now
+ // Clearing the target alone retains native automatic throttle. Release both
+ // directions; the matching event halts without changing walk/run preference.
+ server.queueCombat_locked(updates, player, player, npcMovementPacket(player, 2), npcMovementPacket(player, 4))
+ continue
+ }
+ previous := player.position
+ seconds := now.Sub(player.follow.updatedAt).Seconds()
+ player.follow.updatedAt = now
+ speed := float32(1.5)
+ if player.running || player.flying() {
+ // Native OnStart advances helper subtype0 to forward1 after the first Run;
+ // Halt restores subtype0. Its initial running cache uses the reverse formula.
+ speed = player.runningMovementSpeed(player.follow.velocity == [3]float32{})
+ }
+ if player.movementRestricted() || player.sitting {
+ player.follow.velocity = [3]float32{}
+ player.follow.previousPosition = player.position
+ continue
+ }
+ bodyMass, carriedMass := player.followMass()
+ if carriedMass != player.follow.carriedMass {
+ player.follow.carriedMass = carriedMass
+ server.queueCombat_locked(updates, player, player, playerFollowMassPackets(player)...)
+ }
+ totalMass := bodyMass + float32(carriedMass)*float32(0.001)
+ player.position = player.follow.advance(player.position, targets[target.id], seconds, speed, bodyMass, totalMass)
+ if !player.flying() {
+ // Reuse roaming's height-map policy; scene mesh collision is still pending.
+ if ground := server.terrain[player.playfield]; ground != nil {
+ oldHeight, oldInside := ground.elevation(previous[0], previous[2])
+ newHeight, newInside := ground.elevation(player.position[0], player.position[2])
+ if oldInside && newInside {
+ player.position[1] = previous[1] + (newHeight - oldHeight)
+ }
+ }
+ }
+ if player.position != previous {
+ velocity := player.follow.velocity
+ if velocity[0] != 0 || velocity[2] != 0 {
+ angle := math.Atan2(float64(velocity[0]), float64(velocity[2]))
+ player.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))}
+ }
+ moved = append(moved, client)
+ }
+ }
+ // Check interactions against the completed frame, including two moving traders.
+ for _, client := range moved {
+ server.abortNano_locked(client, now, updates)
+ if client.trade != nil && !server.playerTradeAvailable_locked(client.trade.clients[0], client.trade.clients[1]) {
+ server.cancelPlayerTrade_locked(client)
+ }
+ if client.bank != nil && !server.bankAvailable_locked(client) {
+ updates[client] = append(updates[client], characterActionPacket(client.id, [5]uint32{106}))
+ }
+ }
+}
+
+func (player *character) followMass() (float32, int32) {
+ // KKR SimpleChar initialization (3606dd00) writes mass stat2 from breed/sex.
+ appearance := unpackAppearance(player.appearance)
+ mass := [8][4]uint32{{}, {0, 0, 80, 70}, {0, 0, 75, 65}, {0, 0, 75, 60}, {0, 100}, {0, 100}}[appearance.Breed][appearance.Sex]
+ bodyMass := float32(mass) * float32(0.001)
+ if bodyMass == 0 {
+ bodyMass = 10
+ }
+
+ // Native inventory mass (36061bf0): ordinary slots only, Chest VolumeMass71=0.
+ var carriedMass int32
+ for _, item := range player.inventory.Items {
+ if item.Slot < 64 || item.isPortableContainer() {
+ continue
+ }
+ low, high := item.templateIDs()
+ first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high]
+ itemMass, quantity := int32(itemStat(first, 2)), int32(itemStat(first, 212))
+ if low != high {
+ itemMass = interpolateItemValue(itemMass, int32(itemStat(second, 2)), *first.Quality, *second.Quality, item.Quality)
+ quantity = interpolateItemValue(quantity, int32(itemStat(second, 212)), *first.Quality, *second.Quality, item.Quality)
+ }
+ if quantity < 1 || quantity == 0x499602d2 {
+ quantity = 1
+ }
+ carriedMass += itemMass * int32(item.Count) / quantity
+ }
+ return bodyMass, carriedMass
+}
+
+func (server *server) playerFollowReplay_locked(observer *worldClient, spawned map[uint32]bool) [][]byte {
+ // Both actor snapshots must precede the controller, including NPC interest entry.
+ var packets [][]byte
+ for id, client := range server.clients {
+ player := server.characters[id]
+ if player.follow == nil || !client.ready || client.loading || server.characters[id].playfield != server.characters[observer.id].playfield {
+ continue
+ }
+ target := server.characters[player.follow.target]
+ if !server.playerFollowTargetAvailable_locked(client, target) || target.npc && !observer.npcs[target.id] ||
+ spawned != nil && !spawned[target.id] {
+ continue
+ }
+ packets = append(packets, playerFollowMassPackets(player)...)
+ packet := playerFollowPacket(id, target.id)
+ // Refresh pose as well as target after an observer spent time loading.
+ for axis, value := range player.position {
+ binary.BigEndian.PutUint32(packet[49+axis*4:], math.Float32bits(value))
+ }
+ packets = append(packets, packet)
+ }
+ return packets
+}
+
+func (server *server) playerMovementReplay_locked(observer *worldClient, now time.Time) [][]byte {
+ // Restore the same held input and current pose before replaying its followers.
+ var packets [][]byte
+ for id, client := range server.clients {
+ player := server.characters[id]
+ if id == observer.id || !client.ready || client.loading || player.follow != nil || client.forward == 0 || player.playfield != server.characters[observer.id].playfield {
+ continue
+ }
+ snapshot := *player
+ snapshot.position = predictedPosition_locked(player, client, now)
+ action := uint32(1)
+ if client.forward < 0 {
+ action = 3
+ }
+ packets = append(packets, npcMovementPacket(&snapshot, action))
+ }
+ return packets
+}
+
+func (follow *playerFollow) advance(position, target [3]float32, seconds float64, speed, bodyMass, totalMass float32) [3]float32 {
+ // QQR Vehicle::Run (42014fb0/42011d30): reject long stalls, subdivide at 0.4s.
+ previous := position
+ defer func() { follow.previousPosition = previous }()
+ if seconds <= 0 || seconds > 4 {
+ return position
+ }
+ for seconds > 0 {
+ step := float32(math.Min(seconds, 0.4))
+ seconds -= float64(step)
+ delta := [3]float32{target[0] - position[0], target[1] - position[1], target[2] - position[2]}
+ distance := float32(math.Sqrt(float64(delta[0]*delta[0] + delta[1]*delta[1] + delta[2]*delta[2])))
+ arrival := position
+ if distance > 4 {
+ for axis := range arrival {
+ arrival[axis] += delta[axis] * ((distance - 4) / distance)
+ }
+ }
+ delta = [3]float32{arrival[0] - position[0], arrival[1] - position[1], arrival[2] - position[2]}
+ distance = float32(math.Sqrt(float64(delta[0]*delta[0] + delta[1]*delta[1] + delta[2]*delta[2])))
+ // KKR 36048430 and QQR SteeringDirArrive (42015fe0/42015e90).
+ if distance < 0.2 || delta[0]*(arrival[0]-follow.previousPosition[0])+delta[2]*(arrival[2]-follow.previousPosition[2]) < 0 {
+ follow.velocity = [3]float32{}
+ break
+ }
+ force := [3]float32{}
+ for axis := range force {
+ force[axis] = 4 * bodyMass * (delta[axis]/distance*min(speed, 4*distance) - follow.velocity[axis])
+ }
+ forceLength := float32(math.Sqrt(float64(force[0]*force[0] + force[1]*force[1] + force[2]*force[2])))
+ if forceLength <= 10000000 {
+ forceLimit := min(float32(10000), 2*totalMass*speed)
+ for axis := range force {
+ if forceLength > forceLimit {
+ force[axis] *= forceLimit / forceLength
+ }
+ follow.velocity[axis] += force[axis] * step / bodyMass
+ }
+ }
+ velocityLength := float32(math.Sqrt(float64(follow.velocity[0]*follow.velocity[0] + follow.velocity[1]*follow.velocity[1] + follow.velocity[2]*follow.velocity[2])))
+ for axis := range position {
+ if velocityLength > speed {
+ follow.velocity[axis] *= speed / velocityLength
+ }
+ if velocityLength > 0.001 {
+ position[axis] += follow.velocity[axis] * step
+ }
+ }
+ }
+ return position
+}
diff --git a/server/player_follow_test.go b/server/player_follow_test.go
@@ -0,0 +1,630 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/hex"
+ "fmt"
+ "math"
+ "net"
+ "testing"
+ "time"
+)
+
+func TestPlayerFollowNativeWorldRequestReachesOwnerAndObserver(t *testing.T) {
+ world := newCheckpointWorld(t)
+ client := connectZoningClient(t, world, true)
+ observer := &combatTestConn{}
+ observerClient := &worldClient{id: 2, target: true, ready: true, conn: observer}
+ world.mutex.Lock()
+ world.newCharacter_locked().playfield = 950
+ world.clients[2] = observerClient
+ world.mutex.Unlock()
+ // Captured /follow: owned subject, selected target, distance2.5, no correction/path.
+ captured, _ := hex.DecodeString("dfdf000a0001003a0000000100000002260f36710000c35000000001010000c350000000024020000000000000000000000000000000000000000000")
+ ping := systemPacket(1, nil)
+ binary.BigEndian.PutUint16(ping[2:4], 11)
+
+ if _, err := client.Write(captured); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.Write(ping); err != nil {
+ t.Fatal(err)
+ }
+ response, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(response[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(response[29:33]) != 78 || binary.BigEndian.Uint32(response[33:37]) != 1500 {
+ t.Fatalf("native follow did not establish carried mass before motion: %x", response)
+ }
+ response, err = readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(response[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(response[29:33]) != 156 || binary.BigEndian.Uint32(response[33:37]) != 5 {
+ t.Fatalf("mass update did not refresh native vehicle with raw RunSpeed: %x", response)
+ }
+ response, err = readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if binary.BigEndian.Uint32(response[16:20]) != 0x260f3671 {
+ t.Fatalf("native /follow was ignored: %x", response)
+ }
+ if response[28] != 0 || !bytes.Equal(response[29:58], captured[29:58]) {
+ t.Fatalf("follow response changed the native target or route fields: %x", response)
+ }
+ pong, err := readPacket(client)
+ if err != nil || binary.BigEndian.Uint16(pong[2:4]) != 11 {
+ t.Fatal("following did not leave a usable world connection", err, pong)
+ }
+ observerClient.mutex.Lock()
+ defer observerClient.mutex.Unlock()
+ if len(observer.packets) != 3 || !bytes.Equal(observer.packets[2][16:58], response[16:58]) {
+ t.Fatalf("observer did not receive the same follow control: %x", observer.packets)
+ }
+}
+
+func playerFollowRequest(target uint32) []byte {
+ request := playerFollowPacket(1, target)[20:65]
+ binary.BigEndian.PutUint32(request[12:], 1)
+ return request
+}
+
+func TestPlayerFollowRejectsUntrustedTargetsAndRoutes(t *testing.T) {
+ for _, scenario := range []string{"short", "long", "foreign owner", "subject type", "target type", "pass-on", "scalar", "control", "correction", "waypoints", "missing target", "dead target", "other zone", "unseen NPC", "offline player", "loading player", "loading owner", "unready owner", "dead owner", "sitting owner", "replaced owner", "unsupported client"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newCombatWorld()
+ player, client := world.characters[1], world.clients[1]
+ target := world.characters[1000000]
+ request := playerFollowRequest(target.id)
+ switch scenario {
+ case "short":
+ request = request[:44]
+ case "long":
+ request = append(request, 0)
+ case "foreign owner":
+ binary.BigEndian.PutUint32(request[8:], 2)
+ case "subject type":
+ binary.BigEndian.PutUint32(request[4:], 51035)
+ case "target type":
+ binary.BigEndian.PutUint32(request[16:], 51035)
+ case "pass-on":
+ binary.BigEndian.PutUint32(request[12:], 0)
+ case "scalar":
+ binary.BigEndian.PutUint32(request[24:], 0x7f800000)
+ case "control":
+ request[28] = 23
+ case "correction":
+ request[29] = 1
+ case "waypoints":
+ binary.BigEndian.PutUint32(request[41:], 1)
+ case "missing target":
+ binary.BigEndian.PutUint32(request[20:], 99)
+ case "dead target":
+ target.health = 0
+ case "other zone":
+ target.playfield = 705
+ case "unseen NPC":
+ delete(client.npcs, target.id)
+ case "offline player":
+ target.npc = false
+ case "loading player":
+ target.npc = false
+ world.clients[target.id] = &worldClient{id: target.id, ready: true, loading: true}
+ case "loading owner":
+ client.loading = true
+ case "unready owner":
+ client.ready = false
+ case "dead owner":
+ player.health = 0
+ case "sitting owner":
+ player.sitting = true
+ case "replaced owner":
+ world.clients[1] = &worldClient{id: 1}
+ case "unsupported client":
+ client.target = false
+ }
+
+ err := world.handlePlayerFollow(client, request)
+
+ if (err != nil) != (scenario == "short" || scenario == "long") || world.characters[client.id].follow != nil || len(output.packets) != 0 {
+ t.Fatal("untrusted follow changed state", err, world.characters[client.id].follow, len(output.packets))
+ }
+ })
+ }
+}
+
+func TestPlayerFollowAcceleratesAndArrivesWithoutNativeMovementSnapshots(t *testing.T) {
+ world, _ := newCombatWorld()
+ player, client := world.characters[1], world.clients[1]
+ world.characters[1000000].position = [3]float32{30, 0, 0}
+ if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ start := world.characters[client.id].follow.updatedAt
+
+ world.advancePlayerFollowing(start.Add(100 * time.Millisecond))
+ first := player.position
+ for tick := 2; tick <= 300; tick++ {
+ world.advancePlayerFollowing(start.Add(time.Duration(tick) * 100 * time.Millisecond))
+ }
+ arrived := player.position
+ world.advancePlayerFollowing(start.Add(31 * time.Second))
+
+ if math.Abs(float64(first[0])-0.03) > 0.000001 || first[1] != 0 || first[2] != 0 {
+ t.Fatal("follow did not use native force-limited acceleration", first)
+ }
+ if arrived[0] < 25.8 || arrived[0] > 26.2 || player.position != arrived || world.characters[client.id].follow == nil || world.characters[client.id].follow.velocity != [3]float32{} {
+ t.Fatal("follow failed to arrive four units short and halt", player.position, world.characters[client.id].follow)
+ }
+ if predictedPosition_locked(player, client, start.Add(time.Hour)) != arrived || math.Abs(float64(player.rotation[1])-math.Sqrt(0.5)) > 0.000001 {
+ t.Fatal("position consumer or heading diverged", player.position, player.rotation)
+ }
+}
+
+func TestPlayerFollowChainsUseOneTargetSnapshot(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{10, 0, 0}}
+ world.clients[2] = &worldClient{id: 2, ready: true, target: true, conn: &combatTestConn{}}
+ if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(2)); err != nil {
+ t.Fatal(err)
+ }
+ request := playerFollowRequest(1)
+ binary.BigEndian.PutUint32(request[8:], 2)
+ if err := world.handlePlayerFollow(world.clients[2], request); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ world.characters[1].follow.updatedAt, world.characters[2].follow.updatedAt = now, now
+
+ world.advancePlayerFollowing(now.Add(100 * time.Millisecond))
+
+ if math.Abs(float64(world.characters[1].position[0])-0.03) > 0.000001 || math.Abs(float64(world.characters[2].position[0])-9.97) > 0.000001 {
+ t.Fatal("cyclic follow depended on map iteration order", world.characters[1].position, world.characters[2].position)
+ }
+}
+
+func TestPlayerFollowTargetLossClearsNativeController(t *testing.T) {
+ for _, scenario := range []string{"despawn", "death", "zone", "interest", "owner death", "owner loading"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newCombatWorld()
+ client := world.clients[1]
+ client.forward = 1
+ if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ switch scenario {
+ case "despawn":
+ delete(world.characters, 1000000)
+ case "death":
+ world.characters[1000000].health = 0
+ case "zone":
+ world.characters[1000000].playfield = 705
+ case "interest":
+ delete(client.npcs, 1000000)
+ case "owner death":
+ world.characters[1].health = 0
+ case "owner loading":
+ client.loading = true
+ }
+
+ now := time.Now()
+ world.advancePlayerFollowing(now)
+ world.advancePlayerFollowing(now.Add(time.Second))
+
+ if world.characters[client.id].follow != nil || client.forward != 0 || len(output.packets) != 5 {
+ t.Fatal("target loss did not clear exactly once", world.characters[client.id].follow, output.packets)
+ }
+ for index, action := range []uint32{2, 4} {
+ packet := output.packets[3+index]
+ if binary.BigEndian.Uint32(packet[16:20]) != 0x54111123 || binary.BigEndian.Uint32(decodeMovement1491(packet[29:])) != action {
+ t.Fatal("target loss did not release both native movement directions", packet)
+ }
+ }
+ if predictedPosition_locked(world.characters[client.id], client, now.Add(2*time.Second)) != world.characters[client.id].position {
+ t.Fatal("target loss retained held forward movement")
+ }
+ })
+ }
+}
+
+func TestPlayerFollowMovementCheckpointsWithoutTickDatabaseWrites(t *testing.T) {
+ world := newCheckpointWorld(t)
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{80, 14, 56}}
+ world.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}}
+ client := &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}}
+ world.clients[1] = client
+ if err := world.handlePlayerFollow(client, playerFollowRequest(2)); err != nil {
+ t.Fatal(err)
+ }
+ start := world.characters[client.id].follow.updatedAt
+ world.characters[1].nextPositionSave = start.Add(20 * time.Second)
+ auditCheckpointWrites(t, world)
+
+ for tick := 1; tick <= 10; tick++ {
+ world.advancePlayerFollowing(start.Add(time.Duration(tick) * 100 * time.Millisecond))
+ }
+ if writes := checkpointWrites(t, world); len(writes) != 0 {
+ t.Fatal("follow tick churned SQLite", writes)
+ }
+ if err := world.flushPositions(start.Add(20 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t).characters[1]
+
+ if restored.position != world.characters[1].position || restored.position[0] <= 52 || checkpointWrites(t, world)["characters/UPDATE"] != 1 {
+ t.Fatal("follow checkpoint failed", restored.position, checkpointWrites(t, world))
+ }
+}
+
+func TestPlayerFollowMouseRotationPreservesControllerAndManualMovementCancels(t *testing.T) {
+ for _, moving := range []bool{false, true} {
+ for _, action := range []byte{1, 2, 3, 4, 9, 20, 22, 23} {
+ t.Run(fmt.Sprintf("%d/moving=%t", action, moving), func(t *testing.T) {
+ world, _ := newEquipmentWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ target := &character{id: 1000000, npc: true, playfield: player.playfield, health: 100, position: player.position}
+ if moving {
+ target.position[0] += 30
+ }
+ world.characters[target.id] = target
+ client.npcs = map[uint32]bool{target.id: true}
+ if err := world.handlePlayerFollow(client, playerFollowRequest(target.id)); err != nil {
+ t.Fatal(err)
+ }
+ follow := player.follow
+ world.advancePlayerFollowing(follow.updatedAt.Add(100 * time.Millisecond))
+ request := append([]byte(nil), npcMovementPacket(player, uint32(action))[20:36]...)
+ request = append(request, encodeMovement1491(npcMovementPacket(player, uint32(action))[36:76])...)
+ if action == 20 {
+ request = mouseMovementRequest()
+ }
+
+ err := world.handleMovement(client, request)
+
+ forward := float32(0)
+ if action == 1 || moving && action != 2 && action != 4 && action != 20 {
+ forward = 1
+ }
+ if action == 3 {
+ forward = -1
+ }
+ if err != nil || (player.follow == follow) != (action == 20) || client.forward != forward {
+ t.Fatal("movement follow cancellation or throttle", action, err, player.follow, client.forward, forward)
+ }
+ })
+ }
+ }
+}
+
+func TestPlayerFollowRootSuspendsAndResumesController(t *testing.T) {
+ world, _ := newCombatWorld()
+ player, client := world.characters[1], world.clients[1]
+ world.characters[1000000].position = [3]float32{30, 0, 0}
+ if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ now := world.characters[client.id].follow.updatedAt
+ player.activeNanos = []activeNano{{program: 42110}}
+
+ world.advancePlayerFollowing(now.Add(100 * time.Millisecond))
+ rooted := player.position
+ player.activeNanos = nil
+ world.advancePlayerFollowing(now.Add(200 * time.Millisecond))
+
+ if rooted != [3]float32{} || math.Abs(float64(player.position[0])-0.03) > 0.000001 || world.characters[client.id].follow == nil {
+ t.Fatal("root did not suspend and resume following", rooted, player.position, world.characters[client.id].follow)
+ }
+}
+
+func TestPlayerFollowLateObserverGetsControllerAfterBothActorSnapshots(t *testing.T) {
+ world := newCheckpointWorld(t)
+ world.characters[1000000] = &character{id: 1000000, npc: true, name: "Target", appearance: 229, level: 1, playfield: 950, health: 100, position: [3]float32{70, 14, 56}}
+ world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000000: true}}
+ if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ world.newCharacter().playfield = 950
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0})
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ cookie = append(cookie, targetPacket(n3Packet(0x570c2039, 50000, 2, nil))...)
+ address, peer := net.Pipe()
+ defer address.Close()
+ defer peer.Close()
+ connection := &combatInterestConn{combatTestConn: combatTestConn{Conn: address}, input: bytes.NewReader(cookie)}
+
+ if err := world.serveWorldClient(&worldClient{conn: connection, loading: true}); err != nil {
+ t.Fatal(err)
+ }
+
+ var controls int
+ actors := make(map[uint32]bool)
+ for _, packet := range connection.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x271b3a6b {
+ actors[binary.BigEndian.Uint32(packet[24:28])] = true
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x260f3671 {
+ controls++
+ if !actors[1] || !actors[1000000] || binary.BigEndian.Uint32(packet[24:28]) != 1 || binary.BigEndian.Uint32(packet[33:37]) != 1000000 || math.Float32frombits(binary.BigEndian.Uint32(packet[42:])) != 52 {
+ t.Fatal("wrong follow replay", packet)
+ }
+ }
+ }
+ if controls != 2 {
+ t.Fatal("late observer follow replay count", controls)
+ }
+}
+
+func TestPlayerFollowIntegratorRetainsMassForceCapAndStallLimit(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ seconds float64
+ bodyMass, totalMass float32
+ want float32
+ }{
+ {"body force", .1, 10, 10, .03},
+ {"carried force", .1, 10, 20, .06},
+ {"force ceiling", .1, 10000, 10000, .01},
+ {"long stall", 4.0001, 10, 10, 0},
+ {"zero interval", 0, 10, 10, 0},
+ {"negative interval", -.1, 10, 10, 0},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ follow := &playerFollow{}
+
+ position := follow.advance([3]float32{}, [3]float32{30, 0, 0}, scenario.seconds, 1.5, scenario.bodyMass, scenario.totalMass)
+
+ if math.Abs(float64(position[0]-scenario.want)) > .000001 {
+ t.Fatal("native force/stall boundary", position, scenario.want)
+ }
+ })
+ }
+}
+
+func TestPlayerFollowMassUsesNativeBreedSexAndCarriedSlots(t *testing.T) {
+ for _, scenario := range []struct {
+ breed, sex uint16
+ mass float32
+ }{
+ {1, 2, .08}, {1, 3, .07}, {2, 2, .075}, {2, 3, .065}, {3, 2, .075}, {3, 3, .06}, {4, 1, .1},
+ } {
+ t.Run(fmt.Sprintf("%d/%d", scenario.breed, scenario.sex), func(t *testing.T) {
+ player := &character{appearance: (appearanceFields{Breed: scenario.breed, Sex: scenario.sex}).packed()}
+ player.inventory.Items = []ownedItem{
+ {Type: 51018, Template: 121567, Quality: 1, Slot: 64, Count: 1},
+ {Type: 51018, Template: 121567, Quality: 1, Slot: 6, Count: 1},
+ {Type: 51017, Template: 206730, Quality: 50, Slot: 65, Count: 1},
+ }
+ player.inventory.Bank = []ownedItem{{Type: 51018, Template: 121567, Slot: 0, Count: 1}}
+
+ body, carried := player.followMass()
+
+ if math.Abs(float64(body-scenario.mass)) > .000001 || carried != 1500 {
+ t.Fatal("native mass included equipment/bank/Chest or lost carried item", body, carried)
+ }
+ })
+ }
+}
+
+func TestPlayerFollowArrivalToleranceAndCrossing(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ target, previous, want float32
+ }{
+ {"inside offset", 3, 0, 0}, {"offset", 4, 0, 0}, {"inside tolerance", 4.125, 0, 0},
+ {"outside tolerance", 4.25, 0, .03}, {"crossed goal", 10, 7, 0},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ follow := &playerFollow{previousPosition: [3]float32{scenario.previous, 0, 0}}
+
+ position := follow.advance([3]float32{}, [3]float32{scenario.target, 0, 0}, .1, 1.5, 10, 10)
+
+ if math.Abs(float64(position[0]-scenario.want)) > .000001 {
+ t.Fatal("native arrival boundary", position, scenario.want)
+ }
+ })
+ }
+}
+
+func TestPlayerFollowMotionInterruptsCastAndRefundsReservation(t *testing.T) {
+ world, _ := newNanoCastingWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ world.characters[1000000].position = [3]float32{15, 0, 0}
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if client.nanoCast == nil {
+ t.Fatal("cast was not admitted")
+ }
+ if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ now := world.characters[client.id].follow.updatedAt
+
+ world.advancePlayerFollowing(now.Add(100 * time.Millisecond))
+
+ if client.nanoCast != nil || player.nanoReserved != 0 || player.nano != 30 || player.position[0] <= 0 {
+ t.Fatal("follow retained cast or lost reservation", client.nanoCast, player.nanoReserved, player.nano, player.position)
+ }
+}
+
+func TestPlayerFollowRetargetingPreservesVelocity(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.characters[1000000].position = [3]float32{30, 0, 0}
+ client := world.clients[1]
+ if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ world.advancePlayerFollowing(world.characters[client.id].follow.updatedAt.Add(100 * time.Millisecond))
+ velocity := world.characters[client.id].follow.velocity
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}}
+
+ err := world.handlePlayerFollow(client, playerFollowRequest(2))
+
+ if err != nil || world.characters[client.id].follow.target != 2 || world.characters[client.id].follow.velocity != velocity {
+ t.Fatal("retarget reset native motion", err, world.characters[client.id].follow)
+ }
+}
+
+func TestPlayerFollowSnapshotIncludesVelocityBeforeLateReplay(t *testing.T) {
+ world, _ := newCombatWorld()
+ player := world.characters[1]
+ player.name, player.appearance = "Follower", 0x315
+ world.characters[1000000].position = [3]float32{30, 0, 0}
+ if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ world.advancePlayerFollowing(player.follow.updatedAt.Add(100 * time.Millisecond))
+
+ packet := characterPacket(player)
+
+ // The variable name is followed by 20 auxiliary/ability bytes, level and 14 bases.
+ vehicleOffset := 71 + len(player.name) + 20 + 1 + 14
+ if binary.BigEndian.Uint32(packet[vehicleOffset:]) != 42 || math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(packet[vehicleOffset+4:])))-.3) > .000001 || packet[vehicleOffset+17] != 3 || packet[vehicleOffset+18] != 1 || binary.BigEndian.Uint32(packet[vehicleOffset+30:]) != 0x3f800000 || !bytes.Equal(packet[vehicleOffset+34:vehicleOffset+46], make([]byte, 12)) {
+ t.Fatal("late actor snapshot lost follow velocity", vehicleOffset, packet, player.follow.velocity)
+ }
+}
+
+func TestPlayerFollowChecksTradeRangeAfterBothTradersMove(t *testing.T) {
+ world, _ := newCombatWorld()
+ world.characters[1000000].position = [3]float32{0, 0, 30}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{4.99999, 0, 0}}
+ world.characters[1000001] = &character{id: 1000001, npc: true, playfield: 950, health: 100, position: [3]float32{4.99999, 0, 30}}
+ world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000001: true}}
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ if world.clients[1].trade == nil {
+ t.Fatal("trade was not admitted")
+ }
+ if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ request := playerFollowRequest(1000001)
+ binary.BigEndian.PutUint32(request[8:], 2)
+ if err := world.handlePlayerFollow(world.clients[2], request); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ world.characters[1].follow.updatedAt, world.characters[2].follow.updatedAt = now, now
+
+ world.advancePlayerFollowing(now.Add(100 * time.Millisecond))
+
+ if world.clients[1].trade == nil || world.clients[1].trade != world.clients[2].trade || world.characters[1].position[2] != world.characters[2].position[2] || world.characters[1].position[2] == 0 {
+ t.Fatal("partial follow frame cancelled an in-range trade", world.characters[1].position, world.characters[2].position)
+ }
+}
+
+func TestPlayerFollowRunningStartUsesNativeRestThenForwardParameters(t *testing.T) {
+ world, _ := newCombatWorld()
+ player := world.characters[1]
+ player.running = true
+ player.stats.Speed.RunSpeed = 10
+ world.characters[1000000].position = [3]float32{30, 0, 0}
+ if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ now := player.follow.updatedAt
+
+ world.advancePlayerFollowing(now.Add(100 * time.Millisecond))
+ first := player.position[0]
+ world.advancePlayerFollowing(now.Add(200 * time.Millisecond))
+
+ if math.Abs(float64(first)-.0607) > .000001 || math.Abs(float64(player.position[0])-.2024) > .000001 {
+ t.Fatal("native follow start did not switch its movement parameters", first, player.position)
+ }
+}
+
+func TestLateObserverRestoresHeldPlayerInputAndCurrentPose(t *testing.T) {
+ for _, scenario := range []struct {
+ forward float32
+ action uint32
+ z float32
+ }{{1, 1, 86}, {-1, 3, 26}} {
+ t.Run(fmt.Sprint(scenario.forward), func(t *testing.T) {
+ world := newCheckpointWorld(t)
+ world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}, forward: scenario.forward, movementStarted: time.Now().Add(-30 * time.Second)}
+ world.newCharacter().playfield = 950
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0})
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ cookie = append(cookie, targetPacket(n3Packet(0x570c2039, 50000, 2, nil))...)
+ address, peer := net.Pipe()
+ defer address.Close()
+ defer peer.Close()
+ connection := &combatInterestConn{combatTestConn: combatTestConn{Conn: address}, input: bytes.NewReader(cookie)}
+
+ if err := world.serveWorldClient(&worldClient{conn: connection, loading: true}); err != nil {
+ t.Fatal(err)
+ }
+
+ var controls int
+ for _, packet := range connection.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x54111123 && binary.BigEndian.Uint32(packet[24:28]) == 1 {
+ controls++
+ body := decodeMovement1491(packet[29:])
+ if binary.BigEndian.Uint32(body) != scenario.action || math.Float32frombits(binary.BigEndian.Uint32(body[12:])) != scenario.z {
+ t.Fatal("late observer lost held input or pose", packet)
+ }
+ }
+ }
+ if controls != 2 {
+ t.Fatal("initial and ready movement replay", controls)
+ }
+ })
+ }
+}
+
+func TestPlayerFollowStationaryTerrainDoesNotInterruptCast(t *testing.T) {
+ world, _ := newNanoCastingWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ var err error
+ world.terrain, err = readTerrain()
+ if err != nil {
+ t.Fatal(err)
+ }
+ player.playfield, player.position = 705, [3]float32{960.625, 16.5, 510.625}
+ target := world.characters[1000000]
+ target.playfield, target.position = 705, [3]float32{961, 16.5, 511}
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 29618})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ cast := client.nanoCast
+ if cast == nil {
+ t.Fatal("cast was not admitted")
+ }
+ if err := world.handlePlayerFollow(client, playerFollowRequest(target.id)); err != nil {
+ t.Fatal(err)
+ }
+
+ world.advancePlayerFollowing(player.follow.updatedAt.Add(100 * time.Millisecond))
+
+ if player.position != [3]float32{960.625, 16.5, 510.625} || client.nanoCast != cast || player.nanoReserved != 9 {
+ t.Fatal("stationary terrain projection moved the actor or cancelled its cast", player.position, client.nanoCast, player.nanoReserved)
+ }
+}
+
+func TestPlayerFollowCastAdmissionUsesActualMotion(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ distance float32
+ reserved uint32
+ }{{"stationary", 3, 9}, {"moving", 15, 0}} {
+ t.Run(scenario.name, func(t *testing.T) {
+ world, _ := newNanoCastingWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ world.characters[1000000].position = [3]float32{scenario.distance, 0, 0}
+ if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
+ t.Fatal(err)
+ }
+ world.advancePlayerFollowing(player.follow.updatedAt.Add(100 * time.Millisecond))
+
+ err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:])
+
+ if err != nil || player.nanoReserved != scenario.reserved || player.nano != 30-scenario.reserved || (client.nanoCast != nil) != (scenario.reserved != 0) {
+ t.Fatal("cast admission ignored automatic motion", err, player.nano, player.nanoReserved, client.nanoCast)
+ }
+ })
+ }
+}
diff --git a/server/state.go b/server/state.go
@@ -41,6 +41,7 @@ type character struct {
nextAttack time.Time
rechargeUntil time.Time
running bool
+ follow *playerFollow
returnDoor *doorOrigin
npc bool
npcDefinitionID string
diff --git a/server/world.go b/server/world.go
@@ -112,9 +112,24 @@ func characterPacket(character *character) []byte {
body = binary.BigEndian.AppendUint32(body, value)
}
body = binary.BigEndian.AppendUint16(body, character.baseScale())
- // Stationary velocity, movement commands, control state, and empty path.
- vehicle := make([]byte, 28)
+ // KKR CharVehicle 49220 reads 26 bytes; Player 4bdb0 adds four control floats,
+ // while NPC 4b4d0 adds a short waypoint count. An empty player buffer is 42 bytes.
+ vehicleSize := 42
+ if character.npc {
+ vehicleSize = 28
+ }
+ vehicle := make([]byte, vehicleSize)
+ if character.follow != nil {
+ for axis, velocity := range character.follow.velocity {
+ binary.BigEndian.PutUint32(vehicle[axis*4:], math.Float32bits(velocity))
+ }
+ }
copy(vehicle[12:22], []byte{2, 1, 0, 1, 0, 1, 0, 1, 0, 1})
+ if character.follow != nil && character.follow.velocity != [3]float32{} {
+ vehicle[13] = 3
+ vehicle[14] = 1
+ binary.BigEndian.PutUint32(vehicle[26:30], math.Float32bits(1))
+ }
if character.running {
vehicle[12] = 3
}
diff --git a/server/world_actions.go b/server/world_actions.go
@@ -39,8 +39,11 @@ func (server *server) handleCharacterReady(client *worldClient) error {
var replay [][]byte
var team [][]byte
var death []byte
+ var motion [][]byte
resources := make(map[*worldClient][][]byte)
if client.loading {
+ motion = server.playerMovementReplay_locked(client, time.Now())
+ motion = append(motion, server.playerFollowReplay_locked(client, nil)...)
replay = playerCombatStatPackets(server.characters[client.id])
replay = append(replay, equippedItemPackets(server.characters[client.id])...)
replay = append(replay, activeNanoPackets(server.characters[client.id], time.Now())...)
@@ -69,6 +72,11 @@ func (server *server) handleCharacterReady(client *worldClient) error {
if err := client.send(response); err != nil {
return err
}
+ for _, packet := range motion {
+ if err := client.send(packet); err != nil {
+ return err
+ }
+ }
if death != nil {
server.broadcast(playfield, client.id, death)
return client.send(death)
@@ -130,7 +138,16 @@ func (server *server) handleMovement(client *worldClient, body []byte) error {
}
playfield := character.playfield
client.movementStarted = time.Now()
- switch binary.BigEndian.Uint32(body[16:20]) {
+ action := binary.BigEndian.Uint32(body[16:20])
+ if character.follow != nil && action != 20 {
+ // Native cancellation retains automatic throttle until a linear stop event.
+ client.forward = 0
+ if character.follow.velocity != [3]float32{} {
+ client.forward = 1
+ }
+ character.follow = nil
+ }
+ switch action {
case 1:
client.forward = 1
case 3:
@@ -156,7 +173,10 @@ func (server *server) handleMovement(client *worldClient, body []byte) error {
if client.bank != nil && !server.bankAvailable_locked(client) {
updates[client] = append(updates[client], characterActionPacket(client.id, [5]uint32{106}))
}
- action := binary.BigEndian.Uint32(body[16:20])
+ if character.follow != nil {
+ character.follow.previousPosition = character.position
+ character.follow.updatedAt = client.movementStarted
+ }
if character.position != previousPosition || action == 1 || action == 3 || action == 5 || action == 7 || action == 13 {
server.abortNano_locked(client, client.movementStarted, updates)
}
diff --git a/server/zoning.go b/server/zoning.go
@@ -206,11 +206,10 @@ func (server *server) advanceZoneCrossings(now time.Time) {
server.updateMutex.Lock()
defer server.updateMutex.Unlock()
// The native client sends start/stop controls rather than every walking frame.
- // Predict only trigger checks; received coordinates remain authoritative.
server.mutex.Lock()
var destinations []userData
for id, client := range server.clients {
- if !client.ready || client.loading || client.forward == 0 {
+ if !client.ready || client.loading || client.forward == 0 && server.characters[id].follow == nil {
continue
}
character := *server.characters[id]
@@ -231,6 +230,9 @@ func (server *server) advanceZoneCrossings(now time.Time) {
}
func predictedPosition_locked(character *character, client *worldClient, now time.Time) [3]float32 {
+ if character.follow != nil {
+ return character.position
+ }
// Reuse the same bounded movement estimate for portal checks and the web map.
seconds := math.Min(now.Sub(client.movementStarted).Seconds(), 20)
speed := float32(1.5)