commit db54974f453aece70fba04c938b1ef2d217213ad parent 032be4b3e4dffc8b225ff77e9bd3780996a2c7f7 Author: anon <anon@example.com> Date: Sat, 7 Nov 2026 07:11:04 +0000 Decode shared geometry independently by resource Diffstat:
22 files changed, 312 insertions(+), 146 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -69,7 +69,9 @@ replacement. | Responsibility | Owner and boundary | | --- | --- | | Protocol and sessions | `main.go` decodes native messages and owns socket deadlines; `world_dispatch.go` dispatches game commands; `browser_socket.go` and `browser_account.go` authorize browser streams and credentials. Connection state belongs to `worldClient`, `chatClient` and their output/stream adapters. Decode and authorize before invoking a game action. | -| World simulation | `state.go` owns characters and live sessions. `simulation.go` starts the movement, roaming/action, zoning and checkpoint loops used by both executable entry points. Browser scenarios must not supply their own tick loops. | +| World simulation | Each `zone_runtime.go` goroutine exclusively owns its zone's characters, sessions, inventories, spatial indexes and lifecycle queues. It processes commands and simulation ticks. `simulation.go` starts and drains these owners. Browser scenarios must not supply their own tick loops. | +| Cross-zone coordination | `world_runtime.go` owns routing and detached metadata; `world_operations.go` coordinates operations involving multiple owners. Team and chat owners exchange detached messages with zones. Never read another zone's entity pointers. | +| Shared geometry | Asset decoders publish immutable results once per resource through `sync.Map` and `sync.OnceValue`. A short mutex protects mission registrations; decoding and geometry queries execute outside it. Navigation jobs pin their mission scene until completion. | | Rules and content | Action implementations such as `inventory.go`, combat and nano handlers decide admission and outcomes using `gamedata`. UI and transport code report those outcomes rather than reproducing the rules. | | Durable transactions | `database.go`, `item_store.go` and `world_store.go` own database records, item ownership and checkpoints. Significant actions commit their related changes before updating shared ownership or publishing success. Keep frequent movement in memory until its checkpoint. | @@ -85,8 +87,10 @@ Existing mutation helpers retain zone-local `mutex` and `updateMutex` wrappers, also used by standalone test fixtures. Helpers suffixed `_locked` require the corresponding local lock; acquire `updateMutex` before `mutex`. These wrappers do not grant access to another zone. Use owner commands for external access and the -existing output queues for network delivery. Transport buffers and geometry -caches retain their own small locks. +existing output queues for network delivery. Connection-local transport buffers +retain small mutexes. Geometry has no shared lock around asset reads or decoding; +concurrent requests for one resource share its result while other resources load +independently. Stop zone/navigation readers before closing the asset archive. Unworn item moves between carried slots, backpacks and the bank use `moveStoredItem`: SQLite checks the expected source and backpack ownership, diff --git a/TODO.md b/TODO.md @@ -42,21 +42,24 @@ research separately. More screenshots and test cases do not count as new gamepla Authenticated HTTP requests measured 1.1-3.3 ms with the native client running, and a regression confirms the response completes while the simulation is locked. -- [ ] **Finish goroutine ownership and remove global mutex machinery.** The - production cutover below isolates zones, but simulation helpers and older +- [ ] **Finish goroutine ownership and remove the global simulation lock.** + Production partitions mutable state by zone, but simulation helpers and older concurrent test harnesses still use the old mutex fields. Remove those fields - and lock wrappers, route every concurrent state access through its owner, and - replace server-wide password/database initialization locks with explicit - service lifetimes. Password derivation now has a channel worker, and database - construction is explicit before requests begin; both mutex fields are removed. - Routed fixtures now use production partitioning, and native connection, - inventory and restart tests are moving onto production service ownership. - The browser resource index publishes immutable results through completion - channels instead of a global mutex, and a service-owned writer serializes - profile batches and their size checks. Simulation mutexes and their dependent - harnesses remain; audit the shared geometry cache separately. Completion - requires source inspection, race coverage of the migrated harnesses, and real-server protocol - verification; the existing production isolation tests alone are insufficient. + and redundant wrappers, route concurrent state access through its owner, and + delete obsolete execution paths. Keep small, justified mutexes where they are + simpler and efficient; zero mutexes is not the goal. Password derivation has a + channel worker, database construction is explicit before requests begin, and + native connection, inventory and restart fixtures use production partitioning. + Shared geometry now decodes immutable assets once per resource outside map + synchronization; a short mission-registry mutex protects only registration + access. Navigation jobs retain their scene across retirement. Connection-local + output and stream locks remain appropriate. Completion requires clear ownership + boundaries, relevant correctness and race coverage, real-server protocol tests, + and representative busy-zone isolation measurements. Compare latency, + throughput, CPU per action and memory with the pre-initiative baseline, and + document remaining bottlenecks and measured capacity. Existing production + isolation tests and the 500-client comparison below are evidence, not completion + of the remaining migration. - [x] **Use the original native character creation flow.** Login credentials are collected in a compact modal with password confirmation at native naming, diff --git a/server/combat_visibility_test.go b/server/combat_visibility_test.go @@ -12,11 +12,11 @@ func addCombatWall(world *server) { playfields: map[uint32]scenePlayfield{950: {sizeX: 100, sizeZ: 100, cellsX: 1, cellsZ: 1}}, terrain: map[uint32]*terrain{950: {width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 50, scale: 1, heights: make([]byte, 9)}}, - surfaces: map[uint32]*sceneSurface{950 << 16: {primary: &surfaceTree{ + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{950 << 16: {primary: &surfaceTree{ vertices: [][3]float32{{15, 0, 0}, {15, 0, 100}, {15, 10, 0}}, groups: []surfaceGroup{{bounds: [6]float32{15, 0, 0, 15, 10, 100}, triangles: [][3]uint32{{0, 1, 2}}}}, nodes: []surfaceNode{{groups: []uint32{0}}}, - }}}, + }}}), } world.characters[1].position = [3]float32{14, 0, 10} world.characters[1000000].position = [3]float32{16, 0, 10} @@ -139,7 +139,7 @@ func TestCombatVisibilitySpecialsRejectWithoutLocksOrClockChanges(t *testing.T) func TestCombatVisibilityUsesNativeEyeHeightAboveLowScenery(t *testing.T) { world, _ := newCombatWorld(t) addCombatWall(world) - wall := world.geometry.surfaces[950<<16].primary + wall := world.geometry.surface(950 << 16).primary wall.vertices[2][1], wall.groups[0].bounds[4] = 1, 1 player, target := world.characters[1], world.characters[1000000] target.monsterData = 17655 diff --git a/server/fixture_database_test.go b/server/fixture_database_test.go @@ -9,6 +9,13 @@ import ( func newServerForTest(t *testing.T) *server { t.Helper() world := newServer() + geometry := world.geometry + t.Cleanup(func() { + world.stopNavigation() + if err := geometry.close(); err != nil { + t.Error(err) + } + }) if _, synthetic := resources.(npcFixtureResources); synthetic { // Artificial terrain grids do not describe the original outdoor scenery. world.geometry.playfields = nil diff --git a/server/mission_entrance_test.go b/server/mission_entrance_test.go @@ -27,7 +27,6 @@ func reloadMissionEntranceWorld(t *testing.T) *server { world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), geometry: missionGeometryFixture(t)} openTestDatabase(t, world) - world.geometry.models = make(map[uint32]collisionSphere) if _, err := world.loadNPCs(); err != nil { t.Fatal(err) } diff --git a/server/mission_offers_test.go b/server/mission_offers_test.go @@ -255,7 +255,6 @@ func newMissionOfferWorld(t *testing.T) (*server, *combatTestConn) { t.Cleanup(func() { gamedata.MissionTemplates[3221228472] = definition }) world, output := newEquipmentWorld(t) world.geometry = missionGeometryFixture(t) - world.geometry.models = make(map[uint32]collisionSphere) player := world.characters[1] player.playfield, player.position = 3000, [3]float32{100, 115.75, 145} inventory := player.inventory diff --git a/server/mission_scene_test.go b/server/mission_scene_test.go @@ -19,8 +19,9 @@ func missionGeometryFixture(t *testing.T) *sceneGeometry { if err != nil { t.Fatal(err) } - t.Cleanup(func() { database.file.Close() }) - return &sceneGeometry{database: database, surfaces: make(map[uint32]*sceneSurface)} + geometry := newSceneGeometry(database) + t.Cleanup(func() { geometry.close() }) + return geometry } func TestMissionSceneSamplesDungeonTrianglesAndRotatesGridNormals(t *testing.T) { @@ -191,7 +192,7 @@ func TestMissionScenePlacesTheNativeTwoRoomLayout(t *testing.T) { if scene.rooms[0].template.position != [3]float32{24, 0, 368} || scene.rooms[1].template.position != [3]float32{212, 0, 178} { t.Fatal("template-world surface origins must survive placement") } - if scene.rooms[0].surface != geometry.surfaces[331<<16] || scene.rooms[1].surface != geometry.surfaces[331<<16|37] { + if scene.rooms[0].surface != geometry.surface(331<<16) || scene.rooms[1].surface != geometry.surface(331<<16|37) { t.Fatal("generated rooms must share original immutable surface trees") } } @@ -280,7 +281,9 @@ func TestMissionSceneRejectsUnavailableOrIncompleteRoomAssignments(t *testing.T) layout.template = 341 layout.rooms[0].template = 21 }}, - {"missing surface", func(layout *missionLayout, geometry *sceneGeometry) { geometry.surfaces[331<<16] = nil }}, + {"missing surface", func(layout *missionLayout, geometry *sceneGeometry) { + geometry.surfaces.values.Store(uint32(331<<16), func() *sceneSurface { return nil }) + }}, } { t.Run(scenario.name, func(t *testing.T) { geometry := missionGeometryFixture(t) @@ -391,7 +394,8 @@ func TestMissionScenesShareMeshesWithoutSharingPlacement(t *testing.T) { var point, normal [3]float32 scene.floor([3]float32{15, float32(level)*10 + 1, 35}, &point, &normal) wall := scene.line([3]float32{15, 1, 16}, [3]float32{20, 1, 16}) - results <- point == [3]float32{15, max(.001, float32(level)*10), 35} && normal == [3]float32{0, 1, 0} && wall.hit && scene.rooms[1].position[1] == float32(level)*10 + results <- point == [3]float32{15, max(.001, float32(level)*10), 35} && normal == [3]float32{0, 1, 0} && wall.hit && scene.rooms[1].position[1] == float32(level)*10 && + scene.rooms[0].surface == geometry.surface(331<<16) && scene.rooms[1].surface == geometry.surface(331<<16|37) }() } workers.Wait() @@ -402,9 +406,6 @@ func TestMissionScenesShareMeshesWithoutSharingPlacement(t *testing.T) { t.Fatal("concurrent scene changed another scene's floor placement") } } - if len(geometry.surfaces) != 2 { - t.Fatal("instances must reuse the same two immutable room meshes", len(geometry.surfaces)) - } } func TestMissionSceneSelectsStackedRoomsByHeight(t *testing.T) { diff --git a/server/mission_world.go b/server/mission_world.go @@ -7,8 +7,8 @@ import ( ) func (geometry *sceneGeometry) mission(identity uint32) *missionScene { - geometry.mutex.Lock() - defer geometry.mutex.Unlock() + geometry.missionsMutex.RLock() + defer geometry.missionsMutex.RUnlock() return geometry.missions[identity] } @@ -38,22 +38,19 @@ func (geometry *sceneGeometry) addMission(identity uint32, layout missionLayout) } // Publish only complete scenes; immutable room meshes remain shared across instances. - geometry.mutex.Lock() - defer geometry.mutex.Unlock() + geometry.missionsMutex.Lock() + defer geometry.missionsMutex.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() + geometry.missionsMutex.Lock() delete(geometry.missions, identity) + geometry.missionsMutex.Unlock() } func (scene *missionScene) connectRooms(layout missionLayout) error { diff --git a/server/mission_world_test.go b/server/mission_world_test.go @@ -153,3 +153,43 @@ func TestMissionWorldConcurrentRegistrationQueriesAndRetirement(t *testing.T) { t.Fatal("concurrent retirement crossed world identities") } } + +func TestMissionWorldConcurrentRegistrationPreservesEveryIdentity(t *testing.T) { + geometry := missionGeometryFixture(t) + identities := []uint32{9000001, 9000002, 9000003, 9000004} + results := make(chan error, len(identities)) + for _, identity := range identities { + go func() { results <- geometry.addMission(identity, fixedMissionLayout()) }() + } + for range identities { + if err := <-results; err != nil { + t.Error(err) + } + } + + for _, identity := range identities { + if !geometry.physical(identity) || !geometry.line(identity, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true).hit { + t.Fatal("concurrent registration lost another mission scene", identity) + } + } +} + +func TestMissionWorldNavigationViewRetainsItsRetiredScene(t *testing.T) { + geometry := missionGeometryFixture(t) + if err := geometry.addMission(9000001, fixedMissionLayout()); err != nil { + t.Fatal(err) + } + view := geometry.navigationGeometry(9000001) + geometry.removeMission(9000001) + shifted := fixedMissionLayout() + shifted.width, shifted.rooms[0].x, shifted.rooms[1].x = 6, 3, 3 + if err := geometry.addMission(9000001, shifted); err != nil { + t.Fatal(err) + } + + old := view.line(9000001, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true) + current := geometry.line(9000001, nil, [3]float32{15, 1, 16}, [3]float32{20, 1, 16}, true) + if !old.hit || current.hit { + t.Fatal("a retained navigation view changed to a replacement scene", old, current) + } +} diff --git a/server/navigation_worker.go b/server/navigation_worker.go @@ -91,9 +91,11 @@ func (server *server) requestNPCRoute_locked(npc *character, destination [3]floa func (geometry *sceneGeometry) navigationGeometry(playfield uint32) *sceneGeometry { // Mission retirement may remove the live registration while a search runs. // The completed scene stays immutable and alive until this job releases it. - return &sceneGeometry{cache: geometry, database: geometry.database, - playfields: geometry.playfields, terrain: geometry.terrain, - interiors: geometry.interiors, missions: map[uint32]*missionScene{playfield: geometry.mission(playfield)}} + view := &sceneGeometry{database: geometry.database, + playfields: geometry.playfields, terrain: geometry.terrain, interiors: geometry.interiors, + surfaces: geometry.surfaces, waters: geometry.waters, models: geometry.models} + view.missions = map[uint32]*missionScene{playfield: geometry.mission(playfield)} + return view } func (server *server) stopNavigation() { diff --git a/server/npc_motion_test.go b/server/npc_motion_test.go @@ -49,11 +49,11 @@ func TestNPCRoamingPublishesTheDestinationFloorHeight(t *testing.T) { world.geometry = &sceneGeometry{ playfields: map[uint32]scenePlayfield{950: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, terrain: world.terrain, - surfaces: map[uint32]*sceneSurface{950 << 16: nil}, - waters: map[uint32]*sceneWater{950: {zones: []waterZone{{maxHeight: -1}}}}, + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{950 << 16: nil}), + waters: sceneResourcesForTest(map[uint32]*sceneWater{950: {zones: []waterZone{{maxHeight: -1}}}}), } - advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) + advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) if npc.position != [3]float32{5, 2.01, 5} || npc.motion.home != [3]float32{5, 0, 5} || !npc.motion.moving { t.Fatal("choosing a route changed the current pose or retained home", npc.position, npc.motion) @@ -68,12 +68,12 @@ func TestNPCRoamingDoesNotAdvertiseAnOccludedRoute(t *testing.T) { world, conn, start := newNPCPursuitWorld(t) addCombatWall(world) world.terrain = world.geometry.terrain - world.geometry.waters = map[uint32]*sceneWater{950: {zones: []waterZone{{maxHeight: -1}}}} + world.geometry.waters = sceneResourcesForTest(map[uint32]*sceneWater{950: {zones: []waterZone{{maxHeight: -1}}}}) npc := world.characters[1000000] npc.fighting = 0 npc.motion.home, npc.motion.nextMove = [3]float32{5, 0, 10}, start - advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) + advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) if npc.motion.moving || npc.position != [3]float32{16, 0, 10} || len(conn.packets) != 0 { t.Fatal("idle route crossed an obstruction hidden from the native follower", npc.position, npc.motion, conn.packets) @@ -86,7 +86,7 @@ func TestNPCRoamingDoesNotAdvertiseAnOccludedRoute(t *testing.T) { func TestNPCPursuitStartsItsRouteBeforeAdvancing(t *testing.T) { world, conn, start := newNPCPursuitWorld(t) - advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) + advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) if world.characters[1000000].position != [3]float32{1, 0, 0} || !world.characters[1000000].motion.moving { t.Fatalf("pursuit started with a position jump: %v", world.characters[1000000].position) @@ -104,7 +104,7 @@ func TestNPCPursuitStopsAfterAdvancingTheCurrentInterval(t *testing.T) { world.characters[1000000].running = true world.characters[1000000].movement.velocity = [3]float32{4.5, 0, 0} - advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) + advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) if math.Abs(float64(world.characters[1000000].position[0]-2.125)) > .0001 || world.characters[1000000].motion.moving || world.characters[1000000].fighting != 1 { t.Fatalf("pursuit arrival was deferred to an outdated pose: position=%v moving=%t fighting=%d", world.characters[1000000].position, world.characters[1000000].motion.moving, world.characters[1000000].fighting) @@ -116,7 +116,7 @@ func TestNPCPursuitStopsAfterAdvancingTheCurrentInterval(t *testing.T) { func TestNPCPursuitRouteChangesPreserveNativePosition(t *testing.T) { world, conn, start := newNPCPursuitWorld(t) - advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) + advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) world.characters[1].position = [3]float32{21, 0, 1} advanceNavigationForTest(t, world, start.Add(500 * time.Millisecond), world.advanceNPCs) diff --git a/server/player_collision_test.go b/server/player_collision_test.go @@ -16,7 +16,7 @@ func newPlayerCollisionWorld(t *testing.T) *server { if err != nil { t.Fatal(err) } - t.Cleanup(func() { world.stopNavigation(); world.geometry.database.file.Close() }) + t.Cleanup(func() { world.stopNavigation(); world.geometry.close() }) world.terrain, err = readTerrain() if err != nil { t.Fatal(err) @@ -176,6 +176,7 @@ func TestPlayerCollisionScalesTheExistingPrimitiveIncrementally(t *testing.T) { t.Fatal(err) } started := player.movement.updatedAt + model := world.geometry.model(player.body.mesh) for index, scenario := range []struct { height uint16 scale, radius float32 @@ -191,7 +192,7 @@ func TestPlayerCollisionScalesTheExistingPrimitiveIncrementally(t *testing.T) { world.advancePlayerMovement(started.Add(time.Duration(index+1) * 100 * time.Millisecond)) - if player.body.scale != scenario.scale || player.body.sphere.radius != scenario.radius || player.body.sphere.offset[1] != scenario.radius || len(world.geometry.models) != 1 { + if player.body.scale != scenario.scale || player.body.sphere.radius != scenario.radius || player.body.sphere.offset[1] != scenario.radius || world.geometry.model(player.body.mesh) != model { t.Fatal("scale-only updates must share one decoded model and preserve incremental rounding", scenario.height, player.body) } } diff --git a/server/player_jump_test.go b/server/player_jump_test.go @@ -143,11 +143,13 @@ func TestPlayerJumpShortensForTheCeilingAndBodyScale(t *testing.T) { player, client := world.characters[1], world.clients[1] player.stats.Abilities.Strength, player.stats.Abilities.Agility = 6, 6 player.height = scenario.scale - world.geometry.surfaces[705<<16|384] = &sceneSurface{primary: &surfaceTree{ - vertices: [][3]float32{{960, scenario.ceiling, 500}, {980, scenario.ceiling, 500}, {960, scenario.ceiling, 530}}, - groups: []surfaceGroup{{bounds: [6]float32{960, scenario.ceiling, 500, 980, scenario.ceiling, 530}, triangles: [][3]uint32{{0, 1, 2}}}}, - nodes: []surfaceNode{{groups: []uint32{0}}}, - }} + world.geometry.surfaces.values.Store(uint32(705<<16|384), func() *sceneSurface { + return &sceneSurface{primary: &surfaceTree{ + vertices: [][3]float32{{960, scenario.ceiling, 500}, {980, scenario.ceiling, 500}, {960, scenario.ceiling, 530}}, + groups: []surfaceGroup{{bounds: [6]float32{960, scenario.ceiling, 500, 980, scenario.ceiling, 530}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + }} + }) if err := world.handleMovement(client, playerMovementRequest(player, 13)); err != nil { t.Fatal(err) diff --git a/server/scene_cache.go b/server/scene_cache.go @@ -0,0 +1,22 @@ +package main + +import "sync" + +// Immutable assets are decoded once per identity. Decoding happens outside the +// map's synchronization, so unrelated assets can load independently. +type sceneCache[T any] struct { + values sync.Map +} + +func (cache *sceneCache[T]) get(identity uint32) (T, bool) { + if value, ok := cache.values.Load(identity); ok { + return value.(func() T)(), true + } + var zero T + return zero, false +} + +func (cache *sceneCache[T]) load(identity uint32, decode func() T) T { + value, _ := cache.values.LoadOrStore(identity, sync.OnceValue(decode)) + return value.(func() T)() +} diff --git a/server/scene_cache_test.go b/server/scene_cache_test.go @@ -0,0 +1,9 @@ +package main + +func sceneResourcesForTest[T any](values map[uint32]T) *sceneCache[T] { + cache := &sceneCache[T]{} + for identity, value := range values { + cache.values.Store(identity, func() T { return value }) + } + return cache +} diff --git a/server/scene_geometry.go b/server/scene_geometry.go @@ -7,16 +7,36 @@ import ( ) type sceneGeometry struct { - cache *sceneGeometry database *gameDatabase playfields map[uint32]scenePlayfield - mutex sync.Mutex - surfaces map[uint32]*sceneSurface - waters map[uint32]*sceneWater - models map[uint32]collisionSphere + surfaces *sceneCache[*sceneSurface] + waters *sceneCache[*sceneWater] + models *sceneCache[collisionSphere] terrain map[uint32]*terrain - missions map[uint32]*missionScene interiors map[uint32]*missionScene + // Only registration lookup and publication use this mutex. Scene decoding + // and queries operate on immutable data outside it. + missionsMutex sync.RWMutex + missions map[uint32]*missionScene + closed bool +} + +func newSceneGeometry(database *gameDatabase) *sceneGeometry { + return &sceneGeometry{database: database, + surfaces: &sceneCache[*sceneSurface]{}, + waters: &sceneCache[*sceneWater]{}, + models: &sceneCache[collisionSphere]{}, + interiors: make(map[uint32]*missionScene), + missions: make(map[uint32]*missionScene)} +} + +// The service lifecycle stops readers before closing the owning geometry. +func (geometry *sceneGeometry) close() error { + if geometry == nil || geometry.database == nil || geometry.closed { + return nil + } + geometry.closed = true + return geometry.database.file.Close() } func readSceneGeometry(files fs.FS) (*sceneGeometry, error) { @@ -29,12 +49,13 @@ func readSceneGeometry(files fs.FS) (*sceneGeometry, error) { database.file.Close() return nil, err } - geometry := &sceneGeometry{database: database, playfields: playfields, surfaces: make(map[uint32]*sceneSurface), waters: make(map[uint32]*sceneWater), models: make(map[uint32]collisionSphere), interiors: make(map[uint32]*missionScene)} + geometry := newSceneGeometry(database) + geometry.playfields = playfields // Original dry interiors on the selected early city/shop routes. for _, identity := range []uint32{1180, 1183, 1186, 1191} { scene, err := geometry.staticDungeon(identity) if err != nil { - database.file.Close() + geometry.close() return nil, err } geometry.interiors[identity] = scene @@ -43,74 +64,61 @@ func readSceneGeometry(files fs.FS) (*sceneGeometry, error) { } func (geometry *sceneGeometry) model(identity uint32) collisionSphere { - if geometry.cache != nil { - return geometry.cache.model(identity) + if value, loaded := geometry.models.get(identity); loaded { + return value } - geometry.mutex.Lock() - defer geometry.mutex.Unlock() - if sphere, loaded := geometry.models[identity]; loaded { + return geometry.models.load(identity, func() collisionSphere { + payload, _, err := geometry.database.read(1010002, identity) + if err != nil { + panic(err) + } + sphere, err := decodeModelSphere(payload, 1010002, 1) + if err != nil { + panic(fmt.Errorf("collision model %d: %w", identity, err)) + } return sphere - } - payload, _, err := geometry.database.read(1010002, identity) - if err != nil { - panic(err) - } - sphere, err := decodeModelSphere(payload, 1010002, 1) - if err != nil { - panic(fmt.Errorf("collision model %d: %w", identity, err)) - } - geometry.models[identity] = sphere - return sphere + }) } func (geometry *sceneGeometry) water(playfield uint32, ground *terrain) *sceneWater { - if geometry.cache != nil { - return geometry.cache.water(playfield, ground) + if value, loaded := geometry.waters.get(playfield); loaded { + return value } - geometry.mutex.Lock() - defer geometry.mutex.Unlock() - if water, loaded := geometry.waters[playfield]; loaded { + return geometry.waters.load(playfield, func() *sceneWater { + payload, version, err := geometry.database.read(1000001, playfield) + if err != nil { + panic(err) + } + if version != 1 { + panic(fmt.Errorf("outdoor water resource %d: unsupported version %d", playfield, version)) + } + water, err := readSceneWater(payload, geometry.playfields[playfield], ground) + if err != nil { + panic(fmt.Errorf("outdoor water resource %d: %w", playfield, err)) + } return water - } - payload, version, err := geometry.database.read(1000001, playfield) - if err != nil { - panic(err) - } - if version != 1 { - panic(fmt.Errorf("outdoor water resource %d: unsupported version %d", playfield, version)) - } - water, err := readSceneWater(payload, geometry.playfields[playfield], ground) - if err != nil { - panic(fmt.Errorf("outdoor water resource %d: %w", playfield, err)) - } - geometry.waters[playfield] = water - return water + }) } func (geometry *sceneGeometry) surface(identity uint32) *sceneSurface { - if geometry.cache != nil { - return geometry.cache.surface(identity) + if value, loaded := geometry.surfaces.get(identity); loaded { + return value } - geometry.mutex.Lock() - defer geometry.mutex.Unlock() - if surface, loaded := geometry.surfaces[identity]; loaded { + return geometry.surfaces.load(identity, func() *sceneSurface { + // Missing cells are ordinary; corrupt bundled assets are an error. + if _, exists := geometry.database.positions[[2]uint32{1000013, identity}]; !exists { + return nil + } + payload, version, err := geometry.database.read(1000013, identity) + if err != nil { + panic(err) + } + surface, err := decodeSceneSurface(payload, version) + if err != nil { + panic(fmt.Errorf("scene resource %d: %w", identity, err)) + } return surface - } - if _, exists := geometry.database.positions[[2]uint32{1000013, identity}]; !exists { - geometry.surfaces[identity] = nil - return nil - } - // Missing cells are ordinary; corruption of immutable bundled assets is an error. - payload, version, err := geometry.database.read(1000013, identity) - if err != nil { - panic(err) - } - surface, err := decodeSceneSurface(payload, version) - if err != nil { - panic(fmt.Errorf("scene resource %d: %w", identity, err)) - } - geometry.surfaces[identity] = surface - return surface + }) } func (geometry *sceneGeometry) sphere(playfield uint32, center [3]float32, radius float32) surfaceContact { diff --git a/server/scene_geometry_test.go b/server/scene_geometry_test.go @@ -2,9 +2,12 @@ package main import ( "ao/server/assets" + "io" "math" "sync" + "sync/atomic" "testing" + "time" ) func TestSceneCellLineRejectsHitsOutsideTheVisitedCell(t *testing.T) { @@ -17,7 +20,7 @@ func TestSceneCellLineRejectsHitsOutsideTheVisitedCell(t *testing.T) { } geometry := &sceneGeometry{ playfields: map[uint32]scenePlayfield{705: {cellsX: 3, cellsZ: 1, cellWidth: 1, cellDepth: 1, sizeX: 3, sizeZ: 1}}, - surfaces: map[uint32]*sceneSurface{705 << 16: wall(1.5), 705<<16 | 1: wall(1.75), 705<<16 | 2: nil}, + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{705 << 16: wall(1.5), 705<<16 | 1: wall(1.75), 705<<16 | 2: nil}), } contact := geometry.cellLine(705, [3]float32{.5, .5, .5}, [3]float32{2.5, .5, .5}) @@ -35,14 +38,14 @@ func TestSceneCellLineRejectsHitsOutsideTheVisitedCell(t *testing.T) { func TestSceneSphereUsesOnlyItsCenterCell(t *testing.T) { geometry := &sceneGeometry{ playfields: map[uint32]scenePlayfield{705: {cellsX: 2, cellsZ: 1, cellWidth: 1, cellDepth: 1, sizeX: 2, sizeZ: 1}}, - surfaces: map[uint32]*sceneSurface{ + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{ 705 << 16: nil, 705<<16 | 1: {primary: &surfaceTree{ vertices: [][3]float32{{1.1, 0, 0}, {1.1, 0, 2}, {1.1, 2, 0}}, groups: []surfaceGroup{{bounds: [6]float32{1.1, 0, 0, 1.1, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}}, nodes: []surfaceNode{{groups: []uint32{0}}}, }}, - }, + }), } neighbor := geometry.sphere(705, [3]float32{.99, .5, .5}, .5) @@ -58,15 +61,18 @@ func TestSceneGeometrySharesShippedCellAcrossConcurrentQueries(t *testing.T) { if err != nil { t.Fatal(err) } - t.Cleanup(func() { geometry.database.file.Close() }) - // Interior surfaces are already cached; these queries add one outdoor cell. - initialSurfaces := len(geometry.surfaces) + t.Cleanup(func() { geometry.close() }) grounds, err := readTerrain() if err != nil { t.Fatal(err) } var workers sync.WaitGroup - results := make(chan bool, 16) + type result struct { + correct bool + surface *sceneSurface + water *sceneWater + } + results := make(chan result, 16) for range 16 { workers.Add(1) @@ -76,21 +82,88 @@ func TestSceneGeometrySharesShippedCellAcrossConcurrentQueries(t *testing.T) { line := geometry.cellLine(705, [3]float32{970, 17.5, 519.8}, [3]float32{975, 17.5, 519.8}) var point, normal [3]float32 geometry.floor(705, grounds[705], [3]float32{971.72, 17, 519.66}, &point, &normal) - results <- sphere.hit && line.hit && math.Abs(float64(line.point[0]-971.9442138671875)) < .0001 && math.Abs(float64(point[1]-16.4)) < .0001 && normal == [3]float32{0, 1, 0} + results <- result{sphere.hit && line.hit && math.Abs(float64(line.point[0]-971.9442138671875)) < .0001 && math.Abs(float64(point[1]-16.4)) < .0001 && normal == [3]float32{0, 1, 0}, + geometry.surface(46203264), geometry.water(705, grounds[705])} }() } workers.Wait() close(results) - for passed := range results { - if !passed { - t.Fatal("concurrent archive-backed wall query") + surface, water := geometry.surface(46203264), geometry.water(705, grounds[705]) + for query := range results { + if !query.correct || query.surface != surface || query.water != water { + t.Fatal("concurrent archive-backed queries did not share immutable geometry") + } + } +} + +// A slow archive read must hold only callers of that particular resource. +type gatedSceneArchive struct { + file interface { + io.ReaderAt + io.Closer + } + offset int64 + started chan struct{} + release <-chan struct{} + reads atomic.Int32 +} + +func (archive *gatedSceneArchive) ReadAt(data []byte, offset int64) (int, error) { + if offset == archive.offset { + archive.reads.Add(1) + archive.started <- struct{}{} + <-archive.release + } + return archive.file.ReadAt(data, offset) +} + +func (archive *gatedSceneArchive) Close() error { return archive.file.Close() } + +func TestSceneGeometrySlowSurfaceLoadDoesNotBlockUnrelatedModel(t *testing.T) { + geometry, err := readSceneGeometry(assets.Files) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { geometry.close() }) + release := make(chan struct{}) + archive := &gatedSceneArchive{file: geometry.database.file, + offset: int64(geometry.database.positions[[2]uint32{1000013, 46203264}]), + started: make(chan struct{}, 16), release: release} + geometry.database.file = archive + unblock := sync.OnceFunc(func() { close(release) }) + var workers sync.WaitGroup + t.Cleanup(func() { unblock(); workers.Wait() }) + contacts := make(chan bool, 16) + for range 16 { + workers.Go(func() { + contacts <- geometry.sphere(705, [3]float32{971.72, 16.66075, 519.66}, .25075).hit + }) + } + select { + case <-archive.started: + case <-time.After(time.Second): + t.Fatal("surface decoding did not reach the archive") + } + model := make(chan collisionSphere, 1) + workers.Go(func() { model <- geometry.model(5907) }) + select { + case sphere := <-model: + if sphere.radius != .25075000524520874 { + t.Fatal("unrelated model lost its authored radius", sphere) } + case <-time.After(time.Second): + t.Fatal("one slow resource blocked unrelated geometry") } - if len(geometry.surfaces) != initialSurfaces+1 || geometry.surfaces[46203264] == nil { - t.Fatal("queries must share the decoded immutable cell", len(geometry.surfaces)) + unblock() + workers.Wait() + + for range 16 { + if !<-contacts { + t.Fatal("surface readers did not receive the decoded wall") + } } - if len(geometry.waters) != 1 || geometry.waters[705] == nil { - t.Fatal("queries must share the decoded immutable water geometry", len(geometry.waters)) + if archive.reads.Load() != 1 { + t.Fatal("concurrent queries decoded the same resource more than once", archive.reads.Load()) } } diff --git a/server/scene_queries_test.go b/server/scene_queries_test.go @@ -78,7 +78,7 @@ func TestSceneLineChoosesNearestSurfaceAndTerrainOnEqualHits(t *testing.T) { t.Run(scenario.name, func(t *testing.T) { geometry := &sceneGeometry{ playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, - surfaces: map[uint32]*sceneSurface{705 << 16: sceneSlopeFixture(scenario.offset)}, + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{705 << 16: sceneSlopeFixture(scenario.offset)}), } contact := geometry.line(705, ground, [3]float32{1, 5, 2}, [3]float32{1, -5, 2}, true) @@ -93,7 +93,7 @@ func TestSceneLineChoosesNearestSurfaceAndTerrainOnEqualHits(t *testing.T) { func TestSceneLineRetainsTerrainDisplacementAfterClipping(t *testing.T) { geometry := &sceneGeometry{ playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, - surfaces: map[uint32]*sceneSurface{705 << 16: nil}, + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{705 << 16: nil}), } ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 5, scale: 1, heights: []byte{2, 2, 2, 2, 2, 2, 2, 2, 2}} @@ -132,8 +132,8 @@ func TestSceneFloorSelectsTerrainStaticAndLiquidInNativeOrder(t *testing.T) { } geometry := &sceneGeometry{ playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, - surfaces: map[uint32]*sceneSurface{705 << 16: sceneSlopeFixture(scenario.offset)}, - waters: map[uint32]*sceneWater{705: water}, + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{705 << 16: sceneSlopeFixture(scenario.offset)}), + waters: sceneResourcesForTest(map[uint32]*sceneWater{705: water}), } point, normal := [3]float32{99, 99, 99}, [3]float32{99, 99, 99} @@ -152,8 +152,8 @@ func TestSceneFloorSelectsTerrainStaticAndLiquidInNativeOrder(t *testing.T) { func TestSceneFloorPreservesOutputsOutsideCellsAndTerrainNormalOnInvalidSamples(t *testing.T) { geometry := &sceneGeometry{ playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, - surfaces: map[uint32]*sceneSurface{705 << 16: nil}, - waters: map[uint32]*sceneWater{705: {zones: []waterZone{{maxHeight: -1}}}}, + surfaces: sceneResourcesForTest(map[uint32]*sceneSurface{705 << 16: nil}), + waters: sceneResourcesForTest(map[uint32]*sceneWater{705: {zones: []waterZone{{maxHeight: -1}}}}), } ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 5, scale: 1, heights: make([]byte, 9)} point, normal := [3]float32{1, 2, 3}, [3]float32{4, 5, 6} diff --git a/server/scene_visibility_test.go b/server/scene_visibility_test.go @@ -70,7 +70,7 @@ func TestSceneVisibilityRequiresDirectRoomPairAndDestinationSurface(t *testing.T func TestSceneVisibilityRejectsOutdoorTerrainRidge(t *testing.T) { world, _ := newCombatWorld(t) addCombatWall(world) - world.geometry.surfaces[950<<16] = nil + world.geometry.surfaces.values.Store(uint32(950<<16), func() *sceneSurface { return nil }) world.geometry.terrain[950] = &terrain{width: 3, height: 2, boundsWidth: 3, boundsHeight: 2, spacing: 10, scale: 1, heights: []byte{0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0}} origin, end := [3]float32{2, 1.6, 5}, [3]float32{18, 1.6, 5} diff --git a/server/scene_water_test.go b/server/scene_water_test.go @@ -16,7 +16,7 @@ func TestSceneWaterDecodesEverySelectedOutdoorPlayfield(t *testing.T) { if err != nil { t.Fatal(err) } - t.Cleanup(func() { geometry.database.file.Close() }) + t.Cleanup(func() { geometry.close() }) grounds, err := readTerrain() if err != nil { t.Fatal(err) diff --git a/server/simulation.go b/server/simulation.go @@ -29,5 +29,5 @@ func (server *server) shutdown() error { // directory drains handoffs and each zone's final checkpoint before SQL stops. server.tasks.stop() err := server.world.stop() - return errors.Join(err, server.closeDatabase()) + return errors.Join(err, server.closeDatabase(), server.geometry.close()) } diff --git a/server/starter_missions_test.go b/server/starter_missions_test.go @@ -27,7 +27,6 @@ func newBackyardMissionWorld(t *testing.T, boothID uint32) (*server, *combatTest t.Helper() world, output := newEquipmentWorld(t) world.geometry = missionGeometryFixture(t) - world.geometry.models = make(map[uint32]collisionSphere) world.nextNPC = 2000000 world.combatRoll = func(uint32) uint32 { return 0 } player, booth := world.characters[1], gamedata.MissionBooths[boothID]