aorecomp

Anarchy Online classic in the browser

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


commit ee8d392804cd77954680a8f7ab7fe4871655b4e1
parent 27b0b66b5244d2d6d8e16a900ceaccc0b5bc38ea
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 19:30:44 +0000

Route mission rooms through shared movement and admission

Diffstat:
MTODO.md | 22+++++++++++++++++++---
Mdocs/mission-interiors.md | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_movement.go | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_movement_test.go | 297+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/mission_scene.go | 50+++++++++++++++++++++++++++++---------------------
Aserver/mission_world.go | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_world_test.go | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/nano_buffs.go | 1+
Mserver/player_collision.go | 15++++-----------
Mserver/player_movement.go | 7+++----
Mserver/scene_geometry.go | 4++++
Mserver/scene_queries.go | 7+++++++
Mserver/state.go | 1+
13 files changed, 877 insertions(+), 39 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1539,9 +1539,19 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). 298 original room records, shares immutable meshes, and implements rotated sphere/segment queries, fixed-diagonal floor sampling and tile/ceiling lookup. Four connected-layout rotations match native room anchors, source poses, - reciprocal links and standing floor height. Route this backend through live - movement and enforce room transitions before enabling private entry; this - verification does not establish native equivalence for every query or slope. + reciprocal links and standing floor height. A runtime-ID registry now routes + the normal movement controller's floor, sphere, segment and jump queries into + mission geometry. Registration requires opposing portals, one exterior exit + and a connected graph. Native-style room vetoes reject empty cells and + unlinked transitions, with independent last-allowed room/pose history and + entrance recovery. Common-handler tests cover held traversal/return, walls, + large frames, falling/jumping, prediction, bad reports, instance replacement + and unchanged SQLite positions between checkpoints. Published-WASM wall and + off-center doorway stops match the server; this does not establish equivalence + for every query or slope. These links currently have empty door identities: + bind actual doors and enforce their access policy before enabling private + entry. Relay admitted/corrected poses instead of forwarding rejected reports, + and eject occupants before removing retired geometry. The original generated-world factory clears tileset heights >=6553.5 after decoding. The scene builder now applies that shared rule; ordinary low heights at any tileset index and the raw archive values remain intact. @@ -2484,6 +2494,12 @@ current SQLite storage when applying these findings. a crash stack or proof of a missing adapter. Captures/profile: `local/mission-retirement/event-crash-*`; successful retry: `local/mission-retirement/event-retry-*`. +- [ ] [P1] Close fixture SQLite handles after every test and table case, including + failure paths. The comprehensive mission-movement regression run completed + over 15,000 results, but its timeout dump retained many database/sql connection + opener goroutines from earlier fixtures. Audit shared fixture helpers and + verify bounded open handles/goroutines across a full run. New mission movement + fixtures explicitly close their world database. - [ ] [P3] Reproduce stale shop interaction state after a live control-panel inventory edit. In the restoration smoke run, a nearby original terminal reported "Too far away" after the edit, while a fresh page could use it. diff --git a/docs/mission-interiors.md b/docs/mission-interiors.md @@ -416,3 +416,77 @@ The diagnostic is an owned client-only fixture (player294); it does not modify the shared preview or published WASM. All owned browsers and analysis sessions are closed. `cr-tilemap-short-evidence.json` confirms the underlying short reader copies the raw two bytes; it contains no normalization rule. + +## Runtime scene dispatch and room admission + +Generated scenes can now be registered under a private runtime world identity. +Registration rejects public or duplicate identities and publishes the scene only +after its original external portals pair with opposing directions, matching +positions and the same authored floor. It requires one exterior portal and a +connected room graph. Removal affects that runtime identity; other instances +retain their own placements and shared immutable room meshes. + +The common geometry dispatcher now sends floor, sphere and segment queries to +the registered scene, so the ordinary player controller also uses indoor +collision, gravity and jump clearance without an outdoor terrain object. Room +admission keeps the Dynel's last allowed room and pose separately from the +movement controller. It applies the native integer-boundary nudge, coordinate +limits, empty-cell and unlinked-room vetoes, historical-position recovery and +entrance fallback. Prediction copies this history; committing predicted movement +also commits its room history. Significant state persistence is unchanged, and +movement tests verify that simulation ticks leave stored positions unchanged. + +Portal placement and pairing follow LLR GetDoorPosRot 0x10033650 and KKR 0x100f2f30. +Room-transition recovery follows LLR 0x10036870/0x10036aa0 and +KKR 0x1014cf70/0x1014dad0. The fallback uses the highest floor corner at the entrance +anchor; if that cell is empty it scans tiles in X-major order and transforms the +first nonempty tile center. Its raw tile height differs from the interpolated +floor used during normal movement. Floor interpolation is shared by portal +placement and ordinary floor sampling. + +Published-WASM fixture296 uses the connected room0/room37 layout on the GPU. +It runs into the chamber, returns to the entrance after lining up with the +portal, jumps and lands, and holds movement against the side wall. Go's matched +normal Solitus female stops at the running wall within 0.002 units of the native +pose [14.048968,0.011975,48.291656]. An off-center reverse walk stops at the doorway +frame near [14.048965,0.011,32.186890] in both implementations. The side-wall +contact X17.341246/Y0.740876 also agrees with Go's wall fixture. These settled +contacts do not establish identical trajectories or every sloped query. Native +screenshots were reviewed; no page exception or adapter failure occurred. Two +browser console 404s remain in the capture. The owned browser was closed before +the broader build/test runs, and the single shared HTTPS preview stays available. + +The probe's field named `cell` reads an unverified actor offset and remains 1 +throughout this run. It is not evidence of native room membership. Traversal is +established by observed world positions and the previously verified room poses. + +Registration currently models links with empty door identities, which the +original client permits. Real door bindings, their locked/keyed access policy, +private assignment persistence, corrected-pose delivery, occupant evacuation +before retirement and cross-system isolation are still required before player +mission entry is enabled. This milestone does not make missions enterable from +the shared preview, and does not change the published WASM. + +Retained evidence in `local/mission-interior/` includes +`llr-room-recovery-evidence.json`, `kkr-room-admission-evidence.json`, +`llr-room-floor-recovery-evidence.json`, `runtime-movement-comparison/`, +`tmp_native_movement_comparison.mjs`, `tmp_verify_movement_comparison.py` and +`native-movement-verification.json`. GetTileCenterGlobalPos evidence is +`ev_5642f3249136cf8d5ab66e0242443da42d897586b469f63132ff9f7ed844fa95`; +GetHeightAndNormalAtPos evidence is +`ev_cfc123afaf0950ef057a0b920477e3cddfd2f947ab755741ca4e62fca8f7ad65`. +All owned REA sessions are closed. + +The focused movement/scene/terrain regression suite passes under the race +detector: 115 root tests and 683 results, including concurrent registration and +retirement. Build and vet pass. Combined comprehensive coverage completes all +1,490 server root tests and 23 data-package root tests, with 15,594 unique passing +root/subtest results and no assertion failure. The monolithic invocation reached +its 30-minute ceiling with 11 root tests unfinished; all 11 pass in the separate +completion run. The capped invocation remains a failed invocation in the logs. +These results are verified in `mission-movement-regression-verification.json`, +with logs `mission-movement-full-server-tests.json`, +`mission-movement-remaining-server-tests.json` and `mission-movement-race-tests.json`. +The final mission-fixture cleanup recheck passes 31 results in +`mission-movement-final-fixture-tests.json`; those fixtures close their SQLite +world handles as well as their original-resource files. diff --git a/server/mission_movement.go b/server/mission_movement.go @@ -0,0 +1,124 @@ +package main + +import "math" + +type playerRoomState struct { + scene *missionScene + room *placedRoom + position [3]float32 +} + +func (player *character) vetoPosition(position, previous *[3]float32) bool { + scene := player.geometry.mission(player.playfield) + if scene == nil { + return player.geometry.playfields[player.playfield].veto(position, previous) + } + // client/game/llr.dll/lifted-0021.c, sub_38036870: nudge integer X/Z boundaries. + for _, axis := range []int{0, 2} { + base := math.Floor(float64(position[axis])) + if float64(position[axis]) < base+float64(float32(.01)) { + position[axis] = float32(base + float64(float32(.01))) + } else if float64(position[axis]) > base+float64(float32(.99)) { + position[axis] = float32(base + float64(float32(.99))) + } + } + for axis, value := range position { + if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) { + position[axis] = math.Float32frombits(0x4e6e6b28) + } + } + position[0] = max(float32(.1), min(position[0], float32(7999.9))) + position[2] = max(float32(.1), min(position[2], float32(7999.9))) + position[1] = max(float32(.01), min(position[1], float32(1999.9))) + + // client/game/llr.dll/lifted-0021.c, sub_38036AA0: Dynel history is separate from velocity. + if player.roomState.scene != scene { + player.roomState = playerRoomState{scene: scene} + } + room := scene.roomAt(*position) + allowed := room != nil && (player.roomState.room == nil || player.roomState.room == room) + if room != nil && player.roomState.room != nil && player.roomState.room != room { + // client/game/kkr.dll/lifted-0096.c, sub_3614CF70: links with an empty door identity. + for _, link := range scene.links { + if link == [2]*placedRoom{player.roomState.room, room} || link == [2]*placedRoom{room, player.roomState.room} { + allowed = true + break + } + } + } + if allowed { + player.roomState.room, player.roomState.position = room, *position + return false + } + if player.roomState.room == nil { + *position = scene.safePosition() + return true + } + if previous != nil { + *position = *previous + } else { + // Collision's final retry has no outer pose; recover beside the last allowed pose. + direction := [3]float32{player.roomState.position[0] - position[0], player.roomState.position[1] - position[1], player.roomState.position[2] - position[2]} + radius := player.collisionBody().radius + if direction == [3]float32{} { + forward, _ := bodyAxes(player.rotation) + for axis := range direction { + direction[axis] = -forward[axis] * radius * .5 + } + } else { + length := math.Sqrt(surfaceDot(direction, direction)) + for axis := range direction { + direction[axis] = float32(float64(direction[axis]) / length) + } + } + direction[0], direction[1], direction[2] = direction[0]*.1, 0, direction[2]*.1 + for axis := range position { + position[axis] = player.roomState.position[axis] + direction[axis]*radius*.5 + } + if scene.roomAt(*position) == nil { + for axis := range position { + position[axis] = player.roomState.position[axis] - direction[axis]*radius*.5 + } + } + } + if scene.roomAt(*position) == nil { + *position = scene.safePosition() + } + return true +} + +func (scene *missionScene) safePosition() [3]float32 { + // client/game/kkr.dll/lifted-0096.c, sub_3614DAD0: GetSafePos uses the exterior room. + room := scene.entrance + position := room.position + local := room.tilePoint(position, scene.ground.spacing) + x := int(math.Floor(float64(local[0]/scene.ground.spacing))) + int(room.template.bounds[0]) + z := int(math.Floor(float64(local[2]/scene.ground.spacing))) + int(room.template.bounds[1]) + cell := z*scene.ground.width + x + // client/game/llr.dll/lifted-0020.c, sub_38032CE0: ForcePosInY uses the highest corner. + height := max(scene.ground.floors[cell], scene.ground.floors[z*scene.ground.width+max(x-1, 0)], + scene.ground.floors[max(z-1, 0)*scene.ground.width+x], scene.ground.floors[max(z-1, 0)*scene.ground.width+max(x-1, 0)]) + position[1] = float32(height)*scene.ground.scale - room.template.minHeight + room.position[1] + if scene.ground.tiles[cell]&127 != 0 { + return position + } + + // client/game/llr.dll/lifted-0020.c, sub_38032940/sub_38032A20: X-major tile scan. + for x := int(room.template.bounds[0]); x < int(room.template.bounds[2]); x++ { + for z := int(room.template.bounds[1]); z < int(room.template.bounds[3]); z++ { + cell := z*scene.ground.width + x + if scene.ground.tiles[cell]&127 == 0 { + continue + } + position = [3]float32{(float32(x-int(room.template.bounds[0]))+.5)*scene.ground.spacing - local[0], + float32(scene.ground.floors[cell])*scene.ground.scale - room.template.minHeight, + (float32(z-int(room.template.bounds[1]))+.5)*scene.ground.spacing - local[2]} + position = roomRotate(position, room.rotation) + for axis := range position { + position[axis] += room.position[axis] + } + return position + } + } + return [3]float32{} +} diff --git a/server/mission_movement_test.go b/server/mission_movement_test.go @@ -0,0 +1,297 @@ +package main + +import ( + "bytes" + "math" + "testing" + "time" +) + +func newMissionCollisionWorld(t *testing.T) *server { + t.Helper() + world := newPlayerCollisionWorld(t) + t.Cleanup(func() { world.db.Close() }) + if err := world.geometry.addMission(9000001, fixedMissionLayout()); err != nil { + t.Fatal(err) + } + player := world.characters[1] + player.playfield, player.position = 9000001, [3]float32{15, 1, 16} + player.rotation = [4]float32{0, 0, 0, 1} + player.appearance = 0x195 + return world +} + +func TestMissionMovementCrossesConnectedRoomsAndReturnsWithoutDatabaseChurn(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + for frame := 1; frame <= 1200; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * time.Second / 60)) + } + far := player.position + farRoom := player.roomState.room + player.movement.action(player, 3) + for frame := 1201; frame <= 2700; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * time.Second / 60)) + } + db, err := world.database() + if err != nil { + t.Fatal(err) + } + var storedX, storedY, storedZ float32 + if err := db.QueryRow("SELECT position_x, position_y, position_z FROM characters WHERE id=1").Scan(&storedX, &storedY, &storedZ); err != nil { + t.Fatal(err) + } + + scene := world.geometry.mission(9000001) + if farRoom != &scene.rooms[1] || far[2] < 40 || far[2] > 48 || math.Abs(float64(far[1]-.011)) > .00001 { + t.Fatal("held forward failed to enter the original chamber", far, player.movement) + } + if player.roomState.room != &scene.rooms[0] || player.position[2] < 10 || player.position[2] > 16 || player.movement.falling { + t.Fatal("held reverse failed to return or escaped the exterior portal", player.position, player.movement) + } + if storedX != 15 || storedY != 1 || storedZ != 16 { + t.Fatal("mission simulation persisted ordinary movement on each tick", storedX, storedY, storedZ) + } + t.Log("forward", far, "return", player.position) +} + +func TestMissionMovementStopsHeldInputAndLargeFramesAtOriginalWalls(t *testing.T) { + for _, scenario := range []struct { + name string + running bool + frames int + step time.Duration + }{ + {"sustained walking", false, 1200, time.Second / 60}, + {"large running frame", true, 1, 4 * time.Second}, + } { + t.Run(scenario.name, func(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.position = [3]float32{15, .011, 20} + player.rotation = [4]float32{0, .70710677, 0, .70710677} + player.running, player.stats.Speed.RunSpeed = scenario.running, 2000 + if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + for frame := 1; frame <= scenario.frames; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * scenario.step)) + } + + if player.position[0] < 15 || player.position[0] > 17.7 || player.position[2] < 19.9 || player.position[2] > 20.1 || player.movement.falling { + t.Fatal("common movement escaped the original room wall", player.position, player.movement) + } + if player.movement.velocity[0] <= 1 || player.movement.forward != 1 { + t.Fatal("wall response halted intended movement", player.movement) + } + if !scenario.running && player.position[0] < 17 { + t.Fatal("held walking never reached the wall", player.position) + } + t.Log("wall", player.position) + }) + } +} + +func TestMissionMovementRunningReachesTheChamberWall(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.running, player.stats.Speed.RunSpeed = true, 5 + if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + for frame := 1; frame <= 1200; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * time.Second / 60)) + } + wall := player.position + player.movement.action(player, 22) + player.movement.action(player, 3) + for frame := 1201; frame <= 2880; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * time.Second / 60)) + } + + if player.roomState.room != &world.geometry.mission(9000001).rooms[1] || wall[2] < 47 || wall[2] > 49 || player.movement.falling { + t.Fatal("held run or off-center return escaped the chamber", wall, player.position, player.movement) + } + // Published WASM fixture296: matched normal Solitus female, run skill5, north wall. + if surfaceDistanceSquared(wall, [3]float32{14.048968, .011975, 48.291656}) > .000004 { + t.Fatal("server wall stop differs from the native fixture", wall) + } + if surfaceDistanceSquared(player.position, [3]float32{14.048965, .011, 32.18689}) > .0009 { + t.Fatal("off-center return bypassed the native doorway frame", player.position) + } + t.Log("native wall comparison", wall, "off-center doorway", player.position) +} + +func TestMissionMovementFallsAndJumpsWithoutOutdoorTerrain(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.position[1] = 4 + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + world.advancePlayerMovement(started.Add(100 * time.Millisecond)) + fallingHeight := player.position[1] + world.advancePlayerMovement(started.Add(200 * time.Millisecond)) + secondHeight := player.position[1] + for frame := 3; frame <= 20; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + landed := player.position + player.movement.action(player, 13) + impulse := player.movement.verticalVelocity + world.advancePlayerMovement(started.Add(2100 * time.Millisecond)) + jumped := player.position + for frame := 22; frame <= 50; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + + if fallingHeight != 4 || math.Abs(float64(secondHeight-3.8)) > .00001 || math.Abs(float64(landed[1]-.011)) > .00001 { + t.Fatal("mission fall failed to start on projection and use room floor", fallingHeight, secondHeight, landed) + } + if impulse <= 0 || jumped[1] <= landed[1]+.1 || player.movement.falling || math.Abs(float64(player.position[1]-.011)) > .00001 { + t.Fatal("mission jump did not rise and land", impulse, jumped, player.position, player.movement) + } +} + +func TestMissionMovementPredictionDoesNotMutateLiveRoomHistory(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.position = [3]float32{15, .011, 29} + if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + state, position := player.roomState, player.position + when := player.movement.updatedAt.Add(2 * time.Second) + + snapshot := player.predictedMovement(when) + liveState, livePosition := player.roomState, player.position + player.anchorMovement_locked(when) + + scene := world.geometry.mission(9000001) + if snapshot.roomState.room != &scene.rooms[1] || snapshot.position[2] <= 30 || liveState != state || livePosition != position { + t.Fatal("prediction changed live state or failed to cross the linked portal", snapshot.position, snapshot.roomState, liveState) + } + if player.position != snapshot.position || player.roomState != snapshot.roomState { + t.Fatal("anchoring must commit the predicted room history with its pose", player.position, player.roomState) + } +} + +func TestMissionMovementRejectsEmptySpaceAndUnlinkedRoomReports(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + for frame := 1; frame <= 20; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + scene := world.geometry.mission(9000001) + // A room with no door identity is traversable only when its authored portals link. + scene.links = nil + for _, reported := range [][3]float32{{15, .011, 35}, {5, .011, 16}, {15, 100, 16}} { + before := player.position + requester := *player + requester.position = reported + + if err := world.handleMovement(client, playerMovementRequest(&requester, 20)); err != nil { + t.Fatal(err) + } + + if player.position != before || player.roomState.room != &scene.rooms[0] { + t.Fatal("reported pose bypassed room admission", reported, player.position, before, player.roomState) + } + } +} + +func TestMissionMovementResetsHistoryWhenTheRuntimeSceneIsReplaced(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + old := player.roomState.scene + world.geometry.removeMission(9000001) + layout := fixedMissionLayout() + layout.width, layout.rooms[0].x, layout.rooms[1].x = 6, 3, 3 + if err := world.geometry.addMission(9000001, layout); err != nil { + t.Fatal(err) + } + requester := *player + requester.position = [3]float32{35, .011, 16} + + if err := world.handleMovement(client, playerMovementRequest(&requester, 20)); err != nil { + t.Fatal(err) + } + + scene := world.geometry.mission(9000001) + if player.roomState.scene != scene || player.roomState.scene == old || player.roomState.room != &scene.rooms[0] || player.position[0] != 35.01 { + t.Fatal("reused runtime identity retained a retired room pointer", player.position, player.roomState) + } +} + +func TestMissionMovementRecoversAnInvalidInitialPoseInTheEntranceRoom(t *testing.T) { + world := newMissionCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.position = [3]float32{1, 1, 1} + requester := *player + requester.position = [3]float32{2, 1, 2} + + if err := world.handleMovement(client, playerMovementRequest(&requester, 20)); err != nil { + t.Fatal(err) + } + + scene := world.geometry.mission(9000001) + if scene.roomAt(player.position) != scene.entrance || player.roomState.room != scene.entrance { + t.Fatal("invalid initial pose was not recovered into the exterior room", player.position, player.roomState) + } +} + +func TestMissionSafePositionUsesMaximumCornerThenScansXBeforeZ(t *testing.T) { + ground := &dungeonTilemap{width: 4, depth: 4, spacing: 2, scale: 1, + tiles: bytes.Repeat([]byte{1}, 16), floors: make([]byte, 16)} + room := placedRoom{position: [3]float32{4, 10, 4}, template: &dungeonRoom{bounds: [4]uint16{0, 0, 4, 4}, minHeight: 1}} + scene := &missionScene{ground: ground, entrance: &room} + ground.floors[5], ground.floors[6], ground.floors[9], ground.floors[10] = 2, 5, 3, 4 + + maximum := scene.safePosition() + clear(ground.tiles) + ground.tiles[12], ground.tiles[1] = 1, 1 + ground.floors[12], ground.floors[1] = 7, 8 + first := scene.safePosition() + room.rotation = 1 + rotated := scene.safePosition() + + if maximum != [3]float32{4, 14, 4} || first != [3]float32{1, 16, 7} || rotated != [3]float32{7, 16, 7} { + t.Fatal("native entrance recovery height or X-major tile center", maximum, first, rotated) + } +} + +func TestMissionMovementFinalVetoRecoversAroundLastAllowedPosition(t *testing.T) { + world := newMissionCollisionWorld(t) + player := world.characters[1] + player.position = [3]float32{15, .011, 16} + player.placePosition([3]float32{15, .011, 17}) + previous := player.position + position := [3]float32{1, 1, 1} + + changed := player.vetoPosition(&position, nil) + + if !changed || world.geometry.mission(9000001).roomAt(position) != player.roomState.room || position == previous || surfaceDistanceSquared(position, previous) > .0002 { + t.Fatal("final correction did not recover near the Dynel's allowed pose", position, previous, player.roomState) + } +} diff --git a/server/mission_scene.go b/server/mission_scene.go @@ -6,8 +6,10 @@ import ( ) type missionScene struct { - ground *dungeonTilemap - rooms []placedRoom + ground *dungeonTilemap + rooms []placedRoom + links [][2]*placedRoom + entrance *placedRoom } type placedRoom struct { @@ -195,17 +197,28 @@ func (scene *missionScene) floor(origin [3]float32, point, normal *[3]float32) { *point, *normal = room.globalPoint(static.point), static.normal // Dungeon floor vertices straddle the selected tile; every cell uses the same diagonal. - spacing := scene.ground.spacing - local := room.tilePoint(origin, spacing) - x, z := int(math.Floor(float64(local[0]/spacing))), int(math.Floor(float64(local[2]/spacing))) - u, v := local[0]/spacing-float32(x), local[2]/spacing-float32(z) - x, z = x+int(room.template.bounds[0]), z+int(room.template.bounds[1]) + atlas := room.tilePoint(origin, scene.ground.spacing) + atlas[0] += float32(room.template.bounds[0]) * scene.ground.spacing + atlas[2] += float32(room.template.bounds[1]) * scene.ground.spacing + height, slope := scene.ground.floor(atlas) + height = height - room.template.minHeight + room.position[1] + if height > point[1] { + *point = [3]float32{origin[0], height, origin[2]} + *normal = roomRotate(slope, room.rotation) + } + point[1] = max(float32(.001), min(point[1], float32(1999.9))) +} + +func (ground *dungeonTilemap) floor(origin [3]float32) (float32, [3]float32) { + // client/game/llr.dll/lifted-0021.c, sub_380385E0: GetHeightAndNormalAtPos, dungeon diagonal. + x, z := int(math.Floor(float64(origin[0]/ground.spacing))), int(math.Floor(float64(origin[2]/ground.spacing))) + u, v := origin[0]/ground.spacing-float32(x), origin[2]/ground.spacing-float32(z) var corners [4][3]float32 for index, offset := range [4][2]int{{-1, -1}, {0, -1}, {0, 0}, {-1, 0}} { - cell := max(z+offset[1], 0)*scene.ground.width + max(x+offset[0], 0) - corners[index] = [3]float32{float32(offset[0]+1) * spacing, - float32(scene.ground.floors[cell])*scene.ground.scale - room.template.minHeight, - float32(offset[1]+1) * spacing} + cell := max(z+offset[1], 0)*ground.width + max(x+offset[0], 0) + corners[index] = [3]float32{float32(offset[0]+1) * ground.spacing, + float32(ground.floors[cell]) * ground.scale, + float32(offset[1]+1) * ground.spacing} } indices := [3]int{0, 1, 2} height := corners[0][1] + u*(corners[1][1]-corners[0][1]) + v*(corners[2][1]-corners[1][1]) @@ -213,17 +226,12 @@ func (scene *missionScene) floor(origin [3]float32, point, normal *[3]float32) { indices = [3]int{0, 2, 3} height = corners[0][1] + u*(corners[2][1]-corners[3][1]) + v*(corners[3][1]-corners[0][1]) } - height += room.position[1] - if height > point[1] { - var first, second [3]float32 - for axis := range 3 { - first[axis] = corners[indices[1]][axis] - corners[indices[0]][axis] - second[axis] = corners[indices[2]][axis] - corners[indices[0]][axis] - } - *point = [3]float32{origin[0], height, origin[2]} - *normal = roomRotate(surfaceNormal(second, first), room.rotation) + var first, second [3]float32 + for axis := range 3 { + first[axis] = corners[indices[1]][axis] - corners[indices[0]][axis] + second[axis] = corners[indices[2]][axis] - corners[indices[0]][axis] } - point[1] = max(float32(.001), min(point[1], float32(1999.9))) + return height, surfaceNormal(second, first) } func (scene *missionScene) line(origin, end [3]float32) surfaceIntersection { diff --git a/server/mission_world.go b/server/mission_world.go @@ -0,0 +1,162 @@ +package main + +import ( + "ao/server/gamedata" + "fmt" + "math" +) + +func (geometry *sceneGeometry) mission(identity uint32) *missionScene { + geometry.mutex.Lock() + defer geometry.mutex.Unlock() + return geometry.missions[identity] +} + +func (geometry *sceneGeometry) physical(identity uint32) bool { + if geometry == nil { + return false + } + if geometry.mission(identity) != nil { + return true + } + _, exists := geometry.playfields[identity] + return exists && geometry.terrain[identity] != nil +} + +func (geometry *sceneGeometry) addMission(identity uint32, layout missionLayout) error { + _, public := gamedata.Playfields[identity] + _, outdoor := geometry.playfields[identity] + if identity == 0 || public || outdoor { + return fmt.Errorf("mission identity %d conflicts with a public playfield", identity) + } + scene, err := geometry.missionScene(layout) + if err != nil { + return err + } + if err := scene.connectRooms(layout); err != nil { + return err + } + + // Publish only complete scenes; immutable room meshes remain shared across instances. + geometry.mutex.Lock() + defer geometry.mutex.Unlock() + if geometry.missions[identity] != nil { + return fmt.Errorf("mission identity %d is already registered", identity) + } + if geometry.missions == nil { + geometry.missions = make(map[uint32]*missionScene) + } + geometry.missions[identity] = scene + return nil +} + +func (geometry *sceneGeometry) removeMission(identity uint32) { + geometry.mutex.Lock() + defer geometry.mutex.Unlock() + delete(geometry.missions, identity) +} + +func (scene *missionScene) connectRooms(layout missionLayout) error { + // client/game/kkr.dll/lifted-0071.c, sub_360F2F30: opposing portals on the same floor. + type portal struct { + room *placedRoom + position [3]float32 + direction byte + floor int8 + paired bool + } + var portals []portal + for index := range scene.rooms { + room := &scene.rooms[index] + for _, door := range room.template.doors { + // CreateDungeonRoom turns internal template links into self-links. + if door[0] != -1 { + continue + } + position, direction := scene.portal(room, uint16(door[1])) + portals = append(portals, portal{room: room, position: position, direction: direction, floor: layout.rooms[index].floor}) + } + } + for index := range portals { + first := &portals[index] + if first.paired { + continue + } + match := -1 + for other := index + 1; other < len(portals); other++ { + second := &portals[other] + if second.paired || first.room == second.room || first.floor != second.floor || (first.direction+2)&3 != second.direction { + continue + } + if math.Abs(float64(first.position[0]-second.position[0])) < .1 && + math.Abs(float64(first.position[1]-second.position[1])) < .3 && + math.Abs(float64(first.position[2]-second.position[2])) < .1 { + if match != -1 { + return fmt.Errorf("ambiguous dungeon portal") + } + match = other + } + } + if match == -1 { + if scene.entrance != nil { + return fmt.Errorf("dungeon must have exactly one exterior portal") + } + scene.entrance = first.room + continue + } + first.paired, portals[match].paired = true, true + scene.links = append(scene.links, [2]*placedRoom{first.room, portals[match].room}) + } + if scene.entrance == nil { + return fmt.Errorf("dungeon has no exterior portal") + } + + // Every published room must be reachable from the unique exterior entrance. + visited := map[*placedRoom]bool{scene.entrance: true} + queue := []*placedRoom{scene.entrance} + for len(queue) != 0 { + room := queue[0] + queue = queue[1:] + for _, link := range scene.links { + for side := range 2 { + if link[side] == room && !visited[link[1-side]] { + visited[link[1-side]] = true + queue = append(queue, link[1-side]) + } + } + } + } + if len(visited) != len(scene.rooms) { + return fmt.Errorf("dungeon contains unreachable rooms") + } + return nil +} + +func (scene *missionScene) portal(room *placedRoom, code uint16) ([3]float32, byte) { + // client/game/llr.dll/lifted-0020.c, sub_38033650: GetDoorPosRot, before facing inward. + width := int(room.template.bounds[2] - room.template.bounds[0]) + depth := int(room.template.bounds[3] - room.template.bounds[1]) + local := [3]float32{float32(int(code>>2)%width)*scene.ground.spacing + 1, 0, float32(int(code>>2)/width)*scene.ground.spacing + 1} + switch code & 3 { + case 0: + local[2] += .999 + case 1: + local[0] += .999 + case 2: + local[2] -= .999 + case 3: + local[0] -= .999 + } + atlas := local + atlas[0] += float32(room.template.bounds[0]) * scene.ground.spacing + atlas[2] += float32(room.template.bounds[1]) * scene.ground.spacing + height, _ := scene.ground.floor(atlas) + local[1] = height - room.template.minHeight + local[0] -= float32(((width-1)&^1)+1)*.5*scene.ground.spacing + 1 + local[2] -= float32(((depth-1)&^1)+1)*.5*scene.ground.spacing + 1 + local = roomRotate(local, room.rotation) + for axis := range local { + local[axis] += room.position[axis] + } + return local, (byte(code) + room.rotation) & 3 +} diff --git a/server/mission_world_test.go b/server/mission_world_test.go @@ -0,0 +1,152 @@ +package main + +import ( + "math" + "sync" + "testing" +) + +func fixedMissionLayout() missionLayout { + return missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, + rooms: []missionRoom{{template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}} +} + +func TestMissionWorldRegistersOriginalPortalLinksAtEveryRotation(t *testing.T) { + geometry := missionGeometryFixture(t) + for _, scenario := range []struct { + name string + width, depth uint16 + rooms []missionRoom + first [3]float32 + second [3]float32 + }{ + {"north", 4, 6, []missionRoom{{template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}, [3]float32{15, 0, 29.999}, [3]float32{15, 0, 30.001}}, + {"east", 6, 4, []missionRoom{{template: 0, x: 1, z: 1, rotation: 3}, {template: 37, x: 3, z: 1, rotation: 1}}, [3]float32{29.999, 0, 25}, [3]float32{30.001, 0, 25}}, + {"south", 4, 6, []missionRoom{{template: 0, x: 2, z: 1}, {template: 37, x: 1, z: 3, rotation: 2}}, [3]float32{25, 0, 30.001}, [3]float32{25, 0, 29.999}}, + {"west", 6, 4, []missionRoom{{template: 0, x: 3, z: 2, rotation: 1}, {template: 37, x: 1, z: 1, rotation: 3}}, [3]float32{30.001, 0, 15}, [3]float32{29.999, 0, 15}}, + } { + t.Run(scenario.name, func(t *testing.T) { + layout := missionLayout{template: 331, width: scenario.width, depth: scenario.depth, floorHeight: 10, rooms: scenario.rooms} + + if err := geometry.addMission(9000001, layout); err != nil { + t.Fatal(err) + } + scene := geometry.mission(9000001) + first, direction := scene.portal(&scene.rooms[0], 10) + second, opposite := scene.portal(&scene.rooms[1], 10) + geometry.removeMission(9000001) + + if scene.entrance != &scene.rooms[0] || len(scene.links) != 1 || scene.links[0] != [2]*placedRoom{&scene.rooms[0], &scene.rooms[1]} { + t.Fatal("original portal pairing or unique exterior room", scene.entrance, scene.links) + } + if surfaceDistanceSquared(first, scenario.first) > .000000001 || surfaceDistanceSquared(second, scenario.second) > .000000001 || (direction+2)&3 != opposite { + t.Fatal("native portal positions and opposing directions", first, second, direction, opposite) + } + if scene.roomAt(scene.safePosition()) != scene.entrance || geometry.physical(9000001) { + t.Fatal("safe room or retired world lookup", scene.safePosition()) + } + }) + } +} + +func TestMissionWorldRejectsPublicDuplicateAndUnpairedLayouts(t *testing.T) { + geometry := missionGeometryFixture(t) + if err := geometry.addMission(9000001, fixedMissionLayout()); err != nil { + t.Fatal(err) + } + original := geometry.mission(9000001) + for _, scenario := range []struct { + name string + identity uint32 + change func(*missionLayout) + }{ + {"zero identity", 0, func(*missionLayout) {}}, + {"public outdoor", 705, func(*missionLayout) {}}, + {"public indoor", 3000, func(*missionLayout) {}}, + {"duplicate", 9000001, func(*missionLayout) {}}, + {"unpaired entrance", 9000002, func(layout *missionLayout) { layout.rooms = layout.rooms[:1] }}, + {"misaligned portals", 9000002, func(layout *missionLayout) { layout.rooms[1].x = 2 }}, + {"different authored floors", 9000002, func(layout *missionLayout) { layout.rooms[1].floor = 1 }}, + {"nonopposing portals", 9000002, func(layout *missionLayout) { layout.rooms[1].rotation = 1 }}, + {"ambiguous pair", 9000002, func(layout *missionLayout) { layout.rooms = append(layout.rooms, layout.rooms[1]) }}, + {"no exterior", 9000002, func(layout *missionLayout) { + layout.rooms = []missionRoom{{template: 37, x: 1, z: 1}, {template: 37, x: 0, z: 3, rotation: 2}} + }}, + {"unreachable closed pair", 9000002, func(layout *missionLayout) { + layout.width = 8 + layout.rooms = append(layout.rooms, missionRoom{template: 37, x: 5, z: 1}, missionRoom{template: 37, x: 4, z: 3, rotation: 2}) + }}, + } { + t.Run(scenario.name, func(t *testing.T) { + layout := fixedMissionLayout() + scenario.change(&layout) + + err := geometry.addMission(scenario.identity, layout) + + if err == nil || geometry.mission(9000001) != original || geometry.mission(9000002) != nil { + t.Fatal("invalid registration changed live geometry", err) + } + }) + } +} + +func TestMissionWorldRoutesCommonQueriesWithoutOutdoorTerrainAndIsolatesInstances(t *testing.T) { + geometry := missionGeometryFixture(t) + if err := geometry.addMission(9000001, fixedMissionLayout()); err != nil { + t.Fatal(err) + } + shifted := fixedMissionLayout() + shifted.width, shifted.rooms[0].x, shifted.rooms[1].x = 6, 3, 3 + if err := geometry.addMission(9000002, shifted); err != nil { + t.Fatal(err) + } + var point, normal [3]float32 + + wall := geometry.line(9000001, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true) + other := geometry.line(9000002, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true) + contact := geometry.sphere(9000001, [3]float32{17.1, .8, 16}, .25) + liquid := geometry.floor(9000002, nil, [3]float32{35, 1, 35}, &point, &normal) + first, second := geometry.mission(9000001), geometry.mission(9000002) + geometry.removeMission(9000001) + after := geometry.line(9000001, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true) + + if !wall.hit || math.Abs(float64(wall.point[0]-17.601997)) > .00001 || other.hit || !contact.hit || after.hit { + t.Fatal("common queries missed mission dispatch or crossed world identities", wall, other, contact, after) + } + if point != [3]float32{35, .001, 35} || normal != [3]float32{0, 1, 0} || liquid != (waterContact{}) { + t.Fatal("dry mission floor must work without outdoor terrain", point, normal, liquid) + } + if first.rooms[0].surface != second.rooms[0].surface || &first.rooms[0] == &second.rooms[0] || !geometry.physical(9000002) || geometry.physical(9000001) { + t.Fatal("retirement must preserve the other instance and its shared immutable mesh") + } +} + +func TestMissionWorldConcurrentRegistrationQueriesAndRetirement(t *testing.T) { + geometry := missionGeometryFixture(t) + if err := geometry.addMission(9000001, fixedMissionLayout()); err != nil { + t.Fatal(err) + } + var workers sync.WaitGroup + + for range 4 { + workers.Go(func() { + for range 30 { + if !geometry.line(9000001, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true).hit { + t.Error("stable instance lost its wall") + } + geometry.line(9000002, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true) + } + }) + } + for range 5 { + if err := geometry.addMission(9000002, fixedMissionLayout()); err != nil { + t.Fatal(err) + } + geometry.removeMission(9000002) + } + workers.Wait() + + if !geometry.physical(9000001) || geometry.physical(9000002) { + t.Fatal("concurrent retirement crossed world identities") + } +} diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -395,6 +395,7 @@ func (server *server) finishResourceChange_locked(updates map[*worldClient][][]b if client := server.clients[player.id]; client != nil && (previous.maximumHealth() != player.maximumHealth() || previous.nanoBonus(156) != player.nanoBonus(156)) { snapshot := previous.predictedMovement(now) player.position, player.rotation, player.movement = snapshot.position, snapshot.rotation, snapshot.movement + player.roomState = snapshot.roomState } // Refresh the native resource caches when derived maxima change. diff --git a/server/player_collision.go b/server/player_collision.go @@ -203,7 +203,7 @@ func (player *character) jump() { } abilities := player.baseStats().Abilities height := float32(1 + float64(float32(.005))*float64(uint32(abilities.Strength)+uint32(abilities.Agility))) - if player.geometry != nil && player.geometry.terrain[player.playfield] != nil { + if player.geometry.physical(player.playfield) { player.collisionBody() end := player.position end[1] += 100 @@ -274,14 +274,7 @@ func (player *character) alignSurface(previous [3]float32, skipSegment bool) { // Source: client/game/qqr.dll/lifted-0006.c, sub_42012A50. movement := &player.movement movement.normal = [3]float32{0, 1, 0} - if player.geometry == nil || player.geometry.terrain[player.playfield] == nil { - if movement.falling { - player.land(player.position[1]) - } - return - } - layout, exists := player.geometry.playfields[player.playfield] - if !exists { + if !player.geometry.physical(player.playfield) { if movement.falling { player.land(player.position[1]) } @@ -301,7 +294,7 @@ func (player *character) alignSurface(previous [3]float32, skipSegment bool) { for remaining := 5; remaining > 0; remaining-- { // Veto and all retries keep the same outer-frame historical position. previousY := position[1] - retry := layout.veto(&position, &previous) + retry := player.vetoPosition(&position, &previous) if movement.falling && (position[1] != previousY || retry) { point = [3]float32{} probe := position @@ -436,7 +429,7 @@ func (player *character) alignSurface(previous [3]float32, skipSegment bool) { } } if corrected { - layout.veto(&position, nil) + player.vetoPosition(&position, nil) } player.position = position player.orientMovement() diff --git a/server/player_movement.go b/server/player_movement.go @@ -78,6 +78,7 @@ func (player *character) predictedMovement(now time.Time) character { func (player *character) anchorMovement_locked(now time.Time) { snapshot := player.predictedMovement(now) player.position, player.rotation, player.movement, player.body = snapshot.position, snapshot.rotation, snapshot.movement, snapshot.body + player.roomState = snapshot.roomState player.movement.prepare(player, now) player.movement.updatedAt = now } @@ -89,6 +90,7 @@ func (player *character) updateMovementPermission(previous *character, now time. // Settle the old controller on detached outcome state before changing permission. snapshot := previous.predictedMovement(now) player.position, player.rotation, player.movement, player.body = snapshot.position, snapshot.rotation, snapshot.movement, snapshot.body + player.roomState = snapshot.roomState if player.movementRestricted() { player.restrictMovement() return @@ -205,10 +207,7 @@ func (player *character) advanceMovement(now time.Time, target [3]float32) bool return heightLimited } movement.prepare(player, now) - physical := player.geometry != nil && player.geometry.terrain[player.playfield] != nil - if physical { - _, physical = player.geometry.playfields[player.playfield] - } + physical := player.geometry.physical(player.playfield) bodyMass, carriedMass := player.movementMass() changed := false duration := float32(seconds) diff --git a/server/scene_geometry.go b/server/scene_geometry.go @@ -14,6 +14,7 @@ type sceneGeometry struct { waters map[uint32]*sceneWater models map[uint32]collisionSphere terrain map[uint32]*terrain + missions map[uint32]*missionScene } func readSceneGeometry(files fs.FS) (*sceneGeometry, error) { @@ -92,6 +93,9 @@ func (geometry *sceneGeometry) surface(identity uint32) *sceneSurface { } func (geometry *sceneGeometry) sphere(playfield uint32, center [3]float32, radius float32) surfaceContact { + if scene := geometry.mission(playfield); scene != nil { + return scene.sphere(center, radius) + } layout, exists := geometry.playfields[playfield] if !exists { return surfaceContact{} diff --git a/server/scene_queries.go b/server/scene_queries.go @@ -68,6 +68,9 @@ func (layout scenePlayfield) veto(position, previous *[3]float32) bool { } func (geometry *sceneGeometry) line(playfield uint32, ground *terrain, origin, end [3]float32, clip bool) surfaceIntersection { + if scene := geometry.mission(playfield); scene != nil { + return scene.line(origin, end) + } layout, exists := geometry.playfields[playfield] if !exists { return surfaceIntersection{} @@ -86,6 +89,10 @@ func (geometry *sceneGeometry) line(playfield uint32, ground *terrain, origin, e } func (geometry *sceneGeometry) floor(playfield uint32, ground *terrain, origin [3]float32, point, normal *[3]float32) waterContact { + if scene := geometry.mission(playfield); scene != nil { + scene.floor(origin, point, normal) + return waterContact{} + } // Source: client/game/llr.dll/lifted-0023.c, sub_3803B690. // Invalid cells leave the caller's point and normal unchanged. layout, exists := geometry.playfields[playfield] diff --git a/server/state.go b/server/state.go @@ -46,6 +46,7 @@ type character struct { movement playerMovement geometry *sceneGeometry body playerCollisionBody + roomState playerRoomState returnDoor *doorOrigin npc bool npcDefinitionID string