commit 9ba4cc13b2b682c7718fd1f69810057414ac6921 parent a8f131ffe4064d7639865a9e04c6dc9f4dd36fe8 Author: anon <anon@example.com> Date: Mon, 26 Oct 2026 07:23:27 +0000 Simulate shared native player movement and restore reverse observers Advance held forward/reverse, strafe, turn and follow motion through shared transient vehicle state. Preserve native acceleration, cached controls, component gates and pose anchoring, and use current motion for ranges, checkpoints and player snapshots. Initialize late reverse observers through the native direction transition and document its acceleration limitation. Validated 1,211 top-level server tests (13,994 results), 18 data tests, 143 focused race results and go vet. Two hardware WASM clients verify long strafe, a 35-second moving-target follow, controls and reverse late joins. Diffstat:
51 files changed, 1237 insertions(+), 552 deletions(-)
diff --git a/TODO.md b/TODO.md @@ -1185,17 +1185,27 @@ disconnect retention and succession policy still need period corroboration. Maintained source binds full signed longitudinal force, separate strafe displacement, cached turn rates, input gates, pose anchoring and body heading. Hardware verifies nine control combinations and the engine's occasional - action20 updates. A 25-second pure strafe moves 50.30 units while the current - server map stays at its starting position, with no action20 during the hold. + action20 updates. A baseline 25-second pure strafe moved 50.30 units while the + server map stayed at its starting position, with no action20 during the hold. See [native player movement](docs/player-movement.md). -- [ ] Replace the shared held-input estimate with native player simulation. - Reuse the vehicle integrator with distinct forward, follow, strafe and turn - controllers. Preserve acceleration, stop/reversal gates, cached controls, - angular order, pose-correction realignment and actual snapshot component state. - Cover long forward/strafe motion, reverse-to-follow, simultaneous controls, - speed/stat changes, roots/death/loading, interaction ranges, late observers - and periodic pose checkpoints without per-tick DB churn. Keep scene collision, - flight/water and other orientation modes explicit until implemented and tested. +- [x] Replace the shared held-input estimate with open-ground player simulation. + One integrator serves distinct forward/follow controllers, with independent + strafe and angular motion. Preserve acceleration, stop/reversal gates, cached + controls, angular order, pose-correction realignment and snapshot history. + Regressions cover long forward/reverse/strafe, reverse-to-follow, simultaneous + controls, parameter changes, roots/death/loading, ranges and periodic pose + checkpoints without tick DB churn. Hardware verifies short controls and a + roughly 50-unit strafe with server/client horizontal difference below 0.07 units. + A 35-second moving-target follow stays within 0.11 units horizontally; final + follower difference is 0.022 units. Native late reverse initialization and final + stop are verified separately. +- [ ] Complete native player geometry and movement modes. Recover scene collision, + surface projection, slopes, falling, flight/water, platforms and nonzero + orientation modes. Establish live Chest contents mass and encumbrance policy. + Expand combined lifecycle/interaction tests. Investigate lossless late reverse + initialization: native snapshots omit retained direction; the accepted reverse + transition fixes facing and stopping but necessarily restarts acceleration. + See [native player movement](docs/player-movement.md) for the evidence boundary. - [x] Audit compact actor-spawn Run Speed. Send trained stat 156 as an unsigned byte through 255 or a flagged short above it, preserving following materials. Two GPU WASM clients verified training across 255, separate equipment/nano @@ -1562,11 +1572,11 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah - [ ] 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. Use the shared simulation tracked under - Travel so long-held and strafing targets have current authoritative poses; - [native player movement](docs/player-movement.md) records the current failures - and the engine's sparse action20 correction policy. - Recover retained backward-direction steering when activating follow after - reverse movement; the current controller covers positive-direction following. + Travel for geometry and movement modes. Long-held and strafing targets now + have current authoritative poses; [native player movement](docs/player-movement.md) + records the shared simulation and sparse action20 correction policy. + Retained backward-direction follow and matching arrival stop have regressions; + expand their owner/observer hardware and combined lifecycle coverage. 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 diff --git a/docs/player-follow.md b/docs/player-follow.md @@ -61,15 +61,16 @@ 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 +and refreshes it when an active player'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 +Native physical start invokes PlayerVehicle 360481a0 and the signed movement +event:1 for retained positive direction,3 for negative. Arrival Halt invokes +3604bc80/360481d0 and matching stop2 or4, restoring helper1/0 and zero throttle. +Reverse stop also restores positive direction. 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 @@ -93,23 +94,21 @@ 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. -In a longer walking capture, the target sends an automatic action20 after about -21 seconds. The map prediction stops for 0.884 seconds at its horizon while the -native target travels another 1.324 units, then resumes from the correction. -This capture establishes a brief prediction freeze, not permanent target loss. -Retaining native backward-direction steering when follow starts after reverse -movement also remains outside the current positive-direction controller. +The shared [player simulation](player-movement.md) advances held longitudinal, +strafe and turn controls without the former 20-second prediction horizon. +Following a moving player therefore uses its current authoritative pose between +sparse native action20 corrections. Reverse-to-follow retains negative direction +and body heading until arrival, with a regression for the matching stop4. +Late reverse observers require native direction initialization before follow; +the accepted transition briefly restarts acceleration, as documented there. ## 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 +walking route lasts 19 seconds. This evidence predates the shared player +simulation; 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. diff --git a/docs/player-movement.md b/docs/player-movement.md @@ -1,12 +1,11 @@ # Native player movement -The server still uses a bounded, instant-speed estimate for ordinary held input. -Replacing it requires the shared native vehicle integrator with distinct -longitudinal, arrival, lateral and angular controllers. Combining all controls -into a normalized desired direction would change the original behavior. -[Player following](player-follow.md) implements only its current documented -subset. This document records the wider contract for the shared replacement; -it does not claim that replacement is implemented. +The server advances player motion in memory at 60Hz with one force/velocity +integrator and distinct longitudinal, arrival, lateral and angular controllers. +Ordinary input and [player following](player-follow.md) share this state. +Strafing and turning continue without pose packets; held input has no age cap. +The implementation covers ordinary open-ground motion. Native scene collision, +surface projection, falling, swimming and full flight remain separate TODOs. ## Ordinary ground motion @@ -112,14 +111,14 @@ separate lateral displacement. Pure flat-ground strafe with zero residual longitudinal velocity can move while cached speed remains zero, so the automatic pose-update gate does not establish periodic updates for every moving player. -A 35-second hardware walking capture sends a forward start, one automatic +A baseline 35-second hardware walking capture sends a forward start, one automatic ordinary action20 at 20.982 seconds, then a forward stop. The follower also sends an ordinary action20. During the target's 20-second server prediction horizon, the public map remains unchanged for 0.884 seconds while the native target moves 1.324 units, then resumes after the correction. This demonstrates a brief cap freeze, not permanent loss of target motion in that run. -A separate 25-second pure right-strafe capture covers 50.301 units on the verified +A baseline 25-second pure right-strafe capture covers 50.301 units on the verified flat route while native longitudinal velocity stays exactly zero. The server map remains at the start until release. Its wire stream contains only strafe start5 and stop6, with no action20 during the hold. Removing the forward predictor's @@ -165,7 +164,7 @@ bodies respectively; overlapping functions are not unique additional procedures. reverse-direction probe, long strafe and walking-cap measurements. Page-error logs are empty. All three owned players are removed after closing their clients; unrelated SQLite rows are hashed unchanged and foreign-key/integrity checks pass. -The sole HTTPS8443 preview keeps its existing executable for this research pass. +Those baseline measurements precede the shared server simulation. The 42-byte PlayerVehicle snapshot must retain actual velocity, all ten helper bytes, preferred mode and four cached controls. Some helper fields depend on @@ -173,10 +172,64 @@ command history; resetting unrelated bytes to constructor defaults does not reproduce the native writer. Initial spawn and readiness replay must represent both ordinary motion and follow targets consistently. -The shared implementation remains an open TODO. Verify acceleration and steady -motion beyond 20 seconds, forward/reverse switches and releases, independent and -combined strafe/turn, changed speed while moving, pose corrections and follow -transitions. Include repeated starts, wrong releases, roots/death/loading, -late observers, active range-dependent interactions, and checkpoint/restart -without per-tick database writes. Reuse the integrator while preserving each -controller's actual force, cached parameters and transition rules. +## Authoritative simulation + +`server/player_movement.go` owns transient velocity, previous position, retained +direction, cached controls and component history. The server advances ordinary +inputs first, snapshots follow targets, then advances followers so chains and +cycles use consistent target positions. Maps, portals and interaction ranges +read this same state. Stat and equipment changes anchor the previous motion +before applying new movement parameters. Routine motion does not write SQLite; +the existing periodic checkpoint persists pose, and cold loading starts neutral. + +Regression tests cover initial acceleration, forward/reverse movement beyond +20 seconds, independent lateral displacement, simultaneous controls, stationary +turns, matching and mismatched releases, cached rate changes, pose corrections, +reverse-to-follow arrival, loading/death/root handling and existing resource and +range consumers. Checkpoint auditing verifies no per-tick writes and one durable +pose update. Player snapshots retain all ten actual helper bytes and four cached +controls; neutral defaults cannot reconstruct command history. + +### Late reverse observers + +The native PlayerVehicle reader restores reverse subtype2 and signed throttle, +but omits QQR retained direction. Its constructor starts positive. An action3 +replay alone can reject because the helper already represents reverse; native +physical-start callbacks can subsequently install forward helper state. A +hardware late join reproduces forward travel and rejection of the owner's stop4. + +Replay now sends ordinary stop4, start3, then current pose20 before any follow +controller. This admits the native SetDirection(-1) callback whether the helper +still holds reverse or has become forward. Cached lateral and angular controls +remain intact. The accepted reverse transition necessarily Halts: a late observer +briefly accelerates from rest instead of retaining exact velocity. The snapshot +contains no direction field and a lossless original-server sequence has not been +established. Source-only evidence is retained in +`local/player-movement-research/reverse-replay/`; it verifies64 complete bodies, +the creation/reader chain and all retained direct direction setters. + +Implementation evidence, automated logs and hardware captures are retained in +`local/player-movement-implementation/`. Nine short control exercises match the +native cached values, with sampled horizontal server/client differences below +0.14 units. A final 25-second, roughly 50-unit strafe has a sampled difference +below 0.07 units, rather than a frozen map. A 35-second moving-target follow +exercise samples 36.6 seconds with maximum target/follower horizontal differences +below 0.11 units and final follower difference 0.022 units. Its target sends start1, +one periodic correction20 and stop2. Reverse late-join retesting verifies +negative direction, reverse throttle and the final neutral stop. Timing, native +frame cadence, compact pose quantization and collision remain comparison bounds; +these measurements do not establish float-bit equivalence. + +Owned clients and test players118/119 are removed after testing. Cleanup hashes +all unrelated SQLite rows unchanged and verifies foreign keys and integrity; +the single LAN HTTPS8443 preview serves the final movement executable. + +The final Go code passes all 1,211 top-level server tests +(13,994 results), 18 data tests, 143 focused race results and `go vet`. +`exact-suite-manifest.json` records complete root coverage and source hashes; +`verification.json` links these checks to runtime, preview and cleanup evidence. + +Complete scene geometry, slopes, gravity, flight/water, platforms and nonzero +orientation modes remain open. Establish live Chest contents mass and the +encumbrance flag before adding policies for them. Expand the combined lifecycle +matrix and investigate a lossless late reverse initialization only with evidence. diff --git a/docs/server-action-coverage.md b/docs/server-action-coverage.md @@ -65,7 +65,10 @@ packet finally reported a 12.1-unit change. It is retained as research, with 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 +the server advances with both clients. Ordinary held movement now shares the +authoritative integrator, including separate strafe/turn controls and retained +reverse direction. A 35-second moving-target follow remains within 0.11 units +horizontally of the two native clients. Complete scene collision/terrain/flight and the distinct exported action29 path remain unchecked tasks; see [player following](player-follow.md). diff --git a/server/ability_nano_test.go b/server/ability_nano_test.go @@ -181,7 +181,8 @@ func TestAbilityNanoAnchorsWoundedRecipientsHeldMovement(t *testing.T) { recipient.id, recipient.name, recipient.health, recipient.running = 2, "Recipient", 4, true recipient.position, recipient.rotation = [3]float32{0, 0, 3}, [4]float32{0, 0, 0, 1} world.characters[2], world.nextCharacter = &recipient, 2 - world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true, forward: 1, movementStarted: time.Now()} + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true} + world.characters[2].movement = heldPlayerMovement(world.characters[2], 1, time.Now()) if err := world.saveUser_locked(&recipient); err != nil { t.Fatal(err) } @@ -189,12 +190,12 @@ func TestAbilityNanoAnchorsWoundedRecipientsHeldMovement(t *testing.T) { t.Fatal(err) } at := world.clients[1].nanoCast.readyAt.Add(time.Nanosecond) - world.clients[2].movementStarted = at.Add(-time.Second) + world.characters[2].movement.updatedAt = at.Add(-time.Second) world.advanceNanos(at) - position := predictedPosition_locked(&recipient, world.clients[2], at.Add(time.Second)) + position := predictedPosition_locked(&recipient, at.Add(time.Second)) - if recipient.maximumHealth() != 46 || world.clients[2].movementStarted != at || recipient.position[2] < 6.661 || recipient.position[2] > 6.663 || + if recipient.maximumHealth() != 46 || world.characters[2].movement.updatedAt != at || recipient.position[2] < 6.661 || recipient.position[2] > 6.663 || position[2] < 9.900 || position[2] > 9.903 { t.Fatal("ability buff repriced the earlier wounded movement segment", recipient.position, position) } diff --git a/server/backpack_effects_test.go b/server/backpack_effects_test.go @@ -178,20 +178,20 @@ func TestBackpackSpeedChangeAnchorsHeldMovement(t *testing.T) { t.Fatal("Speeder wear rejected") } finish := client.equipment.readyAt - client.forward, client.movementStarted = 1, finish.Add(-2*time.Second) + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, finish.Add(-2*time.Second)) world.advanceEquipment(finish) - if player.position != [3]float32{0, 0, 9} || client.movementStarted != finish || player.inventory.equipmentBonus(156) != 24 { + if player.position != [3]float32{0, 0, 9} || world.characters[client.id].movement.updatedAt != finish || player.inventory.equipmentBonus(156) != 24 { t.Fatal("wear retroactively applied the new movement speed") } world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]) finish = client.equipment.readyAt - client.movementStarted = finish.Add(-2 * time.Second) + world.characters[client.id].movement.updatedAt = finish.Add(-2 * time.Second) world.advanceEquipment(finish) - if math.Abs(float64(player.position[2])-18.24) > 0.00001 || client.movementStarted != finish || player.inventory.equipmentBonus(156) != 0 { + if math.Abs(float64(player.position[2])-18.24) > 0.00001 || world.characters[client.id].movement.updatedAt != finish || player.inventory.equipmentBonus(156) != 0 { t.Fatal("removal retroactively applied the old movement speed") } } diff --git a/server/bank.go b/server/bank.go @@ -58,7 +58,7 @@ func (server *server) bankAvailable_locked(client *worldClient) bool { return false } player := server.characters[client.id] - position := predictedPosition_locked(player, client, time.Now()) + position := predictedPosition_locked(player, time.Now()) x, y, z := position[0]-client.bank.position[0], position[1]-client.bank.position[1], position[2]-client.bank.position[2] if player.playfield != client.bank.playfield || x*x+y*y+z*z > 25 { client.bank = nil @@ -89,7 +89,7 @@ func (server *server) handleBankUse(client *worldClient, body []byte) error { } client.useSequence = sequence terminal, exists := gamedata.BankTerminals[binary.BigEndian.Uint32(body[44:48])] - position := predictedPosition_locked(player, client, time.Now()) + position := predictedPosition_locked(player, time.Now()) x, y, z := position[0]-terminal.Position[0], position[1]-terminal.Position[1], position[2]-terminal.Position[2] accepted := exists && player.playfield == terminal.Playfield && x*x+y*y+z*z <= 25 && client.equipment == nil && client.trade == nil reply := append([]byte(nil), body[16:]...) @@ -131,7 +131,7 @@ func (server *server) openBank_locked(client *worldClient) error { return err } } - client.bank = &bankSession{player.playfield, predictedPosition_locked(player, client, time.Now())} + client.bank = &bankSession{player.playfield, predictedPosition_locked(player, time.Now())} for _, item := range player.inventory.Bank { if item.isPortableContainer() { if err := client.send(backpackPacket(client.id, player.playfield, item, 105)); err != nil { diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go @@ -455,7 +455,7 @@ func TestExpiredBrowserWorldSessionRemovesLivingTargetAndRetargetsNPC(t *testing if err != nil || binary.BigEndian.Uint32(ready[20:24]) != 0x570c2039 { t.Fatalf("observer did not receive browser player readiness: %x %v", ready, err) } - for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51} { + for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51, 78, 156} { packet, err := readPacket(observer) if err != nil || binary.BigEndian.Uint32(packet[20:24]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[28:32]) != 2 || binary.BigEndian.Uint32(packet[36:40]) != stat { t.Fatalf("observer did not receive player combat foundations: %x %v", packet, err) diff --git a/server/combat.go b/server/combat.go @@ -267,10 +267,10 @@ func (character *character) physicalExtent() float32 { func (server *server) combatInRange_locked(attacker, target *character, now time.Time) bool { first, second := attacker.position, target.position if !attacker.npc { - first = predictedPosition_locked(attacker, server.clients[attacker.id], now) + first = predictedPosition_locked(attacker, now) } if !target.npc { - second = predictedPosition_locked(target, server.clients[target.id], now) + second = predictedPosition_locked(target, now) } x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] itemRange := int32(2) @@ -511,8 +511,9 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr if !target.npc { client := server.clients[target.id] server.cancelPlayerTrade_locked(client) - target.position = predictedPosition_locked(&previous, client, now) - client.forward = 0 + target.position = predictedPosition_locked(&previous, now) + target.followTarget = 0 + target.movement = playerMovement{} client.reclaimItems = nil client.bank = nil client.backpacks = nil diff --git a/server/combat_test.go b/server/combat_test.go @@ -145,9 +145,12 @@ func TestCombatRangeUsesPredictedPlayerPosition(t *testing.T) { world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) first := world.characters[1].nextAttack world.characters[1].rotation = [4]float32{0, 0, 0, 1} - world.clients[1].forward = 1 - world.clients[1].movementStarted = first.Add(-8 * time.Second) + started := first.Add(-8 * time.Second) + world.characters[1].movement = heldPlayerMovement(world.characters[1], 1, started) + for frame := 1; frame <= 80; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } world.advanceCombat(first) if len(world.fighting) != 0 || world.characters[1000000].health != 100 { @@ -255,14 +258,13 @@ func TestCombatPlayerDeathStopsMovementAndFurtherAttacks(t *testing.T) { world.advanceCombat(first) world.characters[1].health = 3 world.characters[1].rotation = [4]float32{0, 0, 0, 1} - world.clients[1].forward = 1 - world.clients[1].movementStarted = first + world.characters[1].movement = heldPlayerMovement(world.characters[1], 1, first) world.advanceCombat(first.Add(time.Second)) world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) world.advanceCombat(first.Add(time.Hour)) - if world.characters[1].health != 0 || world.clients[1].forward != 0 || world.characters[1].position != [3]float32{0, 0, 1.5} || len(world.fighting) != 0 { + if world.characters[1].health != 0 || world.characters[1].movement.forward != 0 || world.characters[1].position != [3]float32{0, 0, 1.5} || len(world.fighting) != 0 { t.Fatal("dead player kept moving or fighting") } if hex.EncodeToString(conn.packets[3][29:57]) != "00000003ffffffff000000000000c350000000010000000400000004" { @@ -409,9 +411,9 @@ func TestCombatDeadPlayerCannotCrossZoneTriggers(t *testing.T) { world, _ := newCombatWorld() world.characters[1].health = 0 world.characters[1].rotation = [4]float32{0, 0, 0, 1} - world.clients[1].forward = 1 + world.characters[1].movement.forward = 1 now := time.Now() - world.clients[1].movementStarted = now + world.characters[1].movement.updatedAt = now world.zoneLinks = map[string]map[uint32]zoneLinks{"target": { 950: {Doors: []zoneDoor{{ID: 1, Destination: 952, DestinationDoor: 2}}}, 952: {Doors: []zoneDoor{{ID: 2, Position: [3]float32{10, 0, 10}}}}, diff --git a/server/dialogue.go b/server/dialogue.go @@ -48,7 +48,7 @@ func (server *server) handleNPCDialogue(client *worldClient, body []byte) error var script gamedata.NPCScript groupID := "" if player != nil && npc != nil && npc.npc && client.ready && !client.loading && client.npcs[npcID] && player.playfield == npc.playfield { - position := predictedPosition_locked(player, client, time.Now()) + position := predictedPosition_locked(player, time.Now()) x, y, z := npc.position[0]-position[0], npc.position[1]-position[1], npc.position[2]-position[2] if x*x+y*y+z*z <= 10*10 { groupID = npc.npcDefinitionID diff --git a/server/dialogue_test.go b/server/dialogue_test.go @@ -174,7 +174,7 @@ func TestNPCConversationBelongsToItsWorldConnection(t *testing.T) { readPacket(first) // The second player's spawn is broadcast to the first. second.Write(targetPacket(n3Packet(0x570c2039, 50000, 2, nil))) readPacket(first) - for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51} { + for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51, 78, 156} { packet, err := readPacket(first) if err != nil || binary.BigEndian.Uint32(packet[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[24:28]) != 2 || binary.BigEndian.Uint32(packet[29:33]) != stat { t.Fatalf("observer did not receive player combat foundations: %x %v", packet, err) diff --git a/server/equipment.go b/server/equipment.go @@ -246,9 +246,9 @@ func (server *server) advanceEquipment(now time.Time) { inventory.Items = slices.Clone(character.inventory.Items) inventory.Items[index].Slot = move.destination movementChanged := move.source == 1 || move.destination == 1 || inventory.equipmentBonus(156) != character.inventory.equipmentBonus(156) - position := character.position + motion := *character if movementChanged { - position = predictedPosition_locked(character, client, now) + motion = character.predictedMovement(now) } health, nano := character.health, character.nano baseHealth := character.maximumHealth() - uint32(character.directHealthBonus()) @@ -261,8 +261,7 @@ func (server *server) advanceEquipment(now time.Time) { } if movementChanged { // Anchor held movement at the speed before the equipment effect changed. - character.position = position - client.movementStarted = now + character.position, character.rotation, character.movement = motion.position, motion.rotation, motion.movement } if move.source < 64 && !item.isWieldableWeapon() { server.queueCombat_locked(updates, character, character, equipmentActionPacket(character.id, item, 7)) diff --git a/server/flying_vehicle_test.go b/server/flying_vehicle_test.go @@ -150,9 +150,9 @@ func TestFlyingVehiclePredictsPitchedForwardAndReverse(t *testing.T) { forward float32 y, z float32 }{ - {"forward", true, 1, 254.3833, 887.3833}, - {"reverse", true, -1, -120.3833, 512.6167}, - {"walking selected", false, 1, 254.3833, 887.3833}, + {"forward", true, 1, 76.36917, 709.36917}, + {"reverse", true, -1, 57.63084, 690.63086}, + {"walking selected", false, 1, 76.36917, 709.36917}, } { t.Run(scenario.name, func(t *testing.T) { world, _ := newFlyingVehicleWorld(t) @@ -160,7 +160,7 @@ func TestFlyingVehiclePredictsPitchedForwardAndReverse(t *testing.T) { player.inventory.Items[0].Slot = 1 player.running = scenario.running player.rotation = [4]float32{-0.38268343, 0, 0, 0.9238795} - client.forward, client.movementStarted = scenario.forward, time.Now().Add(-30*time.Second) + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], scenario.forward, time.Now().Add(-time.Second)) response := httptest.NewRecorder() world.mapPlayers(response, httptest.NewRequest("GET", "/map/players", nil)) @@ -169,7 +169,7 @@ func TestFlyingVehiclePredictsPitchedForwardAndReverse(t *testing.T) { t.Fatal(err) } - if len(result.Players) != 1 || math.Abs(float64(result.Players[0].Position[1]-scenario.y)) > 0.0001 || math.Abs(float64(result.Players[0].Position[2]-scenario.z)) > 0.0001 { + if len(result.Players) != 1 || math.Abs(float64(result.Players[0].Position[1]-scenario.y)) > 0.02 || math.Abs(float64(result.Players[0].Position[2]-scenario.z)) > 0.02 { t.Fatalf("pitched flight prediction: %+v", result.Players) } }) diff --git a/server/grid_test.go b/server/grid_test.go @@ -108,16 +108,17 @@ func TestGridExitHeldMovementRoundTripAndReplay(t *testing.T) { t.Fatal(err) } second := &combatTestConn{} - client := &worldClient{id: 1, conn: second, target: true, ready: true, forward: -1, movementStarted: time.Now()} + client := &worldClient{id: 1, conn: second, target: true, ready: true} + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], -1, time.Now()) world.clients[1] = client if err := world.handleTerminalUse(old, request); err != nil { t.Fatal(err) } - world.advanceZoneCrossings(client.movementStarted) + world.advanceZoneCrossings(world.characters[client.id].movement.updatedAt) if player.playfield != 152 || len(second.packets) != 0 || len(first.packets) != 3 { t.Fatal("entry bounced immediately or an old session replayed Use") } - world.advanceZoneCrossings(client.movementStarted.Add(3 * time.Second)) + world.advanceZoneCrossings(world.characters[client.id].movement.updatedAt.Add(3 * time.Second)) if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } @@ -136,7 +137,7 @@ func TestGridExitRequiresSkillAndNearbyLivingSession(t *testing.T) { world, _ := newGridWorld(t) player, client := world.characters[1], world.clients[1] player.playfield, player.position = 152, [3]float32{242.31323, 4.7, 199.41223} - client.forward, client.movementStarted = 1, time.Now() + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now()) switch scenario { case "skill 90": player.stats.TradeRepair.ComputerLiteracy = 88 @@ -154,7 +155,7 @@ func TestGridExitRequiresSkillAndNearbyLivingSession(t *testing.T) { client.ready = false } - world.advanceZoneCrossings(client.movementStarted) + world.advanceZoneCrossings(world.characters[client.id].movement.updatedAt) if (player.playfield == 800) != (scenario == "skill 91") { t.Fatal("exit ignored its skill, distance or session requirement") diff --git a/server/insurance.go b/server/insurance.go @@ -33,7 +33,7 @@ func (server *server) handleTerminalUse(client *worldClient, body []byte) error client.useSequence = sequence // Shipped statel 51005:0xc00202c1 uses Omni-Med template 117665. - position := predictedPosition_locked(player, client, time.Now()) + position := predictedPosition_locked(player, time.Now()) x, y, z := position[0]-915, position[1]-20.199991, position[2]-578 accepted := client.target && player.playfield == 705 && player.appearance>>9&3 == 2 && binary.BigEndian.Uint32(body[40:44]) == 51005 && binary.BigEndian.Uint32(body[44:48]) == 0xc00202c1 && diff --git a/server/interest.go b/server/interest.go @@ -4,7 +4,7 @@ import "time" func (server *server) updateNPCInterest_locked(client *worldClient, now time.Time) [][]byte { player := server.characters[client.id] - position := predictedPosition_locked(player, client, now) + position := predictedPosition_locked(player, now) var updates [][]byte // Retain a margin beyond the 500-metre minimap query and avoid boundary churn. diff --git a/server/interest_test.go b/server/interest_test.go @@ -69,7 +69,7 @@ func TestHeldMovementStreamsNPCBeforeMinimapRange(t *testing.T) { t.Fatal(err) } world.mutex.Lock() - started := world.clients[1].movementStarted + started := world.characters[1].movement.updatedAt world.mutex.Unlock() done := make(chan struct{}) diff --git a/server/ip_training.go b/server/ip_training.go @@ -107,7 +107,7 @@ func (server *server) handleSkillTraining(client *worldClient, body []byte) erro // Persist IP and all raw stats together before exposing any live change. updated.stats.ImprovementPoints -= uint32((costTenths + 9) / 10) now := time.Now() - position := predictedPosition_locked(player, client, now) + motion := player.predictedMovement(now) if err := server.saveUser_locked(&updated); err != nil { server.mutex.Unlock() return err @@ -119,7 +119,7 @@ func (server *server) handleSkillTraining(client *worldClient, body []byte) erro player.baseStats().Speed.RunSpeed != updated.stats.Speed.RunSpeed *player = updated if movementChanged { - player.position, client.movementStarted = position, now + player.position, player.rotation, player.movement = motion.position, motion.rotation, motion.movement } for _, stat := range [][3]uint32{ {1, baseHealth, player.maximumHealth() - uint32(player.directHealthBonus())}, diff --git a/server/ip_training_test.go b/server/ip_training_test.go @@ -401,12 +401,12 @@ func TestSkillTrainingAnchorsHeldMovementBeforeRunSpeedChange(t *testing.T) { player.stats.Abilities = characterAbilitiesStats{100, 100, 100, 100, 100, 100} player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} player.health = player.maximumHealth() - client.forward, client.movementStarted = 1, time.Now().Add(-time.Second) + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now().Add(-time.Second)) stats := player.stats stats.Speed.RunSpeed = 101 err := world.handleSkillTraining(client, skillTrainingRequest(stats)[20:]) - position := predictedPosition_locked(player, client, client.movementStarted.Add(time.Second)) + position := predictedPosition_locked(player, world.characters[client.id].movement.updatedAt.Add(time.Second)) if err != nil || player.stats.Speed.RunSpeed != 101 || player.position[2] < 4.4 || player.position[2] > 4.8 || position[2]-player.position[2] < 4.504 || position[2]-player.position[2] > 4.506 { @@ -421,12 +421,12 @@ func TestSkillTrainingAnchorsLowHealthMovementBeforeMaximumHealthChanges(t *test player.stats.Abilities = characterAbilitiesStats{100, 100, 100, 100, 100, 100} player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} player.health = 100 - client.forward, client.movementStarted = 1, time.Now().Add(-time.Second) + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now().Add(-time.Second)) stats := player.stats stats.Body.BodyDevelopment = 6 err := world.handleSkillTraining(client, skillTrainingRequest(stats)[20:]) - position := predictedPosition_locked(player, client, client.movementStarted.Add(time.Second)) + position := predictedPosition_locked(player, world.characters[client.id].movement.updatedAt.Add(time.Second)) if err != nil || player.stats.Body.BodyDevelopment != 6 || player.maximumHealth() != 1000 || player.position[2] < 3.506 || player.position[2] > 3.7 || diff --git a/server/loot.go b/server/loot.go @@ -102,7 +102,7 @@ func (server *server) canLoot_locked(client *worldClient, corpse *character) boo if !corpse.corpse.expiresAt.IsZero() && !time.Now().Before(corpse.corpse.expiresAt) { return false } - position := predictedPosition_locked(server.characters[client.id], client, time.Now()) + position := predictedPosition_locked(server.characters[client.id], time.Now()) x, y, z := position[0]-corpse.position[0], position[1]-corpse.position[1], position[2]-corpse.position[2] // kkr.dll sub_3604D350 checks five metres for world item use. return x*x+y*y+z*z <= 5*5 diff --git a/server/main.go b/server/main.go @@ -70,7 +70,7 @@ func main() { go server.serveWorld() go server.serveChat() go server.roamNPCs() - go server.followPlayers() + go server.movePlayers() go server.saveWorld() go server.checkZoneCrossings() @@ -272,7 +272,8 @@ func (server *server) serveWorldClient(client *worldClient) error { return } server.cancelPlayerTrade_locked(client) - character.follow = nil + character.followTarget = 0 + character.movement = playerMovement{} client.ready = false updates := make(map[*worldClient][][]byte) server.cancelCombat_locked(character.id, updates) @@ -353,7 +354,8 @@ func (server *server) serveWorldClient(client *worldClient) error { return err } } - character.follow = nil + character.followTarget = 0 + character.movement = playerMovement{} server.clients[character.id] = client for index := range character.activeNanos { if character.activeNanos[index].expiresAt.IsZero() { @@ -371,8 +373,7 @@ 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 { - snapshot := *other - snapshot.position = predictedPosition_locked(other, server.clients[id], time.Now()) + snapshot := other.predictedMovement(time.Now()) updates = append(updates, characterPacket(&snapshot)) if !server.clients[id].loading { updates = append(updates, playerCombatStatPackets(other)...) diff --git a/server/maps.go b/server/maps.go @@ -48,8 +48,9 @@ func (server *server) mapPlayers(w http.ResponseWriter, r *http.Request) { Zone: gamedata.Playfields[user.Playfield].Name, Position: user.Position, Rotation: user.Rotation} if client := server.clients[user.ID]; client != nil { player.Connected = client.ready - if client.ready && !client.loading && client.forward != 0 { - player.Position = predictedPosition_locked(server.characters[user.ID], client, now) + if client.ready && !client.loading { + snapshot := server.characters[user.ID].predictedMovement(now) + player.Position, player.Rotation = snapshot.position, snapshot.rotation } } if user.ReturnDoor != nil { diff --git a/server/maps_test.go b/server/maps_test.go @@ -55,7 +55,8 @@ func TestMapPlayersPredictsMovementWithoutChangingSavedPosition(t *testing.T) { player := world.newCharacter() player.stats = testCharacterStats() player.running = true - world.clients[player.id] = &worldClient{ready: true, forward: 1, movementStarted: time.Now().Add(-time.Minute)} + world.clients[player.id] = &worldClient{ready: true} + world.characters[player.id].movement = heldPlayerMovement(world.characters[player.id], 1, time.Now().Add(-time.Second)) response := httptest.NewRecorder() world.mapPlayers(response, httptest.NewRequest("GET", "/control/map-players", nil)) @@ -66,7 +67,7 @@ func TestMapPlayersPredictsMovementWithoutChangingSavedPosition(t *testing.T) { t.Fatal(err) } - if len(feed.Players) != 1 || !feed.Players[0].Connected || feed.Players[0].Position != [3]float32{52.625, 14.75, 146.875} || feed.Players[0].Rotation != [4]float32{0, 0, 0, 1} { + if len(feed.Players) != 1 || !feed.Players[0].Connected || (feed.Players[0].Position[0] != 52.625 || feed.Players[0].Position[1] != 14.75 || feed.Players[0].Position[2] < 61.375 || feed.Players[0].Position[2] > 61.395) || feed.Players[0].Rotation != [4]float32{0, 0, 0, 1} { t.Fatalf("player feed: %s", response.Body.String()) } if player.position != [3]float32{52.625, 14.75, 56.875} { diff --git a/server/mouse_movement_test.go b/server/mouse_movement_test.go @@ -114,7 +114,7 @@ func TestMouseMovementRejectsInvalidInputWithoutChangingPose(t *testing.T) { err := world.handleMovement(client, request) - if (err != nil) != malformed || player.position != [3]float32{60, 14, 54} || player.rotation != [4]float32{0, 0, 0, 1} || len(output.packets) != 0 || !client.movementStarted.IsZero() { + if (err != nil) != malformed || player.position != [3]float32{60, 14, 54} || player.rotation != [4]float32{0, 0, 0, 1} || len(output.packets) != 0 || !world.characters[client.id].movement.updatedAt.IsZero() { t.Fatalf("invalid turn changed state: error=%v pose=%v/%v", err, player.position, player.rotation) } }) @@ -124,7 +124,7 @@ func TestMouseMovementRejectsInvalidInputWithoutChangingPose(t *testing.T) { func TestMouseMovementKeepsHeldTranslationAndNormalizesSignedPose(t *testing.T) { world, _ := newEquipmentWorld(t) player, client := world.characters[1], world.clients[1] - client.forward, client.strafing, client.turning = 1, true, true + world.characters[client.id].movement.forward, world.characters[client.id].movement.strafe, world.characters[client.id].movement.turn = 1, 1, 1 player.running = true request := mouseMovementRequest() binary.BigEndian.PutUint16(request[19:21], 0xff38) // Y=-12.5. @@ -138,7 +138,7 @@ func TestMouseMovementKeepsHeldTranslationAndNormalizesSignedPose(t *testing.T) if player.position != [3]float32{60, -12.5, 54} || math.Abs(float64(player.rotation[1]+0.70710677)) > 0.000001 || math.Abs(float64(player.rotation[3]-0.70710677)) > 0.000001 { t.Fatalf("signed pose decoding: %v/%v", player.position, player.rotation) } - if client.forward != 1 || !client.strafing || !client.turning || !player.running || client.movementStarted.IsZero() { + if world.characters[client.id].movement.forward != 1 || world.characters[client.id].movement.strafe == 0 || world.characters[client.id].movement.turn == 0 || !player.running || world.characters[client.id].movement.updatedAt.IsZero() { t.Fatal("mouse turn changed held movement controls") } } diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -392,8 +392,8 @@ func (server *server) finishResourceChange_locked(updates map[*worldClient][][]b } // Keep held movement at its previous speed until the modifier changed. if client := server.clients[player.id]; client != nil && (previous.maximumHealth() != player.maximumHealth() || previous.nanoBonus(156) != player.nanoBonus(156)) { - player.position = predictedPosition_locked(&previous, client, now) - client.movementStarted = now + snapshot := previous.predictedMovement(now) + player.position, player.rotation, player.movement = snapshot.position, snapshot.rotation, snapshot.movement } // Refresh the native resource caches when derived maxima change. diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -105,9 +105,9 @@ func (server *server) nanoTarget_locked(player, target *character, client *world if target.npc || target.appearance>>9&3 != player.appearance>>9&3 || recipient == nil || !recipient.ready || recipient.loading || !target.acceptsNano(program) { return false } - second = predictedPosition_locked(target, recipient, now) + second = predictedPosition_locked(target, now) } - first := predictedPosition_locked(player, client, now) + first := predictedPosition_locked(player, now) x, y, z := float64(first[0])-float64(second[0]), float64(first[1])-float64(second[1]), float64(first[2])-float64(second[2]) // kkr.dll 10066328..10066390 checks the float32 3D distance after its integer gate. distance := float32(math.Sqrt(x*x + y*y + z*z)) @@ -154,8 +154,8 @@ 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{}) && + !player.sitting && !player.driving() && player.movement.forward == 0 && player.movement.strafe == 0 && player.movement.turn == 0 && client.equipment == nil && + player.movement.velocity == [3]float32{} && server.nanoTarget_locked(player, target, client, program, now) var cost int32 if accepted { diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -86,11 +86,11 @@ func TestWinterBiteRejectsInvalidAdmission(t *testing.T) { case "sitting": player.sitting = true case "forward": - client.forward = 1 + world.characters[client.id].movement.forward = 1 case "strafe": - client.strafing = true + world.characters[client.id].movement.strafe = 1 case "turn": - client.turning = true + world.characters[client.id].movement.turn = 1 case "equipment": client.equipment = &equipmentMove{} case "hidden": diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go @@ -19,7 +19,7 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se if target == nil || target.health == 0 || target.playfield != npc.playfield || client == nil || !client.ready || client.loading { server.stopAttack_locked(npc, updates) } else { - destination = predictedPosition_locked(target, client, now) + 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 { diff --git a/server/player_follow.go b/server/player_follow.go @@ -1,21 +1,12 @@ 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") @@ -42,27 +33,12 @@ func (server *server) handlePlayerFollow(client *worldClient, body []byte) error 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) - } - } - } + player.anchorMovement_locked(now) + player.followTarget = target.id + player.movement.prepare(player, now) updates := make(map[*worldClient][][]byte) - _, player.follow.carriedMass = player.followMass() - server.queueCombat_locked(updates, player, target, playerFollowMassPackets(player)...) + _, player.movement.carriedMass = player.movementMass() + server.queueCombat_locked(updates, player, target, playerMovementMassPackets(player)...) server.queueCombat_locked(updates, player, target, playerFollowPacket(player.id, target.id)) server.mutex.Unlock() server.sendCombatUpdates(updates) @@ -91,164 +67,20 @@ func playerFollowPacket(id, target uint32) []byte { 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 { + if player.followTarget == 0 || !client.ready || client.loading || server.characters[id].playfield != server.characters[observer.id].playfield { continue } - target := server.characters[player.follow.target] + target := server.characters[player.followTarget] if !server.playerFollowTargetAvailable_locked(client, target) || target.npc && !observer.npcs[target.id] || spawned != nil && !spawned[target.id] { continue } - packets = append(packets, playerFollowMassPackets(player)...) + packets = append(packets, playerMovementMassPackets(player)...) packet := playerFollowPacket(id, target.id) // Refresh pose as well as target after an observer spent time loading. for axis, value := range player.position { @@ -260,72 +92,22 @@ func (server *server) playerFollowReplay_locked(observer *worldClient, spawned m } func (server *server) playerMovementReplay_locked(observer *worldClient, now time.Time) [][]byte { - // Restore the same held input and current pose before replaying its followers. + // Refresh pose and initialize direction omitted by the native vehicle reader. 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 { + if id == observer.id || !client.ready || client.loading || !player.movement.active() || player.playfield != server.characters[observer.id].playfield || player.followTarget != 0 && player.movement.direction >= 0 { continue } - snapshot := *player - snapshot.position = predictedPosition_locked(player, client, now) - action := uint32(1) - if client.forward < 0 { - action = 3 + snapshot := player.predictedMovement(now) + packets = append(packets, playerMovementMassPackets(player)...) + if player.movement.direction < 0 { + // PlayerVehicle's reader restores helper subtype2, but not GetDir. + // A matching stop then reverse start admits SetDirection(-1). Halt + // necessarily restarts acceleration; see docs/player-movement.md. + packets = append(packets, npcMovementPacket(&snapshot, 4), npcMovementPacket(&snapshot, 3)) } - packets = append(packets, npcMovementPacket(&snapshot, action)) + packets = append(packets, npcMovementPacket(&snapshot, 20)) } 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 @@ -130,8 +130,8 @@ func TestPlayerFollowRejectsUntrustedTargetsAndRoutes(t *testing.T) { 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)) + if (err != nil) != (scenario == "short" || scenario == "long") || world.characters[client.id].followTarget != 0 || len(output.packets) != 0 { + t.Fatal("untrusted follow changed state", err, world.characters[client.id].followTarget, len(output.packets)) } }) } @@ -144,23 +144,23 @@ func TestPlayerFollowAcceleratesAndArrivesWithoutNativeMovementSnapshots(t *test if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil { t.Fatal(err) } - start := world.characters[client.id].follow.updatedAt + start := world.characters[client.id].movement.updatedAt - world.advancePlayerFollowing(start.Add(100 * time.Millisecond)) + world.advancePlayerMovement(start.Add(100 * time.Millisecond)) first := player.position for tick := 2; tick <= 300; tick++ { - world.advancePlayerFollowing(start.Add(time.Duration(tick) * 100 * time.Millisecond)) + world.advancePlayerMovement(start.Add(time.Duration(tick) * 100 * time.Millisecond)) } arrived := player.position - world.advancePlayerFollowing(start.Add(31 * time.Second)) + world.advancePlayerMovement(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 arrived[0] < 25.8 || arrived[0] > 26.2 || player.position != arrived || world.characters[client.id].followTarget == 0 || world.characters[client.id].movement.velocity != [3]float32{} { + t.Fatal("follow failed to arrive four units short and halt", player.position, world.characters[client.id].followTarget) } - if predictedPosition_locked(player, client, start.Add(time.Hour)) != arrived || math.Abs(float64(player.rotation[1])-math.Sqrt(0.5)) > 0.000001 { + if predictedPosition_locked(player, 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) } } @@ -178,9 +178,9 @@ func TestPlayerFollowChainsUseOneTargetSnapshot(t *testing.T) { t.Fatal(err) } now := time.Now() - world.characters[1].follow.updatedAt, world.characters[2].follow.updatedAt = now, now + world.characters[1].movement.updatedAt, world.characters[2].movement.updatedAt = now, now - world.advancePlayerFollowing(now.Add(100 * time.Millisecond)) + world.advancePlayerMovement(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) @@ -192,7 +192,7 @@ func TestPlayerFollowTargetLossClearsNativeController(t *testing.T) { t.Run(scenario, func(t *testing.T) { world, output := newCombatWorld() client := world.clients[1] - client.forward = 1 + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now()) if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil { t.Fatal(err) } @@ -212,11 +212,11 @@ func TestPlayerFollowTargetLossClearsNativeController(t *testing.T) { } now := time.Now() - world.advancePlayerFollowing(now) - world.advancePlayerFollowing(now.Add(time.Second)) + world.advancePlayerMovement(now) + world.advancePlayerMovement(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) + if world.characters[client.id].followTarget != 0 || world.characters[client.id].movement.forward != 0 || len(output.packets) != 5 { + t.Fatal("target loss did not clear exactly once", world.characters[client.id].followTarget, output.packets) } for index, action := range []uint32{2, 4} { packet := output.packets[3+index] @@ -224,7 +224,7 @@ func TestPlayerFollowTargetLossClearsNativeController(t *testing.T) { 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 { + if predictedPosition_locked(world.characters[client.id], now.Add(2*time.Second)) != world.characters[client.id].position { t.Fatal("target loss retained held forward movement") } }) @@ -240,12 +240,12 @@ func TestPlayerFollowMovementCheckpointsWithoutTickDatabaseWrites(t *testing.T) if err := world.handlePlayerFollow(client, playerFollowRequest(2)); err != nil { t.Fatal(err) } - start := world.characters[client.id].follow.updatedAt + start := world.characters[client.id].movement.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)) + world.advancePlayerMovement(start.Add(time.Duration(tick) * 100 * time.Millisecond)) } if writes := checkpointWrites(t, world); len(writes) != 0 { t.Fatal("follow tick churned SQLite", writes) @@ -275,8 +275,8 @@ func TestPlayerFollowMouseRotationPreservesControllerAndManualMovementCancels(t if err := world.handlePlayerFollow(client, playerFollowRequest(target.id)); err != nil { t.Fatal(err) } - follow := player.follow - world.advancePlayerFollowing(follow.updatedAt.Add(100 * time.Millisecond)) + follow := player.followTarget + world.advancePlayerMovement(player.movement.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 { @@ -286,14 +286,14 @@ func TestPlayerFollowMouseRotationPreservesControllerAndManualMovementCancels(t err := world.handleMovement(client, request) forward := float32(0) - if action == 1 || moving && action != 2 && action != 4 && action != 20 { + if action == 1 || moving && action != 2 { 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) + if err != nil || (player.followTarget == follow) != (action == 20) || world.characters[client.id].movement.forward != forward { + t.Fatal("movement follow cancellation or throttle", action, err, player.followTarget, world.characters[client.id].movement.forward, forward) } }) } @@ -307,16 +307,16 @@ func TestPlayerFollowRootSuspendsAndResumesController(t *testing.T) { if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil { t.Fatal(err) } - now := world.characters[client.id].follow.updatedAt + now := world.characters[client.id].movement.updatedAt player.activeNanos = []activeNano{{program: 42110}} - world.advancePlayerFollowing(now.Add(100 * time.Millisecond)) + world.advancePlayerMovement(now.Add(100 * time.Millisecond)) rooted := player.position player.activeNanos = nil - world.advancePlayerFollowing(now.Add(200 * time.Millisecond)) + world.advancePlayerMovement(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) + if rooted != [3]float32{} || math.Abs(float64(player.position[0])-0.03) > 0.000001 || world.characters[client.id].followTarget == 0 { + t.Fatal("root did not suspend and resume following", rooted, player.position, world.characters[client.id].followTarget) } } @@ -358,27 +358,20 @@ func TestPlayerFollowLateObserverGetsControllerAfterBothActorSnapshots(t *testin } } -func TestPlayerFollowIntegratorRetainsMassForceCapAndStallLimit(t *testing.T) { +func TestPlayerForceIntegratorRetainsMassAndForceCeiling(t *testing.T) { for _, scenario := range []struct { - name string - seconds float64 - bodyMass, totalMass float32 - want float32 + name string + mass, force, limit, 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}, + {"body force", 10, 60, 30, .3}, {"carried force", 10, 60, 60, .6}, {"force ceiling", 10000, 60000, 10000, .1}, } { t.Run(scenario.name, func(t *testing.T) { - follow := &playerFollow{} + movement := playerMovement{} - position := follow.advance([3]float32{}, [3]float32{30, 0, 0}, scenario.seconds, 1.5, scenario.bodyMass, scenario.totalMass) + movement.integrateForce([3]float32{scenario.force, 0, 0}, .1, scenario.mass, 1.5, scenario.limit) - if math.Abs(float64(position[0]-scenario.want)) > .000001 { - t.Fatal("native force/stall boundary", position, scenario.want) + if math.Abs(float64(movement.velocity[0]-scenario.want)) > .000001 { + t.Fatal(movement.velocity, scenario.want) } }) } @@ -400,7 +393,7 @@ func TestPlayerFollowMassUsesNativeBreedSexAndCarriedSlots(t *testing.T) { } player.inventory.Bank = []ownedItem{{Type: 51018, Template: 121567, Slot: 0, Count: 1}} - body, carried := player.followMass() + body, carried := player.movementMass() if math.Abs(float64(body-scenario.mass)) > .000001 || carried != 1500 { t.Fatal("native mass included equipment/bank/Chest or lost carried item", body, carried) @@ -418,12 +411,18 @@ func TestPlayerFollowArrivalToleranceAndCrossing(t *testing.T) { {"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}} + world, _ := newCombatWorld() + player := world.characters[1] + world.characters[1000000].position = [3]float32{scenario.target, 0, 0} + if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil { + t.Fatal(err) + } + player.movement.previousPosition = [3]float32{scenario.previous, 0, 0} - position := follow.advance([3]float32{}, [3]float32{scenario.target, 0, 0}, .1, 1.5, 10, 10) + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) - if math.Abs(float64(position[0]-scenario.want)) > .000001 { - t.Fatal("native arrival boundary", position, scenario.want) + if math.Abs(float64(player.position[0]-scenario.want)) > .000001 { + t.Fatal("native arrival boundary", player.position, scenario.want) } }) } @@ -442,9 +441,9 @@ func TestPlayerFollowMotionInterruptsCastAndRefundsReservation(t *testing.T) { if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil { t.Fatal(err) } - now := world.characters[client.id].follow.updatedAt + now := world.characters[client.id].movement.updatedAt - world.advancePlayerFollowing(now.Add(100 * time.Millisecond)) + world.advancePlayerMovement(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) @@ -458,15 +457,15 @@ func TestPlayerFollowRetargetingPreservesVelocity(t *testing.T) { 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.advancePlayerMovement(world.characters[client.id].movement.updatedAt.Add(100 * time.Millisecond)) + velocity := world.characters[client.id].movement.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) + if err != nil || world.characters[client.id].followTarget != 2 || world.characters[client.id].movement.velocity != velocity { + t.Fatal("retarget reset native motion", err, world.characters[client.id].followTarget) } } @@ -478,14 +477,14 @@ func TestPlayerFollowSnapshotIncludesVelocityBeforeLateReplay(t *testing.T) { if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil { t.Fatal(err) } - world.advancePlayerFollowing(player.follow.updatedAt.Add(100 * time.Millisecond)) + world.advancePlayerMovement(player.movement.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) + t.Fatal("late actor snapshot lost follow velocity", vehicleOffset, packet, player.movement.velocity) } } @@ -508,9 +507,9 @@ func TestPlayerFollowChecksTradeRangeAfterBothTradersMove(t *testing.T) { t.Fatal(err) } now := time.Now() - world.characters[1].follow.updatedAt, world.characters[2].follow.updatedAt = now, now + world.characters[1].movement.updatedAt, world.characters[2].movement.updatedAt = now, now - world.advancePlayerFollowing(now.Add(100 * time.Millisecond)) + world.advancePlayerMovement(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) @@ -526,11 +525,11 @@ func TestPlayerFollowRunningStartUsesNativeRestThenForwardParameters(t *testing. if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil { t.Fatal(err) } - now := player.follow.updatedAt + now := player.movement.updatedAt - world.advancePlayerFollowing(now.Add(100 * time.Millisecond)) + world.advancePlayerMovement(now.Add(100 * time.Millisecond)) first := player.position[0] - world.advancePlayerFollowing(now.Add(200 * time.Millisecond)) + world.advancePlayerMovement(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) @@ -545,7 +544,13 @@ func TestLateObserverRestoresHeldPlayerInputAndCurrentPose(t *testing.T) { }{{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.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}} + at := time.Now() + started := at.Add(-20 * time.Second) + world.characters[1].movement = heldPlayerMovement(world.characters[1], scenario.forward, started) + for tick := 1; tick <= 200; tick++ { + world.advancePlayerMovement(started.Add(time.Duration(tick) * 100 * time.Millisecond)) + } 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) @@ -559,18 +564,22 @@ func TestLateObserverRestoresHeldPlayerInputAndCurrentPose(t *testing.T) { t.Fatal(err) } - var controls int + var actions []uint32 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 { + actions = append(actions, binary.BigEndian.Uint32(body)) + if math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(body[12:]))-scenario.z)) > .125 { t.Fatal("late observer lost held input or pose", packet) } } } - if controls != 2 { - t.Fatal("initial and ready movement replay", controls) + want := "[20 20]" + if scenario.forward < 0 { + want = "[4 3 20 4 3 20]" + } + if fmt.Sprint(actions) != want { + t.Fatal("initial and ready movement replay", actions) } }) } @@ -598,7 +607,7 @@ func TestPlayerFollowStationaryTerrainDoesNotInterruptCast(t *testing.T) { t.Fatal(err) } - world.advancePlayerFollowing(player.follow.updatedAt.Add(100 * time.Millisecond)) + world.advancePlayerMovement(player.movement.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) @@ -618,7 +627,7 @@ func TestPlayerFollowCastAdmissionUsesActualMotion(t *testing.T) { if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil { t.Fatal(err) } - world.advancePlayerFollowing(player.follow.updatedAt.Add(100 * time.Millisecond)) + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]) diff --git a/server/player_movement.go b/server/player_movement.go @@ -0,0 +1,464 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "math" + "time" +) + +type playerMovement struct { + velocity [3]float32 + previousPosition [3]float32 + updatedAt time.Time + forward float32 + strafe float32 + turn float32 + vertical float32 + direction int32 + components [10]byte + carriedMass int32 +} + +func (movement *playerMovement) prepare(player *character, now time.Time) { + if movement.components[0] == 0 { + movement.components = [10]byte{2, 1, 0, 1, 0, 1, 0, 1, 0, 1} + movement.direction = 1 + movement.previousPosition = player.position + _, movement.carriedMass = player.movementMass() + } + if movement.updatedAt.IsZero() { + movement.updatedAt = now + } + movement.components[0] = 2 + if player.running { + movement.components[0] = 3 + } + if player.flying() { + movement.components[0] = 7 + } else if player.sitting { + movement.components[0] = 8 + } +} + +func (movement *playerMovement) active() bool { + return movement.velocity != [3]float32{} || movement.forward != 0 || movement.strafe != 0 || movement.turn != 0 || movement.vertical != 0 +} + +func (player *character) predictedMovement(now time.Time) character { + snapshot := *player + if snapshot.followTarget == 0 { + snapshot.advanceMovement(now, [3]float32{}) + } + return snapshot +} + +func (player *character) anchorMovement_locked(now time.Time) { + snapshot := player.predictedMovement(now) + player.position, player.rotation, player.movement = snapshot.position, snapshot.rotation, snapshot.movement + player.movement.prepare(player, now) + player.movement.updatedAt = now +} + +func predictedPosition_locked(player *character, now time.Time) [3]float32 { + return player.predictedMovement(now).position +} + +func bodyAxes(rotation [4]float32) ([3]float32, [3]float32) { + x, y, z, w := rotation[0], rotation[1], rotation[2], rotation[3] + return [3]float32{2*x*z + 2*y*w, 2*y*z - 2*x*w, 1 - 2*x*x - 2*y*y}, [3]float32{1 - 2*y*y - 2*z*z, 2*x*y + 2*z*w, 2*x*z - 2*y*w} +} + +func vectorLength(vector [3]float32) float32 { + return float32(math.Sqrt(float64(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2]))) +} + +// QQR11d30's common force/velocity stage is shared by manual and arrival steering. +func (movement *playerMovement) integrateForce(force [3]float32, seconds, bodyMass, speed, forceLimit float32) float32 { + forceLength := vectorLength(force) + if forceLength <= 10000000 { + for axis := range force { + if forceLength > forceLimit { + force[axis] *= forceLimit / forceLength + } + movement.velocity[axis] += force[axis] * seconds / bodyMass + } + } + length := vectorLength(movement.velocity) + if length > speed { + for axis := range movement.velocity { + movement.velocity[axis] *= speed / length + } + } + return min(length, speed) +} + +func (player *character) advanceMovement(now time.Time, target [3]float32) { + movement := &player.movement + if movement.updatedAt.IsZero() { + return + } + seconds := now.Sub(movement.updatedAt).Seconds() + movement.updatedAt = now + previous := player.position + defer func() { movement.previousPosition = previous }() + if seconds <= 0 || seconds > 4 { + return + } + movement.prepare(player, now) + if player.movementRestricted() || player.sitting { + movement.velocity = [3]float32{} + return + } + speed := float32(1.5) + if player.running || player.flying() { + speed = player.runningMovementSpeed(movement.components[2] != 1) + } + bodyMass, carriedMass := player.movementMass() + forceLimit := min(float32(10000), 2*(bodyMass+float32(carriedMass)*float32(.001))*speed) + for seconds > 0 { + step := float32(math.Min(seconds, .4)) + seconds -= float64(step) + forward, right := bodyAxes(player.rotation) + force := [3]float32{} + if player.followTarget != 0 { + // KKR48430 / QQR15fe0,15e90: four-unit arrival point, damping and Halt. + delta := [3]float32{target[0] - player.position[0], target[1] - player.position[1], target[2] - player.position[2]} + distance := vectorLength(delta) + arrival := player.position + if distance > 4 { + for axis := range arrival { + arrival[axis] += delta[axis] * ((distance - 4) / distance) + } + } + delta = [3]float32{arrival[0] - player.position[0], arrival[1] - player.position[1], arrival[2] - player.position[2]} + distance = vectorLength(delta) + if distance < .2 || delta[0]*(arrival[0]-movement.previousPosition[0])+delta[2]*(arrival[2]-movement.previousPosition[2]) < 0 { + movement.velocity = [3]float32{} + if movement.direction < 0 { + movement.action(player, 4) + } else { + movement.action(player, 2) + } + } else { + for axis := range force { + force[axis] = 4 * bodyMass * (delta[axis]/distance*min(speed, 4*distance) - movement.velocity[axis]) + } + } + } else if movement.forward != 0 { + // QQR159a0/159f0 uses full signed force, independently of arrival damping. + sign := float32(1) + if movement.forward < 0 { + sign = -1 + } + for axis := range force { + force[axis] = sign * forceLimit * forward[axis] + } + } + length := movement.integrateForce(force, step, bodyMass, speed, forceLimit) + for axis := range player.position { + player.position[axis] += step * (right[axis] * movement.strafe) + if axis == 1 { + player.position[axis] += step * movement.vertical + } + if length > .001 { + player.position[axis] += movement.velocity[axis] * step + } + } + // Native angular control runs after displacement, separately from lateral motion. + if movement.turn != 0 { + sine, cosine := math.Sincos(float64(movement.turn * step)) + if movement.velocity[0] == 0 && movement.velocity[2] == 0 { + halfSine, halfCosine := math.Sincos(float64(movement.turn*step) / 2) + x, y, z, w := player.rotation[0], player.rotation[1], player.rotation[2], player.rotation[3] + player.rotation = [4]float32{float32(halfCosine)*x + float32(halfSine)*z, float32(halfCosine)*y + float32(halfSine)*w, float32(halfCosine)*z - float32(halfSine)*x, float32(halfCosine)*w - float32(halfSine)*y} + } else { + x, z := movement.velocity[0], movement.velocity[2] + movement.velocity[0] = float32(cosine)*x + float32(sine)*z + movement.velocity[2] = float32(cosine)*z - float32(sine)*x + } + } + } + // Mode0 body orientation follows horizontal velocity, reversed when backing up. + if !player.flying() && (movement.velocity[0] != 0 || movement.velocity[2] != 0) { + sign := float64(1) + if movement.direction < 0 { + sign = -1 + } + angle := math.Atan2(sign*float64(movement.velocity[0]), sign*float64(movement.velocity[2])) + player.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))} + } + if player.followTarget != 0 && movement.velocity != [3]float32{} && movement.components[1] == 1 { + // Physical follow start refreshes its cache only after this outer frame. + if movement.direction < 0 { + movement.action(player, 3) + } else { + movement.action(player, 1) + } + } +} + +func (movement *playerMovement) action(player *character, action uint32) bool { + movement.prepare(player, movement.updatedAt) + old := movement.components + accepted := true + switch action { + case 1, 3: + direction := int32(1) + subtype := byte(1) + if action == 3 { + direction = -1 + subtype = 2 + } + accepted = old[1] == 1 || old[1] == 3 && old[2] != subtype + if accepted { + if movement.direction != direction { + movement.velocity = [3]float32{} + } + movement.direction = direction + movement.forward = float32(direction) + movement.components[1], movement.components[2] = 3, subtype + if action == 1 && movement.turn != 0 { + movement.turn = float32(math.Copysign(1.5, float64(movement.turn))) + } + } + case 2, 4: + subtype := byte(1) + if action == 4 { + subtype = 2 + } + accepted = old[1] == 3 && old[2] == subtype + if accepted { + movement.forward = 0 + movement.velocity = [3]float32{} + movement.components[1], movement.components[2] = 1, 0 + if action == 4 { + movement.direction = 1 + } else if movement.turn != 0 { + movement.turn = float32(math.Copysign(3.5, float64(movement.turn))) + } + } + case 5, 7: + subtype := byte(4) + sign := float32(1) + if action == 7 { + subtype = 3 + sign = -1 + } + accepted = old[3] == 1 || old[3] == 3 && old[4] != subtype + if accepted { + movement.strafe = sign * player.strafeSpeed() + movement.components[3], movement.components[4] = 3, subtype + } + case 6, 8: + subtype := byte(4) + if action == 8 { + subtype = 3 + } + accepted = old[3] == 3 && old[4] == subtype + if accepted { + movement.strafe = 0 + movement.components[3], movement.components[4] = 1, 0 + } + case 9, 11: + movement.turn = 3.5 + if old[1] != 1 { + movement.turn = 1.5 + } + subtype := byte(4) + if action == 11 { + movement.turn = -movement.turn + subtype = 3 + } + movement.components[7], movement.components[8] = 5, subtype + case 10, 12: + subtype := byte(4) + if action == 12 { + subtype = 3 + } + accepted = old[7] == 5 && old[8] == subtype + if accepted { + movement.turn = 0 + movement.components[7], movement.components[8] = 1, 0 + } + case 22, 23: + player.running = action == 23 + movement.prepare(player, movement.updatedAt) + case 20: + return true + } + if accepted { + movement.components[5] = old[3] + } + return accepted +} + +func (player *character) strafeSpeed() float32 { + runSpeed := float32(player.baseStats().Speed.RunSpeed) + float32(player.inventory.equipmentBonus(156)+player.nanoBonus(156)) + if float32(player.health) < float32(player.maximumHealth())*float32(.15) { + runSpeed = (runSpeed+500)*(float32(player.health)/(float32(player.maximumHealth())*float32(.15))) - 500 + } + return min(float32(15), 2+float32(.0025)*runSpeed) +} + +func (player *character) vehicleState() []byte { + size := 42 + if player.npc { + size = 28 + } + vehicle := make([]byte, size) + movement := player.movement + movement.prepare(player, movement.updatedAt) + copy(vehicle[12:22], movement.components[:]) + preferred := uint32(2) + if player.running { + preferred = 3 + } + binary.BigEndian.PutUint32(vehicle[22:26], preferred) + if !player.npc { + for axis, value := range movement.velocity { + binary.BigEndian.PutUint32(vehicle[axis*4:], math.Float32bits(value)) + } + for index, value := range []float32{movement.forward, movement.strafe, movement.turn, movement.vertical} { + binary.BigEndian.PutUint32(vehicle[26+index*4:], math.Float32bits(value)) + } + } + return vehicle +} + +func (server *server) movePlayers() { + ticker := time.NewTicker(time.Second / 60) + defer ticker.Stop() + for now := range ticker.C { + server.advancePlayerMovement(now) + } +} + +func (server *server) advancePlayerMovement(now time.Time) { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + updates := make(map[*worldClient][][]byte) + server.advancePlayerMovement_locked(now, updates) + server.mutex.Unlock() + server.sendCombatUpdates(updates) +} + +func (server *server) advancePlayerMovement_locked(now time.Time, updates map[*worldClient][][]byte) { + previous := make(map[uint32][3]float32) + // Advance ordinary inputs first so every follower observes this frame's target. + for id, client := range server.clients { + player := server.characters[id] + previous[id] = player.position + if !client.ready || client.loading || player.health == 0 { + if player.followTarget != 0 { + server.queueCombat_locked(updates, player, player, npcMovementPacket(player, 2), npcMovementPacket(player, 4)) + } + player.followTarget = 0 + player.movement = playerMovement{} + continue + } + if player.followTarget == 0 { + player.advanceMovement(now, [3]float32{}) + } + } + targets := make(map[uint32][3]float32) + for _, client := range server.clients { + player := server.characters[client.id] + if player.followTarget != 0 { + if target := server.characters[player.followTarget]; server.playerFollowTargetAvailable_locked(client, target) { + targets[target.id] = target.position + } + } + } + for id, client := range server.clients { + player := server.characters[id] + if player.followTarget != 0 { + target := server.characters[player.followTarget] + if !server.playerFollowTargetAvailable_locked(client, target) { + player.followTarget = 0 + player.movement.action(player, 2) + player.movement.action(player, 4) + player.movement.updatedAt = now + server.queueCombat_locked(updates, player, player, npcMovementPacket(player, 2), npcMovementPacket(player, 4)) + } else { + player.advanceMovement(now, targets[target.id]) + } + } + if player.movement.active() || player.followTarget != 0 { + _, mass := player.movementMass() + if mass != player.movement.carriedMass { + player.movement.carriedMass = mass + server.queueCombat_locked(updates, player, player, playerMovementMassPackets(player)...) + } + } + if player.position != previous[id] { + if !player.flying() { + if ground := server.terrain[player.playfield]; ground != nil { + oldHeight, oldInside := ground.elevation(previous[id][0], previous[id][2]) + newHeight, newInside := ground.elevation(player.position[0], player.position[2]) + if oldInside && newInside { + player.position[1] = previous[id][1] + (newHeight - oldHeight) + } + } + } + } + } + // Resource/range effects see all participants at the completed frame. + for id, client := range server.clients { + player := server.characters[id] + if player.position == previous[id] { + continue + } + 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(id, [5]uint32{106})) + } + } +} + +func playerMovementMassPackets(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. + _, carriedMass := player.movementMass() + var packets [][]byte + for _, stat := range [][2]uint32{{78, uint32(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 (player *character) movementMass() (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 +} diff --git a/server/player_movement_test.go b/server/player_movement_test.go @@ -0,0 +1,421 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "math" + "net" + "testing" + "time" +) + +func playerMovementRequest(player *character, action uint32) []byte { + packet := npcMovementPacket(player, action) + request := append([]byte(nil), packet[20:36]...) + return append(request, encodeMovement1491(packet[36:76])...) +} + +func TestHeldStrafeAdvancesAuthoritativePoseBeyondTwentySeconds(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.position, player.rotation = [3]float32{0, 14, 0}, [4]float32{0, 0, 0, 1} + player.inventory, player.running = playerInventory{}, false + player.stats.Speed.RunSpeed = 0 + if err := world.handleMovement(client, playerMovementRequest(player, 5)); err != nil { + t.Fatal(err) + } + started := world.characters[client.id].movement.updatedAt + + for frame := 1; frame <= 250; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + + if math.Abs(float64(player.position[0])-50) > 0.0002 || player.position[1] != 14 || player.position[2] != 0 { + t.Fatal("held strafe left authoritative pose stale", player.position) + } +} + +func TestHeldForwardUsesNativeForceAcceleration(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.position, player.rotation = [3]float32{0, 14, 0}, [4]float32{0, 0, 0, 1} + player.inventory, player.running, player.appearance = playerInventory{}, false, 0x315 + if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + started := world.characters[client.id].movement.updatedAt + + world.advancePlayerMovement(started.Add(100 * time.Millisecond)) + + if math.Abs(float64(player.position[2])-.03) > .000001 { + t.Fatal("forward input skipped native acceleration", player.position) + } +} + +func heldPlayerMovement(player *character, forward float32, at time.Time) playerMovement { + movement := playerMovement{updatedAt: at} + movement.prepare(player, at) + action := uint32(1) + if forward < 0 { + action = 3 + } + movement.action(player, action) + speed := float32(1.5) + if player.running || player.flying() { + speed = player.runningMovementSpeed(forward < 0) + } + facing, _ := bodyAxes(player.rotation) + for axis := range facing { + movement.velocity[axis] = facing[axis] * speed * forward + } + return movement +} + +func TestPlayerMovementComponentTransitionsUseNativeGates(t *testing.T) { + for _, scenario := range []struct { + name string + actions []uint32 + forward, strafe, turn float32 + }{ + {"wrong reverse release", []uint32{1, 4}, 1, 0, 0}, + {"wrong forward release", []uint32{3, 2}, -1, 0, 0}, + {"wrong left release", []uint32{5, 8}, 0, 2, 0}, + {"wrong right release", []uint32{7, 6}, 0, -2, 0}, + {"opposite strafe", []uint32{5, 7}, 0, -2, 0}, + {"repeated strafe", []uint32{5, 5}, 0, 2, 0}, + {"wrong negative turn release", []uint32{9, 12}, 0, 0, 3.5}, + {"wrong positive turn release", []uint32{11, 10}, 0, 0, -3.5}, + {"forward refreshes turn", []uint32{9, 1}, 1, 0, 1.5}, + {"forward stop refreshes turn", []uint32{9, 1, 2}, 0, 0, 3.5}, + {"reverse retains turn", []uint32{9, 3}, -1, 0, 3.5}, + {"reverse stop retains turn", []uint32{1, 9, 3, 4}, 0, 0, 1.5}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory = playerInventory{} + player.stats.Speed.RunSpeed = 0 + player.rotation = [4]float32{0, 0, 0, 1} + + for _, action := range scenario.actions { + if err := world.handleMovement(client, playerMovementRequest(player, action)); err != nil { + t.Fatal(err) + } + } + + if player.movement.forward != scenario.forward || player.movement.strafe != scenario.strafe || player.movement.turn != scenario.turn { + t.Fatal("native input gate/cache mismatch", player.movement) + } + }) + } +} + +func TestPlayerMovementStrafeCacheChangesOnlyOnAdmittedStart(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory = playerInventory{} + player.stats.Speed.RunSpeed = 0 + if err := world.handleMovement(client, playerMovementRequest(player, 5)); err != nil { + t.Fatal(err) + } + player.stats.Speed.RunSpeed = 100 + + if err := world.handleMovement(client, playerMovementRequest(player, 5)); err != nil { + t.Fatal(err) + } + cached := player.movement.strafe + if err := world.handleMovement(client, playerMovementRequest(player, 7)); err != nil { + t.Fatal(err) + } + + if cached != 2 || player.movement.strafe != -2.25 { + t.Fatal("strafe cache repriced without a transition", cached, player.movement.strafe) + } +} + +func TestPlayerMovementReverseHaltsBeforeApplyingNewForce(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory, player.running = playerInventory{}, false + player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} + if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + + if err := world.handleMovement(client, playerMovementRequest(player, 3)); err != nil { + t.Fatal(err) + } + stopped := player.movement.velocity + before := player.position + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + + if stopped != [3]float32{} || math.Abs(float64(player.position[2]-before[2])+.03) > .000001 || player.rotation != [4]float32{0, 0, 0, 1} { + t.Fatal("reversal retained velocity or turned the body backward", stopped, before, player.position, player.rotation) + } +} + +func TestPlayerMovementCheckpointsPoseWithoutTickDatabaseWrites(t *testing.T) { + world := newCheckpointWorld(t) + player := world.characters[1] + client := &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}} + world.clients[1] = client + player.inventory = playerInventory{} + player.stats.Speed.RunSpeed = 0 + if err := world.handleMovement(client, playerMovementRequest(player, 5)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + player.nextPositionSave = started.Add(20 * time.Second) + auditCheckpointWrites(t, world) + + for frame := 1; frame <= 200; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + if writes := checkpointWrites(t, world); len(writes) != 0 { + t.Fatal("motion churned SQLite", writes) + } + if err := world.flushPositions(started.Add(20 * time.Second)); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t).characters[1] + + if restored.position != player.position || math.Abs(float64(player.position[0])-92) > .001 || checkpointWrites(t, world)["characters/UPDATE"] != 1 || restored.movement.active() { + t.Fatal("movement checkpoint lost pose or persisted held controls", player.position, restored.position, checkpointWrites(t, world), restored.movement) + } +} + +func TestPlayerMovementRejectsStalledFrames(t *testing.T) { + for _, duration := range []time.Duration{-time.Second, 0, 4*time.Second + time.Nanosecond} { + t.Run(duration.String(), func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory = playerInventory{} + if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + before := player.position + at := player.movement.updatedAt.Add(duration) + + world.advancePlayerMovement(at) + + if player.position != before || player.movement.updatedAt != at { + t.Fatal("native rejected-frame boundary", player.position, player.movement.updatedAt, at) + } + }) + } +} + +func TestPlayerMovementReverseFollowRetainsDirectionThroughArrival(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory, player.running = playerInventory{}, false + player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} + target := &character{id: 1000000, npc: true, health: 100, playfield: player.playfield, position: [3]float32{0, 0, 30}} + world.characters[target.id] = target + client.npcs = map[uint32]bool{target.id: true} + if err := world.handleMovement(client, playerMovementRequest(player, 3)); err != nil { + t.Fatal(err) + } + if err := world.handlePlayerFollow(client, playerFollowRequest(target.id)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + for frame := 1; frame <= 10; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + moving := player.movement + bodyZ := 1 - 2*player.rotation[0]*player.rotation[0] - 2*player.rotation[1]*player.rotation[1] + for frame := 11; frame <= 240; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + + if moving.forward != -1 || moving.direction != -1 || moving.velocity[2] <= 0 || bodyZ > -.99 || player.movement.forward != 0 || player.movement.direction != 1 || player.followTarget != target.id { + t.Fatal("reverse follow lost native direction or arrival transition", moving, bodyZ, player.movement, player.followTarget) + } +} + +func TestPlayerMovementPoseCorrectionRealignsVelocity(t *testing.T) { + for _, action := range []uint32{1, 3} { + t.Run(fmt.Sprint(action), func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory, player.running = playerInventory{}, false + player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} + if err := world.handleMovement(client, playerMovementRequest(player, action)); err != nil { + t.Fatal(err) + } + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + + err := world.handleMovement(client, mouseMovementRequest()) + + sign := float32(1) + if action == 3 { + sign = -1 + } + if err != nil || math.Abs(float64(vectorLength(player.movement.velocity))-.3) > .00001 || sign*player.movement.velocity[0] < .24 || sign*player.movement.velocity[2] < .16 { + t.Fatal("pose correction lost speed or retained the old velocity heading", err, player.movement.velocity) + } + }) + } +} + +func TestPlayerMovementSnapshotRetainsCachedControlsAndComponentHistory(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory, player.running = playerInventory{}, false + player.stats.Speed.RunSpeed = 0 + for _, action := range []uint32{9, 3, 5, 23} { + if err := world.handleMovement(client, playerMovementRequest(player, action)); err != nil { + t.Fatal(err) + } + } + + packet := characterPacket(player) + + offset := 71 + len(player.name) + 20 + 1 + 14 + if binary.BigEndian.Uint32(packet[offset:]) != 42 || !bytes.Equal(packet[offset+16:offset+26], []byte{3, 3, 2, 3, 4, 3, 0, 5, 4, 1}) { + t.Fatal("snapshot lost movement component history", packet[offset:offset+46]) + } + for index, word := range []uint32{0xbf800000, 0x40000000, 0x40600000, 0} { + if binary.BigEndian.Uint32(packet[offset+30+index*4:]) != word { + t.Fatal("snapshot recomputed a cached control", index, packet[offset:offset+46]) + } + } +} + +func TestLateReverseFollowInitializesDirectionBeforeController(t *testing.T) { + world := newCheckpointWorld(t) + player := world.characters[1] + player.movement = heldPlayerMovement(player, -1, time.Now()) + player.followTarget = 1000000 + world.characters[1000000] = &character{id: 1000000, npc: true, health: 100, playfield: player.playfield} + world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000000: true}} + world.newCharacter().playfield = player.playfield + connection := &combatTestConn{} + observer := &worldClient{id: 2, ready: true, loading: true, target: true, conn: connection, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = observer + + if err := world.handleCharacterReady(observer); err != nil { + t.Fatal(err) + } + + var actions []uint32 + for _, packet := range connection.packets { + if binary.BigEndian.Uint32(packet[24:28]) != 1 { + continue + } + switch binary.BigEndian.Uint32(packet[16:20]) { + case 0x54111123: + actions = append(actions, binary.BigEndian.Uint32(decodeMovement1491(packet[29:]))) + case 0x260f3671: + actions = append(actions, 1000000) + } + } + if fmt.Sprint(actions) != "[4 3 20 1000000]" || player.movement.direction != -1 || player.followTarget != 1000000 { + t.Fatal("reverse direction replay must precede follow without changing authoritative state", actions, player.movement, player.followTarget) + } +} + +func TestHeldLongitudinalMovementContinuesBeyondTwentySeconds(t *testing.T) { + for _, scenario := range []struct { + action uint32 + z float32 + }{{1, 52.2}, {3, -52.2}} { + t.Run(fmt.Sprint(scenario.action), func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory, player.running = playerInventory{}, false + player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} + if err := world.handleMovement(client, playerMovementRequest(player, scenario.action)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + for frame := 1; frame <= 350; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + + if math.Abs(float64(player.position[2]-scenario.z)) > .001 || player.position[0] != 0 || player.rotation != [4]float32{0, 0, 0, 1} { + t.Fatal("held input expired or skipped acceleration", player.position, player.rotation) + } + }) + } +} + +func TestCombinedHeldMovementKeepsIndependentLateralDisplacement(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory, player.running = playerInventory{}, false + player.stats.Speed.RunSpeed = 0 + player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} + for _, action := range []uint32{1, 5} { + if err := world.handleMovement(client, playerMovementRequest(player, action)); err != nil { + t.Fatal(err) + } + } + started := player.movement.updatedAt + + for frame := 1; frame <= 10; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + + if math.Abs(float64(player.position[0])-2) > .001 || math.Abs(float64(player.position[2])-1.2) > .001 || math.Abs(float64(vectorLength(player.movement.velocity))-1.5) > .00001 { + t.Fatal("lateral motion was folded into capped longitudinal velocity", player.position, player.movement.velocity) + } +} + +func TestHeldStationaryTurnAdvancesAuthoritativeHeading(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1} + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + + world.advancePlayerMovement(player.movement.updatedAt.Add(time.Second)) + + if player.position != [3]float32{} || math.Abs(float64(player.rotation[1])-.98398596) > .000001 || math.Abs(float64(player.rotation[3])+.17824606) > .000001 { + t.Fatal("stationary turn did not rotate by 3.5 radians", player.position, player.rotation) + } +} + +func TestLateObserverSnapshotAdvancesHeadingWithPose(t *testing.T) { + world := newCheckpointWorld(t) + player := world.characters[1] + player.rotation = [4]float32{0, 0, 0, 1} + player.movement.prepare(player, time.Now().Add(-100*time.Millisecond)) + player.movement.turn = 3.5 + player.movement.components[7], player.movement.components[8] = 5, 4 + world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}} + world.newCharacter().playfield = player.playfield + cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}) + binary.BigEndian.PutUint16(cookie, 0xdfdf) + 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 snapshots int + for _, packet := range connection.packets { + if binary.BigEndian.Uint32(packet[16:20]) != 0x271b3a6b || binary.BigEndian.Uint32(packet[24:28]) != 1 { + continue + } + snapshots++ + // SCFU's fixed prefix ends with compact position then body quaternion. + y := math.Float32frombits(binary.BigEndian.Uint32(packet[48:52])) + w := math.Float32frombits(binary.BigEndian.Uint32(packet[56:60])) + if y < .17 || y > .5 || w < .8 || w > .986 { + t.Fatal("late actor snapshot retained the old heading", y, w) + } + } + if snapshots != 1 || player.rotation != [4]float32{0, 0, 0, 1} { + t.Fatal("snapshot mutated authoritative motion or omitted the actor", snapshots, player.rotation) + } +} diff --git a/server/player_trading.go b/server/player_trading.go @@ -31,7 +31,7 @@ func (server *server) playerTradeAvailable_locked(first, second *worldClient) bo return false } now := time.Now() - x, y := predictedPosition_locked(a, first, now), predictedPosition_locked(b, second, now) + x, y := predictedPosition_locked(a, now), predictedPosition_locked(b, now) dx, dy, dz := x[0]-y[0], x[1]-y[1], x[2]-y[2] return dx*dx+dy*dy+dz*dz <= 25 } diff --git a/server/reclaim.go b/server/reclaim.go @@ -29,7 +29,7 @@ func (player *character) collectReclaim(now time.Time) { func (server *server) nearReclaim_locked(client *worldClient) bool { player := server.characters[client.id] - position := predictedPosition_locked(player, client, time.Now()) + position := predictedPosition_locked(player, time.Now()) x, y, z := position[0]-915, position[1]-20.2001, position[2]-580 return player.playfield == 705 && x*x+y*y+z*z <= 5*5 } diff --git a/server/remote_combat_stats_test.go b/server/remote_combat_stats_test.go @@ -69,7 +69,7 @@ func TestRemotePlayerSpawnCarriesUnmodifiedCombatFoundations(t *testing.T) { } values = append(values, [2]uint32{binary.BigEndian.Uint32(packet[valueOffset:]), binary.BigEndian.Uint32(packet[valueOffset+4:])}) case 0x3b1d2268, 0x35505644, 0x5e477770: - if len(values) != 11 { + if len(values) != 13 { t.Fatal("equipment or nano replay preceded raw combat foundations", values) } case 0x29304349: @@ -78,7 +78,7 @@ func TestRemotePlayerSpawnCarriesUnmodifiedCombatFoundations(t *testing.T) { } expected := [][2]uint32{{16, 7}, {17, 11}, {18, 13}, {19, 17}, {20, 19}, {21, 23}, - {118, 123}, {119, 0}, {120, 567}, {149, 1490}, {51, 0xffffff9c}} + {118, 123}, {119, 0}, {120, 567}, {149, 1490}, {51, 0xffffff9c}, {78, 1200}, {156, 0}} if err != nil || !spawned || !reflect.DeepEqual(values, expected) || player.equipmentBonus(51) != 5 || player.nanoBonus(16) != 12 { t.Fatal("observer omitted, duplicated or derived a raw combat foundation", err, values) } diff --git a/server/resource_kit.go b/server/resource_kit.go @@ -144,8 +144,8 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body if accepted { accepted = server.itemUseRequirementsMet_locked(player, target, item) accepted = accepted && !now.Before(lockRecipient.skillLocks[kit.lockSkill]) - first := predictedPosition_locked(player, client, now) - second := predictedPosition_locked(target, server.clients[target.id], now) + first := predictedPosition_locked(player, now) + second := predictedPosition_locked(target, now) x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] distance := float32(itemStat(gamedata.ItemTemplates[item.Template], 287)) + player.physicalExtent() + target.physicalExtent() accepted = accepted && x*x+y*y+z*z <= distance*distance diff --git a/server/resurrection_reconnect_test.go b/server/resurrection_reconnect_test.go @@ -104,7 +104,7 @@ func TestResurrectionReconnectResumesPendingDeath(t *testing.T) { } } expectedStats := [][2]uint32{{16, 6}, {17, 6}, {18, 6}, {19, 6}, {20, 6}, {21, 6}, - {118, 5}, {119, 5}, {120, 5}, {149, 5}, {51, 0}} + {118, 5}, {119, 5}, {120, 5}, {149, 5}, {51, 0}, {78, 0}, {156, 5}} if !reflect.DeepEqual(observerStats, expectedStats) { t.Fatal("pending reconnect omitted or changed the other player's combat foundations", observerStats) } diff --git a/server/roaming_test.go b/server/roaming_test.go @@ -45,7 +45,7 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) { peer.Add(1) go func() { defer peer.Done() - for range 12 { + for range 14 { if _, err := readPacket(clients[0]); err != nil { t.Error(err) return diff --git a/server/shops.go b/server/shops.go @@ -24,7 +24,7 @@ func (server *server) canUseShop_locked(client *worldClient, machine gamedata.Sh client.equipment != nil || client.trade != nil || player.playfield != machine.Playfield { return false } - position := predictedPosition_locked(player, client, time.Now()) + position := predictedPosition_locked(player, time.Now()) x, y, z := position[0]-machine.Position[0], position[1]-machine.Position[1], position[2]-machine.Position[2] if x*x+y*y+z*z > 5*5 { return false diff --git a/server/skill_nano_test.go b/server/skill_nano_test.go @@ -214,7 +214,8 @@ func TestSkillNanoAnchorsMovingRecipientOnApplicationAndExpiry(t *testing.T) { recipient.health = recipient.maximumHealth() recipient.position, recipient.rotation = [3]float32{0, 0, 3}, [4]float32{0, 0, 0, 1} world.characters[2], world.nextCharacter = &recipient, 2 - client := &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true, forward: 1, movementStarted: time.Now()} + client := &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true} + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now()) world.clients[2] = client if err := world.saveUser_locked(&recipient); err != nil { t.Fatal(err) @@ -223,22 +224,22 @@ func TestSkillNanoAnchorsMovingRecipientOnApplicationAndExpiry(t *testing.T) { t.Fatal(err) } at := world.clients[1].nanoCast.readyAt.Add(time.Nanosecond) - client.movementStarted = at.Add(-time.Second) + world.characters[client.id].movement.updatedAt = at.Add(-time.Second) world.advanceNanos(at) - position := predictedPosition_locked(&recipient, client, at.Add(time.Second)) + position := predictedPosition_locked(&recipient, at.Add(time.Second)) - if client.movementStarted != at || recipient.position[2] < 7.499 || recipient.position[2] > 7.501 || position[2] < 12.049 || position[2] > 12.051 { + if world.characters[client.id].movement.updatedAt != at || recipient.position[2] < 7.499 || recipient.position[2] > 7.501 || position[2] < 12.049 || position[2] > 12.051 { t.Fatal("RunSpeed buff repriced the previous segment or omitted the new speed", recipient.position, position) } // Expiry must retain the buffed speed for the preceding segment only. expires := recipient.activeNanos[0].expiresAt recipient.position = [3]float32{0, 0, 3} - client.movementStarted = expires.Add(-time.Second) + world.characters[client.id].movement.updatedAt = expires.Add(-time.Second) world.advanceNanos(expires) - position = predictedPosition_locked(&recipient, client, expires.Add(time.Second)) - if client.movementStarted != expires || recipient.position[2] < 7.549 || recipient.position[2] > 7.551 || position[2] < 12.049 || position[2] > 12.051 || + position = predictedPosition_locked(&recipient, expires.Add(time.Second)) + if world.characters[client.id].movement.updatedAt != expires || recipient.position[2] < 7.549 || recipient.position[2] > 7.551 || position[2] < 12.049 || position[2] > 12.051 || recipient.nanoBonus(156) != 0 || len(newTestInventoryServer(t).characters[2].activeNanos) != 0 { t.Fatal("expired RunSpeed buff changed the previous segment or remained active", recipient.position, position) } diff --git a/server/social_actions_test.go b/server/social_actions_test.go @@ -206,11 +206,11 @@ func TestSocialActionKeepsPostureAndHeldMovement(t *testing.T) { world, _ := newCombatWorld() player, client := world.characters[1], world.clients[1] player.sitting, player.running = true, true - client.forward, client.strafing, client.turning = 1, true, true + world.characters[client.id].movement.forward, world.characters[client.id].movement.strafe, world.characters[client.id].movement.turn = 1, 1, 1 err := world.handleSocialAction(client, socialActionRequest(61)) - if err != nil || !player.sitting || !player.running || client.forward != 1 || !client.strafing || !client.turning { + if err != nil || !player.sitting || !player.running || world.characters[client.id].movement.forward != 1 || world.characters[client.id].movement.strafe == 0 || world.characters[client.id].movement.turn == 0 { t.Fatal("gesture changed posture or held movement") } } diff --git a/server/state.go b/server/state.go @@ -41,7 +41,8 @@ type character struct { nextAttack time.Time rechargeUntil time.Time running bool - follow *playerFollow + followTarget uint32 + movement playerMovement returnDoor *doorOrigin npc bool npcDefinitionID string @@ -74,10 +75,6 @@ type worldClient struct { loading bool id uint32 target bool - forward float32 - strafing bool - turning bool - movementStarted time.Time regenerationAt time.Time regenerationSeconds uint32 npcs map[uint32]bool diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -184,7 +184,7 @@ func TestTargetMovementIsPersistedAndRelayedToReleaseClient(t *testing.T) { if id == 2 { client.Write(targetPacket(n3Packet(0x570c2039, 50000, id, nil))) readPacket(clients[0]) - for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51} { + for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51, 78, 156} { packet, err := readPacket(clients[0]) if err != nil || binary.BigEndian.Uint32(packet[20:24]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[28:32]) != 2 || binary.BigEndian.Uint32(packet[36:40]) != stat { t.Fatalf("observer did not receive player combat foundations: %x %v", packet, err) diff --git a/server/vehicle_test.go b/server/vehicle_test.go @@ -193,13 +193,13 @@ func TestGroundVehicleMovementUsesNativeRunSpeed(t *testing.T) { health uint32 z float32 }{ - {"human forward", false, true, 1, 100, 90}, - {"human backward", false, true, -1, 100, -67}, - {"vehicle forward", true, true, 1, 100, 105}, - {"vehicle backward", true, true, -1, 100, -77.5}, - {"vehicle walking", true, false, 1, 100, 30}, - {"injured human", false, true, 1, 10, 70}, - {"injured vehicle", true, true, 1, 10, 80}, + {"human forward", false, true, 1, 100, 4.5}, + {"human backward", false, true, -1, 100, -3.35}, + {"vehicle forward", true, true, 1, 100, 5.25}, + {"vehicle backward", true, true, -1, 100, -3.875}, + {"vehicle walking", true, false, 1, 100, 1.5}, + {"injured human", false, true, 1, 10, 3.5}, + {"injured vehicle", true, true, 1, 10, 4}, } { t.Run(scenario.name, func(t *testing.T) { world, _ := newVehicleWorld(t) @@ -210,7 +210,7 @@ func TestGroundVehicleMovementUsesNativeRunSpeed(t *testing.T) { if scenario.worn { player.inventory.Items[0].Slot = 1 } - client.forward, client.movementStarted = scenario.forward, time.Now().Add(-30*time.Second) + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], scenario.forward, time.Now().Add(-time.Second)) response := httptest.NewRecorder() world.mapPlayers(response, httptest.NewRequest("GET", "/map/players", nil)) @@ -219,8 +219,8 @@ func TestGroundVehicleMovementUsesNativeRunSpeed(t *testing.T) { t.Fatal(err) } - if len(result.Players) != 1 || math.Abs(float64(result.Players[0].Position[2]-scenario.z)) > 0.0001 { - t.Fatalf("twenty-second native movement estimate: %+v", result.Players) + if len(result.Players) != 1 || math.Abs(float64(result.Players[0].Position[2]-scenario.z)) > 0.02 { + t.Fatalf("one-second native movement estimate: %+v", result.Players) } }) } @@ -230,26 +230,26 @@ func TestGroundVehicleSpeedChangesDoNotRepriceEarlierMovement(t *testing.T) { world, _ := newVehicleWorld(t) player, client := world.characters[1], world.clients[1] player.running, player.rotation = true, [4]float32{0, 0, 0, 1} - client.forward = 1 + player.movement = heldPlayerMovement(player, 1, time.Now()) if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { t.Fatal(err) } finish := client.equipment.readyAt - client.movementStarted = finish.Add(-10 * time.Second) + player.movement.updatedAt = finish.Add(-time.Second) world.advanceEquipment(finish) - if player.position != [3]float32{600, 67, 745} || client.movementStarted != finish { - t.Fatal("equipping applied the new speed to the previous ten seconds of movement") + if player.position != [3]float32{600, 67, 704.5} || player.movement.updatedAt != finish { + t.Fatal("equipping applied the new speed to the preceding movement segment") } if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil { t.Fatal(err) } finish = client.equipment.readyAt - client.movementStarted = finish.Add(-10 * time.Second) + player.movement.updatedAt = finish.Add(-time.Second) world.advanceEquipment(finish) - if player.position != [3]float32{600, 67, 797.5} || client.movementStarted != finish { - t.Fatal("removing the vehicle lost movement accumulated at vehicle speed") + if player.position[0] != 600 || player.position[1] != 67 || math.Abs(float64(player.position[2])-709.75) > .001 || player.movement.updatedAt != finish { + t.Fatal("removing the vehicle lost movement accumulated at vehicle speed", player.position, player.movement) } } diff --git a/server/whompah_test.go b/server/whompah_test.go @@ -55,7 +55,7 @@ func TestWhomPahHeldMovementRoundTripPersistsWithoutBouncing(t *testing.T) { world, first := newWhomPahWorld(t) player, old := world.characters[1], world.clients[1] now := time.Now() - old.forward, old.movementStarted = -1, now + world.characters[old.id].movement = heldPlayerMovement(world.characters[old.id], -1, now) world.advanceZoneCrossings(now.Add(1500 * time.Millisecond)) if player.playfield != 710 || player.position != [3]float32{388, 17.5, 382.484985} || player.returnDoor != nil { @@ -120,7 +120,7 @@ func TestWhomPahDoorPlaneAndSessionEligibility(t *testing.T) { world.zoneLinks["target"][705].Doors[0].Position = [3]float32{} world.characters[1].position = scenario.position client := world.clients[1] - client.forward, client.movementStarted = 1, time.Now() + world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now()) switch scenario.name { case "dead": world.characters[1].health = 0 @@ -130,7 +130,7 @@ func TestWhomPahDoorPlaneAndSessionEligibility(t *testing.T) { client.ready = false } - world.advanceZoneCrossings(client.movementStarted) + world.advanceZoneCrossings(world.characters[client.id].movement.updatedAt) if (world.characters[1].playfield == 710) != scenario.arrives { t.Fatal("door plane or player eligibility disagrees with the selected policy") diff --git a/server/world.go b/server/world.go @@ -112,34 +112,7 @@ func characterPacket(character *character) []byte { body = binary.BigEndian.AppendUint32(body, value) } body = binary.BigEndian.AppendUint16(body, character.baseScale()) - // 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 - } - // Sitting and flight retain the preferred walk/run mode for standing or landing. - binary.BigEndian.PutUint32(vehicle[22:26], uint32(vehicle[12])) - if character.flying() { - vehicle[12] = 7 - } else if character.sitting { - vehicle[12] = 8 - } + vehicle := character.vehicleState() body = binary.BigEndian.AppendUint32(body, uint32(len(vehicle))) body = append(body, vehicle...) head, textures := uint32(0), [5]uint32{} @@ -203,6 +176,7 @@ func playerCombatStatPackets(character *character) [][]byte { packets = append(packets, n3Packet(0x2b333d6e, 50000, character.id, body)) } } + packets = append(packets, playerMovementMassPackets(character)...) return packets } diff --git a/server/world_actions.go b/server/world_actions.go @@ -130,41 +130,30 @@ func (server *server) handleMovement(client *worldClient, body []byte) error { return nil } previousPosition := character.position + now := time.Now() + character.anchorMovement_locked(now) + oldPosition, oldRotation := character.position, character.rotation for i := range character.position { character.position[i] = math.Float32frombits(binary.BigEndian.Uint32(body[20+i*4:])) } for i := range character.rotation { character.rotation[i] = math.Float32frombits(binary.BigEndian.Uint32(body[32+i*4:])) } + // Native pose anchoring preserves speed, aligning velocity before the event. + if character.position != oldPosition || character.rotation != oldRotation { + forward, _ := bodyAxes(character.rotation) + speed := vectorLength(character.movement.velocity) * float32(character.movement.direction) + for axis := range forward { + character.movement.velocity[axis] = forward[axis] * speed + } + } playfield := character.playfield - client.movementStarted = time.Now() 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: - client.forward = -1 - case 2, 4: - client.forward = 0 - case 5, 7: - client.strafing = true - case 6, 8: - client.strafing = false - case 9, 11: - client.turning = true - case 10, 12: - client.turning = false - case 22, 23: - character.running = binary.BigEndian.Uint32(body[16:20]) == 23 + if action != 20 { + character.followTarget = 0 } + character.movement.action(character, action) + character.movement.previousPosition = character.position if client.trade != nil && !server.playerTradeAvailable_locked(client.trade.clients[0], client.trade.clients[1]) { server.cancelPlayerTrade_locked(client) } @@ -173,12 +162,8 @@ 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})) } - 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) + server.abortNano_locked(client, now, updates) } traceLog.Printf("Character %d action=%d position=%v", character.id, binary.BigEndian.Uint32(body[16:20]), character.position) destination := server.zoneDestination_locked(character, client) diff --git a/server/world_output_test.go b/server/world_output_test.go @@ -85,7 +85,7 @@ func TestWorldReplacementRemovesRemoteActorBeforeReplayingEquipment(t *testing.T } expected := []uint32{0x271b3a6b, 0x570c2039} - for range 11 { + for range 13 { expected = append(expected, 0x2b333d6e) } expected = append(expected, 0x3b1d2268, 0x35505644, 0x570c2039, 0x36510078) diff --git a/server/zoning.go b/server/zoning.go @@ -209,14 +209,14 @@ func (server *server) advanceZoneCrossings(now time.Time) { server.mutex.Lock() var destinations []userData for id, client := range server.clients { - if !client.ready || client.loading || client.forward == 0 && server.characters[id].follow == nil { + if !client.ready || client.loading || !server.characters[id].movement.active() && server.characters[id].followTarget == 0 { continue } character := *server.characters[id] if character.health == 0 { continue } - character.position = predictedPosition_locked(&character, client, now) + character.position = predictedPosition_locked(&character, now) if destination := server.zoneDestination_locked(&character, client); destination != nil { destinations = append(destinations, *destination) } @@ -229,26 +229,6 @@ 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) - if character.running || character.flying() { - speed = character.runningMovementSpeed(client.forward < 0) - } - x, y, z, w := character.rotation[0], character.rotation[1], character.rotation[2], character.rotation[3] - position := character.position - position[0] += float32(seconds) * speed * client.forward * (2*x*z + 2*y*w) - if character.flying() { - position[1] += float32(seconds) * speed * client.forward * (2*y*z - 2*x*w) - } - position[2] += float32(seconds) * speed * client.forward * (1 - 2*x*x - 2*y*y) - return position -} - func (character *character) runningMovementSpeed(backward bool) float32 { // Native movement reads RunSpeed without ability trickle-down. runSpeed := float32(100) diff --git a/server/zoning_test.go b/server/zoning_test.go @@ -133,7 +133,7 @@ func TestHeldWalkingCrossesDoorWithoutAnotherMovementPacket(t *testing.T) { t.Fatal(err) } world.mutex.Lock() - started := world.clients[1].movementStarted + started := world.characters[1].movement.updatedAt world.mutex.Unlock() done := make(chan struct{})