aorecomp

Anarchy Online classic in the browser

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


commit f969ed81f968744525c6f207678d45d335190a78
parent 0923ace04396499cebb5a831c76a4678276b5365
Author: anon <anon@example.com>
Date:   Tue, 13 Oct 2026 01:58:31 +0000

Implement automatic zoning from original client door and boundary data

Diffstat:
M.gitignore | 2++
MREADME.md | 1+
Mdocs/README.md | 1+
Adocs/zoning.md | 170+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/control.go | 1+
Mserver/main.go | 27+++++++++++++++++++++++++--
Mserver/main_test.go | 2++
Mserver/npc_data_test.go | 3+++
Mserver/npcs_test.go | 2+-
Mserver/roaming_test.go | 7+++++++
Mserver/state.go | 21++++++++++++++++-----
Mserver/target_protocol_test.go | 5+++++
Mserver/users.go | 22++++++++++++----------
Aserver/zoning.go | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/zoning_test.go | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
15 files changed, 696 insertions(+), 18 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -6,6 +6,7 @@ tools/*.7z tools/*.exe tools/*.log tools/cellao-reference/ +tools/aotomation-reference/ tools/browser-reference/ tools/rust/ browser/**/target/ @@ -23,6 +24,7 @@ patches/* !patches/manifest.json data/*.bin data/npc_spawns.yaml +data/zone_links.yaml data/users.yaml data/users.yaml.tmp node_modules/ diff --git a/README.md b/README.md @@ -21,6 +21,7 @@ From this directory in PowerShell: ```powershell .\venv\Scripts\python.exe tools\patch_local.py +.\venv\Scripts\python.exe tools\extract_zone_links.py & 'C:\Program Files\Go\bin\go.exe' run ./server ``` diff --git a/docs/README.md b/docs/README.md @@ -19,6 +19,7 @@ current feature status. Read the source for implementation details and the | [protocol.md](protocol.md) | Framing, compression, login, entity messages, zoning, time, appearance, and original reader/activation addresses. | | [protocol-13.2.md](protocol-13.2.md) | Recovered 13.2 envelope, appearance, character, movement, and teleport differences, with native runtime checks. | | [game-data.md](game-data.md) | Resource database, map/terrain decoding, original district populations, monster appearances, and unresolved template links. | +| [zoning.md](zoning.md) | Fixed door links, shared interior returns, boundary lines and portal polygons, native trigger behavior, and unresolved mission destinations. | | [reverse-engineering.md](reverse-engineering.md) | Original binary hashes, saved evidence/snapshots, capture locations, and analysis recovery. | | [open-questions.md](open-questions.md) | Unknown semantics, failed experiments worth preserving, and other server projects as research leads. | | [browser-porting.md](browser-porting.md) | Approach comparison, bounded runtime assessment, and the initial original-terrain browser scene. | diff --git a/docs/zoning.md b/docs/zoning.md @@ -0,0 +1,170 @@ +# Doors and zone boundaries + +The client database contains fixed shop/venue destinations and paired outdoor +boundary lines. Mission entrances have separate records, but their destination +is assigned by a server mission. A mission door ID is not a fixed destination +playfield ID. + +## Fixed doors + +Resource **1000026** contains length-prefixed statels. A statel starts with +little-endian type/instance identities, playfield, XYZ position, quaternion +in **WZYX** order, template ID and a length-prefixed HighLow descriptor. +The descriptor's events/functions use big-endian fields. + +Type **51016 (0xc748)** identifies doors used by the teleport functions. Do +not substitute type 56006 or join different statel types merely because they +share the same instance number: their transforms can describe different things. + +A recovered fixed entrance has a leading **OnEnter event 16**, containing +**TeleportProxy function 53082**. Its four arguments are: + +| Argument | Meaning | +| --- | --- | +| 0 | Destination category; 51102 is a concrete playfield, 51105 is a mission/proxy destination. | +| 1 | Destination playfield instance. | +| 2 | Door index within the destination. | +| 3 | External/source door instance. | + +The corresponding destination door instance is +`0xc0000000 | destination_playfield | (door_index << 16)`. +The destination is its authored transform, with a small displacement along +the rotated +Z axis to place the character beyond the entrance. + +For example, Omni Entertainment (705), door `0xc01102c1`, points to the basic +equipment shop (1183), door `0xc000049f`. The entrance is approximately +`[765.0848, 19.1349, 516.5070]`; the interior door is +`[187.0007, 5, 116.0100]`. The same shop interior can serve several exterior +entrances. Its return destination therefore needs per-character context: +the external playfield and door instance. A global reverse mapping would +return some characters to the wrong entrance or city. + +The recovered 11.0 data resolves 1,213 fixed links; 13.2 resolves 1,170. +These counts cover single leading unconditional OnEnter TeleportProxy events. +They do not mean every door script has been decoded. In each version, 202 +leading functions have dynamic destinations and 48 concrete references lack +a matching destination door. Other event/function forms are not enabled by +this bounded extraction. Requirements must be interpreted before gated +functions can be enabled. + +Resource **1000030** supplies mission-door metadata, including position and +packed IDs. Its 47-byte records are not a complete fixed shop routing table. +Apartment ownership, missions, keys and similar server assignments remain +separate from the fixed links. + +## Outdoor boundaries + +Resource **1000021** contains closed vertex groups. Each 16-byte vertex is +`int16 destination_playfield`, `uint8 destination_index`, `uint8 flags`, then +three little-endian floats. A segment takes its destination from its **second +vertex**. Nonpositive destination playfields do not supply a fixed transition. + +Resource **1000001** ends with destination lines: a count followed by 28-byte +records containing a packed playfield/index and two XYZ endpoints. A source +wall references a destination line in another playfield. Position along the +source segment becomes position along the destination segment; a displacement +along the destination's left normal places the player inside the new zone. +The databases supply 394 resolved source segments per tested client. + +The tail can be located by a bounded count search, validating every packed +identity and requiring one candidate. This decodes the destination section; +it does not establish the layout of the entire playfield definition. + +Resource **1000013**, version 4, supplies exact tile portal polygons. The +resource instance packs `playfield << 16 | tile_index`. Its payload starts +with a little-endian uncompressed length and a zlib stream. The inflated blob +contains three length-prefixed sections: main KDTree, invisible KDTree and +PortalArea. Nonempty trees start with `KDTreeFile\0`. PortalArea contains a +point count, two path bounds, XYZ points, and two localizer DWORDs; its size +is `20 + point_count * 12`. Localizer type 53059 and the packed instance +identify a destination playfield/index. + +Native polygon membership uses **X/Z**, ignoring Y. The three recovered Omni +Entertainment tile portals point to HQ (700) and Omni Forest (716), with Omni Forest using +two different destination lines. They do not describe the shop-door triggers. +The full 13.2 surface inspection found 8,395 PortalArea records among 155,931 +surface resources; not all are outdoor boundaries paired with 1000021 walls. + +## Native behavior and protocol + +The client sends **CharDCMove 0x54111123** start/stop controls and occasional +position updates. Action **20** occurs when the native portal test starts a +teleport attempt, but also periodically during ordinary motion. It cannot +by itself authorize zoning: the position must match a mapped trigger. + +Door collision also opens the visual door locally. The traced native opening +path sends no dedicated teleport request. A server therefore needs continuous +trigger checks while movement remains active. Forward/backward extrapolation +is enough for an initial implementation; matching acceleration, collision +surfaces, stairs, turning and other vehicle modes requires more physics work. +Received positions provide the authoritative anchors for that extrapolation. + +The tested character initializes in walking mode 2: **1.5 m/s**. Native 13.2 +running uses `min(15, 4 + RunSpeed*.005)` forward and +`min(15, 3 + RunSpeed*.0035)` backward. With the current RunSpeed 100 those are +4.5 and 3.35 m/s. Encumbrance also modifies effective RunSpeed. These running +coefficients are version-specific; later emulator formulas and original 11.0 +analysis are not interchangeable with the 13.2 instructions. + +**LookAt 0x2252445f** targets an identity but is not a zone request. +**GenericCmd 0x52526858**, action 3, is Use. In the 13.2 N3 body, its action +is at offset 24, user identity at 32, target identity at 40. The native +**Teleport 0x43197d22** class rejects client-originated use. Actual transitions +use the already verified server Teleport plus system redirect/reconnect sequence. + +During reconnection the native client can send action 20 at its previous +position before **CharacterReady 0x570c2039**. Those loading-time coordinates +must not overwrite the destination position. In 13.2, +`llr.dll:n3TeleportIIR_t::Activate` at `0x1003db10` handles a nonzero playfield +proxy by stopping the current playfield, rather than immediately applying XYZ. +The destination initialization establishes the new position. + +Exact fixed-door trigger shapes remain unresolved. Small horizontal entrance +areas with a vertical tolerance are a provisional interpretation of the +authored transforms. Full world collision is needed to prevent straight-line +prediction from finding a portal through an intervening wall. Returned door +positions and rotations are extracted data; trigger extents and the arrival +displacements are emulator behavior, not recovered historical server code. + +## Evidence and reproduction + +Run `venv/Scripts/python tools/extract_zone_links.py` to regenerate the editable, +unembedded `data/zone_links.yaml` for both preserved clients. The extractor +validates exact statel, wall and decoded surface record alignment. Large generated +data and binary evidence are local and excluded from Git. + +Native 13.2 code/data ranges are retained in +`tools/zoning-target-disassembly.json`, reproducible with +`tools/capture_zone_disassembly.py`. Relevant addresses: + +| DLL / address | Finding | +| --- | --- | +| llr 0x100395a0 | n3Zone::LoadSurface selects resource 1000013. | +| llr 0x10032670 | n3SurfaceResource::ReadBlob. | +| llr 0x1003a350 | PortalArea reader. | +| llr 0x1003a4b0 | XZ polygon containment. | +| llr 0x10039a70 | IsPosInTeleportal. | +| kkr 0x10066ab0 | Continuous character portal check. | +| kkr 0x10027e50 | StartTeleportTry emits action 20. | +| kkr 0x10027970 | Periodic movement action 20. | +| kkr 0x10081920 / 0x100816e0 | Door collision / visual opening. | +| kkr 0x10041030 | Vehicle maximum speed selection. | +| llr 0x10015030 | Teleport message is disallowed from the client. | + +Supporting primary source references: + +- [AODB PlayfieldDynels and HighLow readers](https://gitlab.com/never-knows-best/aodb/-/tree/a772622bf39f7ac07a1761b90765214304d15107/AODB.Common/RDBObjects). +- [CellAO](https://github.com/CellAO/CellAO): `Playfields.Playfield.CheckWallCollision`, + `teleportproxy.Execute`, `exitproxyplayfield.Execute`, + `PlayfieldLoader` exit-event synthesis, and `DestinationExtractor.ReadFromStream`. +- [AOtomation.Messaging](https://github.com/CellAO/AOtomation.Messaging): + `LookAtMessage`, `GenericCmdMessage`, and the named message/action enums. + +Later source establishes useful pairing conventions. Native code, original +record bytes and runtime checks take precedence when they disagree. + +Native 13.2 runtime checks verified entering shop 1183 from Omni Entertainment +door `0xc01102c1`, then returning to that same entrance. A separate windowed +client also walked into the outdoor portal near `[1025, 16.4, 505]`, loaded +Omni Forest (716), and subsequently reported coordinates near +`[217.625, 9.81, 2307.875]`, consistent with the paired arrival line. diff --git a/server/control.go b/server/control.go @@ -210,6 +210,7 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) { destination.Position[2] += float32((id-1)%4) * 3 } destination.Rotation = [4]float32{0, 0, 0, 1} + destination.ReturnDoor = nil if err := server.updateUser(destination); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/server/main.go b/server/main.go @@ -39,6 +39,7 @@ func main() { }() go server.serveWorld() go server.roamNPCs() + go server.checkZoneCrossings() // Keep development connections confined to this computer. listener, err := net.Listen("tcp", "127.0.0.1:7500") @@ -195,7 +196,7 @@ func (server *server) serveWorld() { } func (server *server) serveWorldConnection(conn net.Conn) error { - client := &worldClient{conn: conn} + client := &worldClient{conn: conn, loading: true} var character *character loggingOut := false defer func() { @@ -328,6 +329,7 @@ func (server *server) serveWorldConnection(conn net.Conn) error { case 0x570c2039: response = n3Packet(0x570c2039, 50000, character.id, nil) server.mutex.Lock() + client.loading = false playfield := character.playfield server.mutex.Unlock() server.broadcast(playfield, character.id, response) @@ -343,7 +345,8 @@ func (server *server) serveWorldConnection(conn net.Conn) error { return fmt.Errorf("short character movement message") } server.mutex.Lock() - if !client.ready { + // Portal attempts can report the old position while a new zone loads. + if !client.ready || client.loading { server.mutex.Unlock() continue } @@ -354,7 +357,27 @@ func (server *server) serveWorldConnection(conn net.Conn) error { character.rotation[i] = math.Float32frombits(binary.BigEndian.Uint32(body[32+i*4:])) } playfield := character.playfield + client.movementStarted = time.Now() + switch binary.BigEndian.Uint32(body[16:20]) { + case 1: + client.forward = 1 + case 3: + client.forward = -1 + case 2, 4: + client.forward = 0 + case 22, 23: + client.running = binary.BigEndian.Uint32(body[16:20]) == 23 + } log.Printf("Character %d action=%d position=%v", character.id, binary.BigEndian.Uint32(body[16:20]), character.position) + destination := server.zoneDestination_locked(character, client) + if destination != nil { + server.mutex.Unlock() + log.Printf("Character %d zoning %d -> %d", character.id, playfield, destination.Playfield) + if err := server.updateUser(*destination); err != nil { + return err + } + continue + } if err := server.saveUsers_locked(); err != nil { server.mutex.Unlock() return err diff --git a/server/main_test.go b/server/main_test.go @@ -141,6 +141,8 @@ func TestTwoPlayersShareMovementAndDisconnect(t *testing.T) { first.Write(cookie) readWorldUpdates(t, first) + first.Write(n3Packet(0x570c2039, 50000, 1, nil)) + readPacket(first) cookie[23] = 2 second.Write(cookie) var existing []byte diff --git a/server/npc_data_test.go b/server/npc_data_test.go @@ -55,6 +55,9 @@ func useNPCData(t *testing.T, contents string) { if err := os.WriteFile(filepath.Join(directory, "data", "terrain.bin"), append([]byte("AOTERR01"), 0, 0, 0, 0), 0644); err != nil { t.Fatal(err) } + if err := os.WriteFile(filepath.Join(directory, "data", "zone_links.yaml"), []byte("original: {}\ntarget: {}\n"), 0644); err != nil { + t.Fatal(err) + } if err := os.Chdir(directory); err != nil { t.Fatal(err) } diff --git a/server/npcs_test.go b/server/npcs_test.go @@ -25,7 +25,7 @@ func TestMain(m *testing.M) { panic(err) } } - for _, name := range []string{"data/npc_spawns.yaml", "data/terrain.bin", "tools/original-npc-spawns.json"} { + for _, name := range []string{"data/npc_spawns.yaml", "data/terrain.bin", "data/zone_links.yaml", "tools/original-npc-spawns.json"} { contents, err := os.ReadFile(name) if err != nil { panic(err) diff --git a/server/roaming_test.go b/server/roaming_test.go @@ -52,6 +52,13 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) { if player.id == 2 { readPacket(clients[0]) } + // Finish connection initialization before expecting peer broadcasts. + ping := systemPacket(1, nil) + binary.BigEndian.PutUint16(ping[2:4], 11) + client.Write(ping) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } } now := time.Now() diff --git a/server/state.go b/server/state.go @@ -19,16 +19,21 @@ type character struct { appearance uint16 monsterData uint32 level uint16 + returnDoor *doorOrigin npc bool roaming *npcRoaming } type worldClient struct { - conn net.Conn - mutex sync.Mutex - ready bool - id uint32 - target bool + conn net.Conn + mutex sync.Mutex + ready bool + loading bool + id uint32 + target bool + forward float32 + running bool + movementStarted time.Time } func (client *worldClient) send(packet []byte) error { @@ -55,6 +60,7 @@ type server struct { clockStarted time.Time lastNPCUpdate time.Time terrain map[uint32]*terrain + zoneLinks map[string]map[uint32]zoneLinks } func newServer() *server { @@ -68,6 +74,11 @@ func newServer() *server { panic(err) } server.terrain = ground + links, err := readZoneLinks() + if err != nil { + panic(err) + } + server.zoneLinks = links // Create shared live instances from the editable NPC data. spawns, err := readNPCSpawns() if err != nil { diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -87,6 +87,11 @@ func TestTargetMovementIsPersistedAndRelayedToReleaseClient(t *testing.T) { if id == 2 { readPacket(clients[0]) } + if id == 2 { + client.Write(targetPacket(n3Packet(0x570c2039, 50000, id, nil))) + readPacket(clients[0]) + readPacket(client) + } ping := systemPacket(1, nil) binary.BigEndian.PutUint16(ping[2:4], 11) client.Write(ping) diff --git a/server/users.go b/server/users.go @@ -14,24 +14,26 @@ import ( // User IDs are stable; each local user currently owns one character. type userData struct { - ID uint32 `yaml:"id"` - Name string `yaml:"name"` - Playfield uint32 `yaml:"playfield"` - Position [3]float32 `yaml:"position,flow"` - Rotation [4]float32 `yaml:"rotation,flow"` - Appearance uint16 `yaml:"appearance"` - MonsterData uint32 `yaml:"monster_data"` - Level uint16 `yaml:"level"` + ID uint32 `yaml:"id"` + Name string `yaml:"name"` + Playfield uint32 `yaml:"playfield"` + Position [3]float32 `yaml:"position,flow"` + Rotation [4]float32 `yaml:"rotation,flow"` + Appearance uint16 `yaml:"appearance"` + MonsterData uint32 `yaml:"monster_data"` + Level uint16 `yaml:"level"` + ReturnDoor *doorOrigin `yaml:"return_door,omitempty"` } func (character *character) userData() userData { return userData{character.id, character.name, character.playfield, character.position, - character.rotation, character.appearance, character.monsterData, character.level} + character.rotation, character.appearance, character.monsterData, character.level, character.returnDoor} } func (data userData) character() *character { return &character{id: data.ID, name: data.Name, playfield: data.Playfield, position: data.Position, - rotation: data.Rotation, appearance: data.Appearance, monsterData: data.MonsterData, level: data.Level} + rotation: data.Rotation, appearance: data.Appearance, monsterData: data.MonsterData, level: data.Level, + returnDoor: data.ReturnDoor} } func (data userData) validate() error { diff --git a/server/zoning.go b/server/zoning.go @@ -0,0 +1,195 @@ +package main + +import ( + "bytes" + "fmt" + "log" + "math" + "os" + "time" +) + +type doorOrigin struct { + Playfield uint32 `yaml:"playfield"` + Door uint32 `yaml:"door"` +} + +type zoneDoor struct { + ID uint32 `yaml:"id"` + Position [3]float32 `yaml:"position"` + Rotation [4]float32 `yaml:"rotation"` + Destination uint32 `yaml:"destination"` + DestinationDoor uint32 `yaml:"destination_door"` + Return bool `yaml:"return"` +} + +type zoneWall struct { + Start [3]float32 `yaml:"start"` + End [3]float32 `yaml:"end"` + Destination uint32 `yaml:"destination"` + DestinationIndex uint32 `yaml:"destination_index"` + ArrivalStart [3]float32 `yaml:"arrival_start"` + ArrivalEnd [3]float32 `yaml:"arrival_end"` +} + +type zonePortal struct { + Polygon [][3]float32 `yaml:"polygon"` + Destination uint32 `yaml:"destination"` + DestinationIndex uint32 `yaml:"destination_index"` +} + +type zoneLinks struct { + Doors []zoneDoor `yaml:"doors"` + Walls []zoneWall `yaml:"walls"` + Portals []zonePortal `yaml:"portals"` +} + +func readZoneLinks() (map[string]map[uint32]zoneLinks, error) { + contents, err := os.ReadFile("data/zone_links.yaml") + if err != nil { + return nil, err + } + var links map[string]map[uint32]zoneLinks + if err := decodeUsers(bytes.NewReader(contents), &links); err != nil { + return nil, fmt.Errorf("zone links: %w", err) + } + return links, nil +} + +func (server *server) zoneDestination_locked(character *character, client *worldClient) *userData { + version := "original" + if client.target { + version = "target" + } + links := server.zoneLinks[version] + zone := links[character.playfield] + // Door transforms are height anchors; use the horizontal entrance position. + { + var selected *zoneDoor + distance := float32(4) + for index := range zone.Doors { + door := &zone.Doors[index] + x, z := door.Position[0]-character.position[0], door.Position[2]-character.position[2] + if squared := x*x + z*z; squared < distance && math.Abs(float64(door.Position[1]-character.position[1])) < 8 { + selected, distance = door, squared + } + } + if selected != nil { + origin := doorOrigin{character.playfield, selected.ID} + destinationPlayfield, destinationDoor := selected.Destination, selected.DestinationDoor + if selected.Return && character.returnDoor != nil { + destinationPlayfield, destinationDoor = character.returnDoor.Playfield, character.returnDoor.Door + } + for _, door := range links[destinationPlayfield].Doors { + if door.ID != destinationDoor { + continue + } + destination := character.userData() + destination.Playfield, destination.Position, destination.Rotation = destinationPlayfield, door.Position, door.Rotation + // Face away from the exit and arrive outside its collision area. + x, y, z, w := door.Rotation[0], door.Rotation[1], door.Rotation[2], door.Rotation[3] + destination.Position[0] += 2.5 * (2*x*z + 2*y*w) + destination.Position[2] += 2.5 * (1 - 2*x*x - 2*y*y) + destination.ReturnDoor = &origin + if selected.Return { + destination.ReturnDoor = nil + } + return &destination + } + } + } + + // Boundary vertices carry a destination line and preserve position along it. + for _, wall := range zone.Walls { + inPortal := false + for _, portal := range zone.Portals { + if portal.Destination != wall.Destination || portal.DestinationIndex != wall.DestinationIndex { + continue + } + inside := false + for index, end := range portal.Polygon { + start := portal.Polygon[(index+len(portal.Polygon)-1)%len(portal.Polygon)] + if (start[2] > character.position[2]) != (end[2] > character.position[2]) && + character.position[0] < (end[0]-start[0])*(character.position[2]-start[2])/(end[2]-start[2])+start[0] { + inside = !inside + } + } + inPortal = inPortal || inside + } + dx, dz := wall.End[0]-wall.Start[0], wall.End[2]-wall.Start[2] + length := dx*dx + dz*dz + if length == 0 { + continue + } + factor := ((character.position[0]-wall.Start[0])*dx + (character.position[2]-wall.Start[2])*dz) / length + if !inPortal && (factor < 0 || factor > 1) { + continue + } + factor = max(0, min(1, factor)) + x, z := wall.Start[0]+factor*dx-character.position[0], wall.Start[2]+factor*dz-character.position[2] + if !inPortal && x*x+z*z > 4 { + continue + } + destination := character.userData() + destination.Playfield = wall.Destination + for index := range destination.Position { + destination.Position[index] = wall.ArrivalStart[index] + factor*(wall.ArrivalEnd[index]-wall.ArrivalStart[index]) + } + dx, dz = wall.ArrivalEnd[0]-wall.ArrivalStart[0], wall.ArrivalEnd[2]-wall.ArrivalStart[2] + length = float32(math.Hypot(float64(dx), float64(dz))) + if length == 0 { + continue + } + destination.Position[0] -= 8 * dz / length + destination.Position[2] += 8 * dx / length + if ground := server.terrain[destination.Playfield]; ground != nil { + if height, inside := ground.elevation(destination.Position[0], destination.Position[2]); inside { + destination.Position[1] = height + } + } + destination.ReturnDoor = nil + return &destination + } + return nil +} + +func (server *server) checkZoneCrossings() { + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for now := range ticker.C { + server.advanceZoneCrossings(now) + } +} + +func (server *server) advanceZoneCrossings(now time.Time) { + // The native client sends start/stop controls rather than every walking frame. + // Predict only trigger checks; received coordinates remain authoritative. + server.mutex.Lock() + var destinations []userData + for id, client := range server.clients { + if !client.ready || client.loading || client.forward == 0 { + continue + } + character := *server.characters[id] + seconds := math.Min(now.Sub(client.movementStarted).Seconds(), 20) + speed := float32(1.5) + if client.running { + speed = 4.5 + if client.forward < 0 { + speed = 3.35 + } + } + x, y, z, w := character.rotation[0], character.rotation[1], character.rotation[2], character.rotation[3] + character.position[0] += float32(seconds) * speed * client.forward * (2*x*z + 2*y*w) + character.position[2] += float32(seconds) * speed * client.forward * (1 - 2*x*x - 2*y*y) + if destination := server.zoneDestination_locked(&character, client); destination != nil { + destinations = append(destinations, *destination) + } + } + server.mutex.Unlock() + for _, destination := range destinations { + if err := server.updateUser(destination); err != nil { + log.Printf("Automatic zoning: %v", err) + } + } +} diff --git a/server/zoning_test.go b/server/zoning_test.go @@ -0,0 +1,255 @@ +package main + +import ( + "encoding/binary" + "math" + "net" + "testing" + "time" +) + +func connectZoningClient(t *testing.T, world *server, target bool) net.Conn { + t.Helper() + client, connection := net.Pipe() + t.Cleanup(func() { client.Close() }) + client.SetDeadline(time.Now().Add(5 * time.Second)) + go func() { defer connection.Close(); world.serveWorldConnection(connection) }() + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + if target { + binary.BigEndian.PutUint16(cookie, 0xdfdf) + } + client.Write(cookie) + for { + packet, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + offset := 20 + if target { + offset = 16 + } + if binary.BigEndian.Uint32(packet[offset:]) == 0x5f52412e { + break + } + } + ready := n3Packet(0x570c2039, 50000, 1, nil) + if target { + ready = targetPacket(ready) + } + client.Write(ready) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } + // A ping ensures the CharacterReady notification has been processed. + ping := systemPacket(1, nil) + binary.BigEndian.PutUint16(ping[2:4], 11) + client.Write(ping) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } + return client +} + +func TestShopDoorReturnsToItsOriginalEntrance(t *testing.T) { + for _, target := range []bool{false, true} { + t.Run(map[bool]string{false: "11.0", true: "13.2"}[target], func(t *testing.T) { + world := newTestServer(t) + world.characters = make(map[uint32]*character) + player := world.newCharacter() + player.playfield = 705 + player.position = [3]float32{765.0848, 19.1349, 516.5} + client := connectZoningClient(t, world, target) + + movement := npcMovementPacket(player, 1) + if target { + movement = targetPacket(movement) + } + client.Write(movement) + teleport, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + redirect, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + restarted := newServer() + arrived := restarted.characters[1].userData() + + offset := 20 + if target { + offset = 16 + } + if binary.BigEndian.Uint32(teleport[offset:]) != 0x43197d22 || binary.BigEndian.Uint32(redirect[16:]) != 0x3c { + t.Fatalf("missing native zone sequence: %x %x", teleport, redirect) + } + if arrived.Playfield != 1183 || math.Abs(float64(arrived.Position[2]-118.50997)) > 0.001 || arrived.ReturnDoor == nil || *arrived.ReturnDoor != (doorOrigin{705, 0xc01102c1}) { + t.Fatalf("wrong shop arrival or persisted entrance: %+v", arrived) + } + + client.Close() + client = connectZoningClient(t, world, target) + world.mutex.Lock() + movementPlayer := *player + world.mutex.Unlock() + movementPlayer.position = [3]float32{187.0007, 5, 116.01} + movement = npcMovementPacket(&movementPlayer, 1) + if target { + movement = targetPacket(movement) + } + client.Write(movement) + readPacket(client) + readPacket(client) + restarted = newServer() + returned := restarted.characters[1].userData() + + if returned.Playfield != 705 || returned.ReturnDoor != nil || math.Abs(float64(returned.Position[2]-514.007)) > 0.001 { + t.Fatalf("exit did not return to the same entrance: %+v", returned) + } + }) + } +} + +func TestHeldWalkingCrossesDoorWithoutAnotherMovementPacket(t *testing.T) { + world := newTestServer(t) + world.characters = make(map[uint32]*character) + player := world.newCharacter() + player.playfield = 705 + player.position = [3]float32{765.0848, 19.1349, 511.5} + player.rotation = [4]float32{0, 0, 0, 1} + client := connectZoningClient(t, world, true) + client.Write(targetPacket(npcMovementPacket(player, 1))) + ping := systemPacket(1, nil) + binary.BigEndian.PutUint16(ping[2:4], 11) + client.Write(ping) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } + world.mutex.Lock() + started := world.clients[1].movementStarted + world.mutex.Unlock() + + done := make(chan struct{}) + go func() { world.advanceZoneCrossings(started.Add(3 * time.Second)); close(done) }() + teleport, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + redirect, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + <-done + + if binary.BigEndian.Uint32(teleport[16:]) != 0x43197d22 || binary.BigEndian.Uint32(redirect[16:]) != 0x3c || world.characters[1].playfield != 1183 { + t.Fatal("held forward movement did not enter the mapped shop") + } +} + +func TestOmniCityPortalMapsToItsBoundaryExit(t *testing.T) { + world := newTestServer(t) + world.characters = make(map[uint32]*character) + player := world.newCharacter() + player.playfield = 705 + player.position = [3]float32{1025, 16.4, 509} + client := connectZoningClient(t, world, true) + + client.Write(targetPacket(npcMovementPacket(player, 20))) + teleport, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + readPacket(client) + + if binary.BigEndian.Uint32(teleport[16:]) != 0x43197d22 || world.characters[1].playfield != 716 || world.characters[1].position[0] == playfields[716].spawn[0] { + t.Fatal("city portal did not use the paired boundary destination") + } +} + +func TestLookingAtDoorAndUnassignedMissionDoNotZone(t *testing.T) { + world := newTestServer(t) + world.characters = make(map[uint32]*character) + player := world.newCharacter() + player.playfield = 705 + player.position = [3]float32{765.0848, 19.1349, 516.5} + client := connectZoningClient(t, world, true) + look := binary.BigEndian.AppendUint32(nil, 51016) + look = binary.BigEndian.AppendUint32(look, 0xc01102c1) + look = binary.BigEndian.AppendUint32(look, 0) + ping := systemPacket(1, nil) + binary.BigEndian.PutUint16(ping[2:4], 11) + + client.Write(targetPacket(n3Packet(0x2252445f, 50000, 1, look))) + client.Write(ping) + reply, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + + if binary.BigEndian.Uint16(reply[2:]) != 11 || player.playfield != 705 { + t.Fatal("selecting a door incorrectly triggered zoning") + } + + world.mutex.Lock() + movementPlayer := *player + world.mutex.Unlock() + for _, door := range world.zoneLinks["target"][705].Doors { + if door.ID == 0xc00402c1 { + movementPlayer.position = door.Position + } + } + + client.Write(targetPacket(npcMovementPacket(&movementPlayer, 2))) + client.Write(ping) + reply, err = readPacket(client) + if err != nil { + t.Fatal(err) + } + + if binary.BigEndian.Uint16(reply[2:]) != 11 || player.playfield != 705 { + t.Fatal("unassigned mission entrance incorrectly triggered zoning") + } +} + +func TestMovementBeforeCharacterReadyPreservesZoneArrival(t *testing.T) { + world := newTestServer(t) + world.characters = make(map[uint32]*character) + player := world.newCharacter() + player.playfield = 716 + player.position = [3]float32{726, 9.8, 2304} + client, connection := net.Pipe() + t.Cleanup(func() { client.Close() }) + client.SetDeadline(time.Now().Add(5 * time.Second)) + go func() { defer connection.Close(); world.serveWorldConnection(connection) }() + client.Write(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})) + readWorldUpdates(t, client) + stale := *player + stale.position = [3]float32{1025, 16.4, 509} + ping := systemPacket(1, nil) + binary.BigEndian.PutUint16(ping[2:4], 11) + + client.Write(npcMovementPacket(&stale, 20)) + client.Write(ping) + readPacket(client) + + world.mutex.Lock() + arrival := player.position + world.mutex.Unlock() + if arrival != [3]float32{726, 9.8, 2304} { + t.Fatalf("loading movement overwrote arrival: %v", arrival) + } + + client.Write(n3Packet(0x570c2039, 50000, 1, nil)) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } + stale.position = [3]float32{727, 9.8, 2304} + client.Write(npcMovementPacket(&stale, 2)) + client.Write(ping) + readPacket(client) + restarted := newServer() + + if restarted.characters[1].position != [3]float32{727, 9.8, 2304} { + t.Fatal("movement after CharacterReady was not persisted") + } +}