aorecomp

Anarchy Online classic in the browser

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


server/player_follow_test.go (26749B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/binary"
      6 	"encoding/hex"
      7 	"fmt"
      8 	"math"
      9 	"net"
     10 	"testing"
     11 	"time"
     12 )
     13 
     14 func TestPlayerFollowNativeWorldRequestReachesOwnerAndObserver(t *testing.T) {
     15 	world := newCheckpointWorld(t)
     16 	world.newCharacter().playfield = 950
     17 	startTestService(t, world)
     18 	client := connectZoningClient(t, world, true)
     19 	observer := &combatTestConn{}
     20 	observerClient := &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer}
     21 	callTestZone(t, world, 1, zoneTestCommand(func(state *server) error {
     22 		state.clients[2] = observerClient
     23 		state.clients[1].players = map[uint32]bool{2: true}
     24 		return nil
     25 	}))
     26 	// Captured /follow: owned subject, selected target, distance2.5, no correction/path.
     27 	captured, _ := hex.DecodeString("dfdf000a0001003a0000000100000002260f36710000c35000000001010000c350000000024020000000000000000000000000000000000000000000")
     28 	ping := systemPacket(1, nil)
     29 	binary.BigEndian.PutUint16(ping[2:4], 11)
     30 
     31 	if _, err := client.Write(captured); err != nil {
     32 		t.Fatal(err)
     33 	}
     34 	if _, err := client.Write(ping); err != nil {
     35 		t.Fatal(err)
     36 	}
     37 	response, err := readPacket(client)
     38 	if err != nil {
     39 		t.Fatal(err)
     40 	}
     41 	if binary.BigEndian.Uint32(response[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(response[29:33]) != 78 || binary.BigEndian.Uint32(response[33:37]) != 1500 {
     42 		t.Fatalf("native follow did not establish carried mass before motion: %x", response)
     43 	}
     44 	response, err = readPacket(client)
     45 	if err != nil {
     46 		t.Fatal(err)
     47 	}
     48 	if binary.BigEndian.Uint32(response[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(response[29:33]) != 156 || binary.BigEndian.Uint32(response[33:37]) != 5 {
     49 		t.Fatalf("mass update did not refresh native vehicle with raw RunSpeed: %x", response)
     50 	}
     51 	response, err = readPacket(client)
     52 	if err != nil {
     53 		t.Fatal(err)
     54 	}
     55 
     56 	if binary.BigEndian.Uint32(response[16:20]) != 0x260f3671 {
     57 		t.Fatalf("native /follow was ignored: %x", response)
     58 	}
     59 	if response[28] != 0 || !bytes.Equal(response[29:58], captured[29:58]) {
     60 		t.Fatalf("follow response changed the native target or route fields: %x", response)
     61 	}
     62 	pong, err := readPacket(client)
     63 	if err != nil || binary.BigEndian.Uint16(pong[2:4]) != 11 {
     64 		t.Fatal("following did not leave a usable world connection", err, pong)
     65 	}
     66 	observerClient.mutex.Lock()
     67 	defer observerClient.mutex.Unlock()
     68 	if len(observer.packets) != 3 || !bytes.Equal(observer.packets[2][16:58], response[16:58]) {
     69 		t.Fatalf("observer did not receive the same follow control: %x", observer.packets)
     70 	}
     71 }
     72 
     73 func playerFollowRequest(target uint32) []byte {
     74 	request := playerFollowPacket(1, target)[20:65]
     75 	binary.BigEndian.PutUint32(request[12:], 1)
     76 	return request
     77 }
     78 
     79 func TestPlayerFollowRejectsUntrustedTargetsAndRoutes(t *testing.T) {
     80 	for _, scenario := range []string{"short", "long", "foreign owner", "subject type", "target type", "pass-on", "scalar", "admin", "correction", "waypoints", "missing target", "dead target", "other zone", "unseen NPC", "offline player", "loading player", "loading owner", "unready owner", "dead owner", "sitting owner", "replaced owner", "unsupported client"} {
     81 		t.Run(scenario, func(t *testing.T) {
     82 			world, output := newCombatWorld(t)
     83 			player, client := world.characters[1], world.clients[1]
     84 			target := world.characters[1000000]
     85 			request := playerFollowRequest(target.id)
     86 			switch scenario {
     87 			case "short":
     88 				request = request[:44]
     89 			case "long":
     90 				request = append(request, 0)
     91 			case "foreign owner":
     92 				binary.BigEndian.PutUint32(request[8:], 2)
     93 			case "subject type":
     94 				binary.BigEndian.PutUint32(request[4:], 51035)
     95 			case "target type":
     96 				binary.BigEndian.PutUint32(request[16:], 51035)
     97 			case "pass-on":
     98 				binary.BigEndian.PutUint32(request[12:], 0)
     99 			case "scalar":
    100 				binary.BigEndian.PutUint32(request[24:], 0x7f800000)
    101 			case "admin":
    102 				request[28] = 23
    103 			case "correction":
    104 				request[29] = 1
    105 			case "waypoints":
    106 				binary.BigEndian.PutUint32(request[41:], 1)
    107 			case "missing target":
    108 				binary.BigEndian.PutUint32(request[20:], 99)
    109 			case "dead target":
    110 				target.health = 0
    111 			case "other zone":
    112 				target.playfield = 705
    113 			case "unseen NPC":
    114 				delete(client.npcs, target.id)
    115 			case "offline player":
    116 				target.npc = false
    117 			case "loading player":
    118 				target.npc = false
    119 				world.clients[target.id] = &worldClient{id: target.id, ready: true, loading: true}
    120 			case "loading owner":
    121 				client.loading = true
    122 			case "unready owner":
    123 				client.ready = false
    124 			case "dead owner":
    125 				player.health = 0
    126 			case "sitting owner":
    127 				player.sitting = true
    128 			case "replaced owner":
    129 				world.clients[1] = &worldClient{id: 1}
    130 			case "unsupported client":
    131 				client.target = false
    132 			}
    133 
    134 			err := world.handlePlayerFollow(client, request)
    135 
    136 			if (err != nil) != (scenario == "short" || scenario == "long") || world.characters[client.id].followTarget != 0 || len(output.packets) != 0 {
    137 				t.Fatal("untrusted follow changed state", err, world.characters[client.id].followTarget, len(output.packets))
    138 			}
    139 		})
    140 	}
    141 }
    142 
    143 func TestPlayerFollowAcceleratesAndArrivesWithoutNativeMovementSnapshots(t *testing.T) {
    144 	world, _ := newCombatWorld(t)
    145 	player, client := world.characters[1], world.clients[1]
    146 	world.characters[1000000].position = [3]float32{30, 0, 0}
    147 	if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
    148 		t.Fatal(err)
    149 	}
    150 	start := world.characters[client.id].movement.updatedAt
    151 
    152 	world.advancePlayerMovement(start.Add(100 * time.Millisecond))
    153 	first := player.position
    154 	for tick := 2; tick <= 300; tick++ {
    155 		world.advancePlayerMovement(start.Add(time.Duration(tick) * 100 * time.Millisecond))
    156 	}
    157 	arrived := player.position
    158 	world.advancePlayerMovement(start.Add(31 * time.Second))
    159 
    160 	if math.Abs(float64(first[0])-0.03) > 0.000001 || first[1] != 0 || first[2] != 0 {
    161 		t.Fatal("follow did not use native force-limited acceleration", first)
    162 	}
    163 	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{} {
    164 		t.Fatal("follow failed to arrive four units short and halt", player.position, world.characters[client.id].followTarget)
    165 	}
    166 	if predictedPosition(player, start.Add(time.Hour)) != arrived || math.Abs(float64(player.rotation[1])-math.Sqrt(0.5)) > 0.000001 {
    167 		t.Fatal("position consumer or heading diverged", player.position, player.rotation)
    168 	}
    169 }
    170 
    171 func TestPlayerFollowChainsUseOneTargetSnapshot(t *testing.T) {
    172 	world, _ := newCombatWorld(t)
    173 	world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{10, 0, 0}}
    174 	world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, target: true, conn: &combatTestConn{}}
    175 	world.clients[1].players = map[uint32]bool{2: true}
    176 	if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(2)); err != nil {
    177 		t.Fatal(err)
    178 	}
    179 	request := playerFollowRequest(1)
    180 	binary.BigEndian.PutUint32(request[8:], 2)
    181 	if err := world.handlePlayerFollow(world.clients[2], request); err != nil {
    182 		t.Fatal(err)
    183 	}
    184 	now := time.Now()
    185 	world.characters[1].movement.updatedAt, world.characters[2].movement.updatedAt = now, now
    186 
    187 	world.advancePlayerMovement(now.Add(100 * time.Millisecond))
    188 
    189 	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 {
    190 		t.Fatal("cyclic follow depended on map iteration order", world.characters[1].position, world.characters[2].position)
    191 	}
    192 }
    193 
    194 func TestPlayerFollowTargetLossClearsNativeController(t *testing.T) {
    195 	for _, scenario := range []string{"despawn", "death", "zone", "interest", "owner death", "owner loading"} {
    196 		t.Run(scenario, func(t *testing.T) {
    197 			world, output := newCombatWorld(t)
    198 			client := world.clients[1]
    199 			world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now())
    200 			if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
    201 				t.Fatal(err)
    202 			}
    203 			switch scenario {
    204 			case "despawn":
    205 				delete(world.characters, 1000000)
    206 			case "death":
    207 				world.characters[1000000].health = 0
    208 			case "zone":
    209 				world.characters[1000000].playfield = 705
    210 			case "interest":
    211 				delete(client.npcs, 1000000)
    212 			case "owner death":
    213 				world.characters[1].health = 0
    214 			case "owner loading":
    215 				client.loading = true
    216 			}
    217 
    218 			now := time.Now()
    219 			world.advancePlayerMovement(now)
    220 			world.advancePlayerMovement(now.Add(time.Second))
    221 
    222 			if world.characters[client.id].followTarget != 0 || world.characters[client.id].movement.forward != 0 || len(output.packets) != 5 {
    223 				t.Fatal("target loss did not clear exactly once", world.characters[client.id].followTarget, output.packets)
    224 			}
    225 			for index, action := range []uint32{2, 4} {
    226 				packet := output.packets[3+index]
    227 				if binary.BigEndian.Uint32(packet[16:20]) != 0x54111123 || binary.BigEndian.Uint32(decodeMovement1491(packet[29:])) != action {
    228 					t.Fatal("target loss did not release both native movement directions", packet)
    229 				}
    230 			}
    231 			if predictedPosition(world.characters[client.id], now.Add(2*time.Second)) != world.characters[client.id].position {
    232 				t.Fatal("target loss retained held forward movement")
    233 			}
    234 		})
    235 	}
    236 }
    237 
    238 func TestPlayerFollowMovementCheckpointsWithoutTickDatabaseWrites(t *testing.T) {
    239 	world := newCheckpointWorld(t)
    240 	world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{80, 14, 56}}
    241 	world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, conn: &combatTestConn{}}
    242 	client := &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}}
    243 	world.clients[1] = client
    244 	client.players = map[uint32]bool{2: true}
    245 	if err := world.handlePlayerFollow(client, playerFollowRequest(2)); err != nil {
    246 		t.Fatal(err)
    247 	}
    248 	start := world.characters[client.id].movement.updatedAt
    249 	world.characters[1].nextPositionSave = start.Add(20 * time.Second)
    250 	auditCheckpointWrites(t, world)
    251 
    252 	for tick := 1; tick <= 10; tick++ {
    253 		world.advancePlayerMovement(start.Add(time.Duration(tick) * 100 * time.Millisecond))
    254 	}
    255 	if writes := checkpointWrites(t, world); len(writes) != 0 {
    256 		t.Fatal("follow tick churned SQLite", writes)
    257 	}
    258 	if err := world.flushPositions(start.Add(20 * time.Second)); err != nil {
    259 		t.Fatal(err)
    260 	}
    261 	restored := newTestInventoryServer(t).characters[1]
    262 
    263 	if restored.position != world.characters[1].position || restored.position[0] <= 52 || checkpointWrites(t, world)["characters/UPDATE"] != 1 {
    264 		t.Fatal("follow checkpoint failed", restored.position, checkpointWrites(t, world))
    265 	}
    266 }
    267 
    268 func TestPlayerFollowMouseRotationPreservesControllerAndManualMovementCancels(t *testing.T) {
    269 	for _, moving := range []bool{false, true} {
    270 		for _, action := range []byte{1, 2, 3, 4, 9, 20, 22, 23} {
    271 			t.Run(fmt.Sprintf("%d/moving=%t", action, moving), func(t *testing.T) {
    272 				world, _ := newEquipmentWorld(t)
    273 				player, client := world.characters[1], world.clients[1]
    274 				target := &character{id: 1000000, npc: true, playfield: player.playfield, health: 100, position: player.position}
    275 				if moving {
    276 					target.position[0] += 30
    277 				}
    278 				world.characters[target.id] = target
    279 				client.npcs = map[uint32]bool{target.id: true}
    280 				if err := world.handlePlayerFollow(client, playerFollowRequest(target.id)); err != nil {
    281 					t.Fatal(err)
    282 				}
    283 				follow := player.followTarget
    284 				world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond))
    285 				request := append([]byte(nil), npcMovementPacket(player, uint32(action))[20:36]...)
    286 				request = append(request, encodeMovement1491(npcMovementPacket(player, uint32(action))[36:76])...)
    287 				if action == 20 {
    288 					request = mouseMovementRequest()
    289 				}
    290 
    291 				err := world.handleMovement(client, request)
    292 
    293 				forward := float32(0)
    294 				if action == 1 || moving && action != 2 {
    295 					forward = 1
    296 				}
    297 				if action == 3 {
    298 					forward = -1
    299 				}
    300 				if err != nil || (player.followTarget == follow) != (action == 20) || world.characters[client.id].movement.forward != forward {
    301 					t.Fatal("movement follow cancellation or throttle", action, err, player.followTarget, world.characters[client.id].movement.forward, forward)
    302 				}
    303 			})
    304 		}
    305 	}
    306 }
    307 
    308 func TestPlayerFollowRootSuspendsAndResumesController(t *testing.T) {
    309 	world, _ := newCombatWorld(t)
    310 	player, client := world.characters[1], world.clients[1]
    311 	world.characters[1000000].position = [3]float32{30, 0, 0}
    312 	if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
    313 		t.Fatal(err)
    314 	}
    315 	now := world.characters[client.id].movement.updatedAt
    316 	player.activeNanos = []activeNano{{program: 42110}}
    317 
    318 	world.advancePlayerMovement(now.Add(100 * time.Millisecond))
    319 	rooted := player.position
    320 	player.activeNanos = nil
    321 	world.advancePlayerMovement(now.Add(200 * time.Millisecond))
    322 
    323 	if rooted != [3]float32{} || math.Abs(float64(player.position[0])-0.03) > 0.000001 || world.characters[client.id].followTarget == 0 {
    324 		t.Fatal("root did not suspend and resume following", rooted, player.position, world.characters[client.id].followTarget)
    325 	}
    326 }
    327 
    328 func TestPlayerFollowLateObserverGetsControllerAfterBothActorSnapshots(t *testing.T) {
    329 	world := newCheckpointWorld(t)
    330 	world.characters[1000000] = &character{id: 1000000, npc: true, name: "Target", appearance: 229, level: 1, playfield: 950, health: 100, position: [3]float32{70, 14, 56}}
    331 	world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000000: true}}
    332 	if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
    333 		t.Fatal(err)
    334 	}
    335 	world.newCharacter().playfield = 950
    336 	cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0})
    337 	binary.BigEndian.PutUint16(cookie, 0xdfdf)
    338 	cookie = append(cookie, targetPacket(n3Packet(0x570c2039, 50000, 2, nil))...)
    339 	address, peer := net.Pipe()
    340 	defer address.Close()
    341 	defer peer.Close()
    342 	connection := &combatInterestConn{combatTestConn: combatTestConn{Conn: address}, input: bytes.NewReader(cookie)}
    343 
    344 	if err := serveWorldClient(world, &worldClient{conn: connection, loading: true}); err != nil {
    345 		t.Fatal(err)
    346 	}
    347 
    348 	var controls int
    349 	actors := make(map[uint32]bool)
    350 	for _, packet := range connection.packets {
    351 		if binary.BigEndian.Uint32(packet[16:20]) == 0x271b3a6b {
    352 			actors[binary.BigEndian.Uint32(packet[24:28])] = true
    353 		}
    354 		if binary.BigEndian.Uint32(packet[16:20]) == 0x260f3671 {
    355 			controls++
    356 			if !actors[1] || !actors[1000000] || binary.BigEndian.Uint32(packet[24:28]) != 1 || binary.BigEndian.Uint32(packet[33:37]) != 1000000 || math.Float32frombits(binary.BigEndian.Uint32(packet[42:])) != 52 {
    357 				t.Fatal("wrong follow replay", packet)
    358 			}
    359 		}
    360 	}
    361 	if controls != 2 {
    362 		t.Fatal("late observer follow replay count", controls)
    363 	}
    364 }
    365 
    366 func TestPlayerForceIntegratorRetainsMassAndForceCeiling(t *testing.T) {
    367 	for _, scenario := range []struct {
    368 		name                     string
    369 		mass, force, limit, want float32
    370 	}{
    371 		{"body force", 10, 60, 30, .3}, {"carried force", 10, 60, 60, .6}, {"force ceiling", 10000, 60000, 10000, .1},
    372 	} {
    373 		t.Run(scenario.name, func(t *testing.T) {
    374 			movement := playerMovement{}
    375 
    376 			movement.integrateForce([3]float32{scenario.force, 0, 0}, .1, scenario.mass, 1.5, scenario.limit)
    377 
    378 			if math.Abs(float64(movement.velocity[0]-scenario.want)) > .000001 {
    379 				t.Fatal(movement.velocity, scenario.want)
    380 			}
    381 		})
    382 	}
    383 }
    384 
    385 func TestPlayerFollowMassUsesNativeBreedSexAndCarriedSlots(t *testing.T) {
    386 	for _, scenario := range []struct {
    387 		breed, sex uint16
    388 		mass       float32
    389 	}{
    390 		{1, 2, .08}, {1, 3, .07}, {2, 2, .075}, {2, 3, .065}, {3, 2, .075}, {3, 3, .06}, {4, 1, .1},
    391 	} {
    392 		t.Run(fmt.Sprintf("%d/%d", scenario.breed, scenario.sex), func(t *testing.T) {
    393 			player := &character{appearance: (appearanceFields{Breed: scenario.breed, Sex: scenario.sex}).packed()}
    394 			player.inventory.Items = []ownedItem{
    395 				{Type: 51018, Template: 121567, Quality: 1, Slot: 64, Count: 1},
    396 				{Type: 51018, Template: 121567, Quality: 1, Slot: 6, Count: 1},
    397 				{Type: 51017, Template: 206730, Quality: 50, Slot: 65, Count: 1},
    398 			}
    399 			player.inventory.Bank = []ownedItem{{Type: 51018, Template: 121567, Slot: 0, Count: 1}}
    400 
    401 			body, carried := player.movementMass()
    402 
    403 			if math.Abs(float64(body-scenario.mass)) > .000001 || carried != 1500 {
    404 				t.Fatal("native mass included equipment/bank/Chest or lost carried item", body, carried)
    405 			}
    406 		})
    407 	}
    408 }
    409 
    410 func TestPlayerFollowArrivalToleranceAndCrossing(t *testing.T) {
    411 	for _, scenario := range []struct {
    412 		name                   string
    413 		target, previous, want float32
    414 	}{
    415 		{"inside offset", 3, 0, 0}, {"offset", 4, 0, 0}, {"inside tolerance", 4.125, 0, 0},
    416 		{"outside tolerance", 4.25, 0, .03}, {"crossed goal", 10, 7, 0},
    417 	} {
    418 		t.Run(scenario.name, func(t *testing.T) {
    419 			world, _ := newCombatWorld(t)
    420 			player := world.characters[1]
    421 			world.characters[1000000].position = [3]float32{scenario.target, 0, 0}
    422 			if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
    423 				t.Fatal(err)
    424 			}
    425 			player.movement.previousPosition = [3]float32{scenario.previous, 0, 0}
    426 
    427 			world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond))
    428 
    429 			if math.Abs(float64(player.position[0]-scenario.want)) > .000001 {
    430 				t.Fatal("native arrival boundary", player.position, scenario.want)
    431 			}
    432 		})
    433 	}
    434 }
    435 
    436 func TestPlayerFollowMotionInterruptsCastAndRefundsReservation(t *testing.T) {
    437 	world, _ := newNanoCastingWorld(t)
    438 	player, client := world.characters[1], world.clients[1]
    439 	world.characters[1000000].position = [3]float32{15, 0, 0}
    440 	if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]); err != nil {
    441 		t.Fatal(err)
    442 	}
    443 	if client.nanoCast == nil {
    444 		t.Fatal("cast was not admitted")
    445 	}
    446 	if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
    447 		t.Fatal(err)
    448 	}
    449 	now := world.characters[client.id].movement.updatedAt
    450 
    451 	world.advancePlayerMovement(now.Add(100 * time.Millisecond))
    452 
    453 	if client.nanoCast != nil || player.nanoReserved != 0 || player.nano != 30 || player.position[0] <= 0 {
    454 		t.Fatal("follow retained cast or lost reservation", client.nanoCast, player.nanoReserved, player.nano, player.position)
    455 	}
    456 }
    457 
    458 func TestPlayerFollowRetargetingPreservesVelocity(t *testing.T) {
    459 	world, _ := newCombatWorld(t)
    460 	world.characters[1000000].position = [3]float32{30, 0, 0}
    461 	client := world.clients[1]
    462 	if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
    463 		t.Fatal(err)
    464 	}
    465 	world.advancePlayerMovement(world.characters[client.id].movement.updatedAt.Add(100 * time.Millisecond))
    466 	velocity := world.characters[client.id].movement.velocity
    467 	world.characters[2] = &character{id: 2, playfield: 950, health: 100}
    468 	world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, conn: &combatTestConn{}}
    469 
    470 	client.players = map[uint32]bool{2: true}
    471 	err := world.handlePlayerFollow(client, playerFollowRequest(2))
    472 
    473 	if err != nil || world.characters[client.id].followTarget != 2 || world.characters[client.id].movement.velocity != velocity {
    474 		t.Fatal("retarget reset native motion", err, world.characters[client.id].followTarget)
    475 	}
    476 }
    477 
    478 func TestPlayerFollowSnapshotIncludesVelocityBeforeLateReplay(t *testing.T) {
    479 	world, _ := newCombatWorld(t)
    480 	player := world.characters[1]
    481 	player.name, player.appearance = "Follower", 0x315
    482 	world.characters[1000000].position = [3]float32{30, 0, 0}
    483 	if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
    484 		t.Fatal(err)
    485 	}
    486 	world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond))
    487 
    488 	packet := characterPacket(player)
    489 
    490 	// The variable name is followed by 20 auxiliary/ability bytes, level and 14 bases.
    491 	vehicleOffset := 71 + len(player.name) + 20 + 1 + 14
    492 	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)) {
    493 		t.Fatal("late actor snapshot lost follow velocity", vehicleOffset, packet, player.movement.velocity)
    494 	}
    495 }
    496 
    497 func TestPlayerFollowChecksTradeRangeAfterBothTradersMove(t *testing.T) {
    498 	world, _ := newCombatWorld(t)
    499 	world.characters[1000000].position = [3]float32{0, 0, 30}
    500 	world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{4.99999, 0, 0}}
    501 	world.characters[1000001] = &character{id: 1000001, npc: true, playfield: 950, health: 100, position: [3]float32{4.99999, 0, 30}}
    502 	world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000001: true}}
    503 	playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
    504 	if world.clients[1].trade == nil {
    505 		t.Fatal("trade was not admitted")
    506 	}
    507 	if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
    508 		t.Fatal(err)
    509 	}
    510 	request := playerFollowRequest(1000001)
    511 	binary.BigEndian.PutUint32(request[8:], 2)
    512 	if err := world.handlePlayerFollow(world.clients[2], request); err != nil {
    513 		t.Fatal(err)
    514 	}
    515 	now := time.Now()
    516 	world.characters[1].movement.updatedAt, world.characters[2].movement.updatedAt = now, now
    517 
    518 	world.advancePlayerMovement(now.Add(100 * time.Millisecond))
    519 
    520 	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 {
    521 		t.Fatal("partial follow frame cancelled an in-range trade", world.characters[1].position, world.characters[2].position)
    522 	}
    523 }
    524 
    525 func TestPlayerFollowRunningStartUsesNativeRestThenForwardParameters(t *testing.T) {
    526 	world, _ := newCombatWorld(t)
    527 	player := world.characters[1]
    528 	player.running = true
    529 	player.stats.Speed.RunSpeed = 10
    530 	world.characters[1000000].position = [3]float32{30, 0, 0}
    531 	if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(1000000)); err != nil {
    532 		t.Fatal(err)
    533 	}
    534 	now := player.movement.updatedAt
    535 
    536 	world.advancePlayerMovement(now.Add(100 * time.Millisecond))
    537 	first := player.position[0]
    538 	world.advancePlayerMovement(now.Add(200 * time.Millisecond))
    539 
    540 	if math.Abs(float64(first)-.0607) > .000001 || math.Abs(float64(player.position[0])-.2024) > .000001 {
    541 		t.Fatal("native follow start did not switch its movement parameters", first, player.position)
    542 	}
    543 }
    544 
    545 func TestLateObserverRestoresHeldPlayerInputAndCurrentPose(t *testing.T) {
    546 	for _, scenario := range []struct {
    547 		forward float32
    548 		action  uint32
    549 		z       float32
    550 	}{{1, 1, 86}, {-1, 3, 26}} {
    551 		t.Run(fmt.Sprint(scenario.forward), func(t *testing.T) {
    552 			world := newCheckpointWorld(t)
    553 			world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}}
    554 			at := time.Now()
    555 			started := at.Add(-20 * time.Second)
    556 			world.characters[1].movement = heldPlayerMovement(world.characters[1], scenario.forward, started)
    557 			for tick := 1; tick <= 200; tick++ {
    558 				world.advancePlayerMovement(started.Add(time.Duration(tick) * 100 * time.Millisecond))
    559 			}
    560 			world.newCharacter().playfield = 950
    561 			cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0})
    562 			binary.BigEndian.PutUint16(cookie, 0xdfdf)
    563 			cookie = append(cookie, targetPacket(n3Packet(0x570c2039, 50000, 2, nil))...)
    564 			address, peer := net.Pipe()
    565 			defer address.Close()
    566 			defer peer.Close()
    567 			connection := &combatInterestConn{combatTestConn: combatTestConn{Conn: address}, input: bytes.NewReader(cookie)}
    568 
    569 			if err := serveWorldClient(world, &worldClient{conn: connection, loading: true}); err != nil {
    570 				t.Fatal(err)
    571 			}
    572 
    573 			var actions []uint32
    574 			for _, packet := range connection.packets {
    575 				if binary.BigEndian.Uint32(packet[16:20]) == 0x54111123 && binary.BigEndian.Uint32(packet[24:28]) == 1 {
    576 					body := decodeMovement1491(packet[29:])
    577 					actions = append(actions, binary.BigEndian.Uint32(body))
    578 					if math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(body[12:]))-scenario.z)) > .125 {
    579 						t.Fatal("late observer lost held input or pose", packet)
    580 					}
    581 				}
    582 			}
    583 			want := "[20 20]"
    584 			if scenario.forward < 0 {
    585 				want = "[4 3 20 4 3 20]"
    586 			}
    587 			if fmt.Sprint(actions) != want {
    588 				t.Fatal("initial and ready movement replay", actions)
    589 			}
    590 		})
    591 	}
    592 }
    593 
    594 func TestPlayerFollowStationaryTerrainDoesNotInterruptCast(t *testing.T) {
    595 	world, _ := newNanoCastingWorld(t)
    596 	player, client := world.characters[1], world.clients[1]
    597 	var err error
    598 	world.terrain, err = readTerrain()
    599 	if err != nil {
    600 		t.Fatal(err)
    601 	}
    602 	player.playfield, player.position = 705, [3]float32{960.625, 16.5, 510.625}
    603 	target := world.characters[1000000]
    604 	target.playfield, target.position = 705, [3]float32{961, 16.5, 511}
    605 	if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 29618})[20:]); err != nil {
    606 		t.Fatal(err)
    607 	}
    608 	cast := client.nanoCast
    609 	if cast == nil {
    610 		t.Fatal("cast was not admitted")
    611 	}
    612 	if err := world.handlePlayerFollow(client, playerFollowRequest(target.id)); err != nil {
    613 		t.Fatal(err)
    614 	}
    615 
    616 	world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond))
    617 
    618 	if player.position != [3]float32{960.625, 16.5, 510.625} || client.nanoCast != cast || player.nanoReserved != 9 {
    619 		t.Fatal("stationary terrain projection moved the actor or cancelled its cast", player.position, client.nanoCast, player.nanoReserved)
    620 	}
    621 }
    622 
    623 func TestPlayerFollowCastAdmissionUsesActualMotion(t *testing.T) {
    624 	for _, scenario := range []struct {
    625 		name     string
    626 		distance float32
    627 		reserved uint32
    628 	}{{"stationary", 3, 9}, {"moving", 15, 0}} {
    629 		t.Run(scenario.name, func(t *testing.T) {
    630 			world, _ := newNanoCastingWorld(t)
    631 			player, client := world.characters[1], world.clients[1]
    632 			world.characters[1000000].position = [3]float32{scenario.distance, 0, 0}
    633 			if err := world.handlePlayerFollow(client, playerFollowRequest(1000000)); err != nil {
    634 				t.Fatal(err)
    635 			}
    636 			world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond))
    637 
    638 			err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:])
    639 
    640 			if err != nil || player.nanoReserved != scenario.reserved || player.nano != 30-scenario.reserved || (client.nanoCast != nil) != (scenario.reserved != 0) {
    641 				t.Fatal("cast admission ignored automatic motion", err, player.nano, player.nanoReserved, client.nanoCast)
    642 			}
    643 		})
    644 	}
    645 }