commit 9729d4441969bcfcbdc1bd10a1fb520e7dc4dd07
parent 12780bfc715560c65c06749cecf82ede86b77537
Author: anon <anon@example.com>
Date: Sat, 7 Nov 2026 16:54:00 +0000
Load zone populations on demand and hibernate empty zones
Diffstat:
30 files changed, 967 insertions(+), 110 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -75,14 +75,32 @@ replacement.
| 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. |
-Production startup checkpoints the initial population, partitions mutable state
-by playfield, and starts one `zone_runtime.go` goroutine per zone. The root server
+Production startup reserves catalog identities and partitions saved player/item
+state by playfield. Each `zone_runtime.go` owner starts with no simulation timers
+or live NPC population until gameplay needs that zone. The root server
relinquishes its character, client, item and lifecycle maps. External requests
reach owners through channels; there is no shared simulation lock across zones.
Bank, reclaim and bag contents follow their player; corpses, pets, resource state
and mission floor items belong to their physical zone. Unassigned items remain
in SQLite and are imported only through a transaction that claims ownership.
+Zone activation restores its NPC checkpoint or creates its authored population
+in one transaction. Concurrent arrivals share that owner's activation, while
+the directory continues routing other zones. NPC identities are reserved before
+activation, so late-loaded populations cannot collide with pets or respawns.
+Admin catalog, map and player-list observations do not activate populations;
+inactive NPC markers use authored positions or committed state. Game data stays
+loaded for catalog searches and validation.
+
+Five minutes after the last connection leaves, an idle zone checkpoints before
+stopping its timers and releasing NPC actors, spatial/navigation state and
+checkpoint copies. Offline players and item records remain with their owner.
+A failed checkpoint retains the live state for retry. Later gameplay restores
+the population and processes elapsed corpse/respawn deadlines before admission.
+Zones with pets or active NPC effects remain awake to finish their work; those
+zones also resume at startup without waiting for a local player. The existing
+15-minute NPC proximity grace still applies within zones that remain active.
+
Mutation helpers run on their owning zone goroutine. External callers submit
commands and receive detached results; they must not retain or inspect mutable
actors, inventories or client session state. Single-threaded unit fixtures may
diff --git a/server/admin_map.go b/server/admin_map.go
@@ -78,7 +78,7 @@ func (server *server) mapEntities(w http.ResponseWriter, r *http.Request) {
if view != "world" && zone != uint32(playfield) {
continue
}
- if err := owner.call(query); err != nil {
+ if err := owner.observe(query); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
@@ -155,6 +155,14 @@ type zoneMapNPCs struct {
}
func (query *zoneMapNPCs) execute(state *server) error {
+ if state.populationDormant() {
+ return state.visitDormantNPCs(func(id uint32, name string, position [3]float32, alive bool) {
+ point := query.point(state.playfield, position)
+ if alive && query.visible(point) {
+ query.markers[id] = mapMarker{Name: name, Point: *point}
+ }
+ })
+ }
for id, character := range state.characters {
if !character.npc || character.health == 0 {
continue
diff --git a/server/admin_pages.go b/server/admin_pages.go
@@ -47,7 +47,7 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) {
}
seconds, weather = int(snapshot.seconds), snapshot.weather
for _, owner := range snapshot.zones {
- if err := owner.call(counts); err != nil {
+ if err := owner.observe(counts); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
diff --git a/server/browser_equipment_replacement_test.go b/server/browser_equipment_replacement_test.go
@@ -22,7 +22,8 @@ func TestBrowserEquipmentReplacement(t *testing.T) {
_, source, _, _ := runtime.Caller(0)
root := filepath.Dir(filepath.Dir(source))
output := filepath.Join(root, "local/equipment-replacement", time.Now().Format("20060102-150405"))
- world := newTestServer(t)
+ t.Chdir(t.TempDir())
+ world := newDormantServerForTest(t)
for i := 0; i < 2; i++ {
player := world.newCharacter()
player.name, player.level, player.profession = fmt.Sprint("Replacement ", i), 10, 9
@@ -54,7 +55,7 @@ func TestBrowserEquipmentReplacement(t *testing.T) {
for _, phase := range []string{"live", "cold"} {
if phase == "cold" {
- world = newServerForTest(t)
+ world = newDormantServerForTest(t)
}
if !t.Run(phase, func(t *testing.T) {
shutdown := startTestService(t, world)
diff --git a/server/fixture_database_test.go b/server/fixture_database_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "maps"
"net"
"testing"
"time"
@@ -8,7 +9,33 @@ import (
func newServerForTest(t *testing.T) *server {
t.Helper()
+ world := newServerBase()
+ // A persisted serial fixture may intentionally contain only a few hand-built
+ // actors with IDs inside the real catalog's range. Restore that exact fixture.
+ var initialized bool
+ if err := world.db.QueryRow("SELECT npcs_initialized FROM world WHERE id=1").Scan(&initialized); err != nil {
+ t.Fatal(err)
+ }
+ if initialized {
+ world.populations = make(map[uint32]npcPopulation)
+ }
+ if err := world.loadInitialState(); err != nil {
+ t.Fatal(err)
+ }
+ registerServerFixture(t, world)
+ loadTestPopulations(t, world)
+ return world
+}
+
+func newDormantServerForTest(t *testing.T) *server {
+ t.Helper()
world := newServer()
+ registerServerFixture(t, world)
+ return world
+}
+
+func registerServerFixture(t *testing.T, world *server) {
+ t.Helper()
geometry := world.geometry
t.Cleanup(func() {
world.stopNavigation()
@@ -21,7 +48,6 @@ func newServerForTest(t *testing.T) *server {
world.geometry.playfields = nil
}
registerTestDatabaseCleanup(t, world)
- return world
}
func openTestDatabase(t *testing.T, world *server) {
@@ -142,3 +168,45 @@ func TestFixtureDisconnectsWorldBeforeClosingDatabase(t *testing.T) {
t.Fatal("fixture logout did not persist the paused nano duration")
}
}
+
+// Serial model fixtures materialize the same populations that live zones load
+// on demand. They keep direct entity access without a second runtime path.
+func loadTestPopulations(t *testing.T, world *server) {
+ t.Helper()
+ zones := make(map[uint32]bool)
+ for zone := range world.populations {
+ zones[zone] = true
+ }
+ for _, zone := range world.npcOwners {
+ zones[zone] = true
+ }
+ if world.savedNPCs == nil {
+ world.savedNPCs = make(map[uint32]savedNPC)
+ }
+ for zone := range zones {
+ draft := world.emptyZone()
+ draft.playfield = zone
+ draft.items = world.items
+ for id, placement := range world.itemPlacements {
+ if placement.Corpse != 0 && world.npcOwners[placement.Corpse] == zone {
+ draft.itemPlacements[id] = placement
+ }
+ }
+ if err := draft.activatePopulation(); err != nil {
+ t.Fatal(err)
+ }
+ for _, npc := range draft.characters {
+ world.addNPC(npc)
+ }
+ maps.Copy(world.savedNPCs, draft.savedNPCs)
+ maps.Copy(world.mobileNPCs, draft.mobileNPCs)
+ world.npcRespawns = append(world.npcRespawns, draft.npcRespawns...)
+ world.corpseExpiry = append(world.corpseExpiry, draft.corpseExpiry...)
+ world.petExpiry = append(world.petExpiry, draft.petExpiry...)
+ }
+ world.populationLoaded = true
+ world.expirePets(time.Now(), nil)
+ if err := world.expireMissions(time.Now(), nil); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/server/inventory_test.go b/server/inventory_test.go
@@ -181,12 +181,14 @@ func newTestInventoryServer(t *testing.T) *server {
if err != nil {
t.Fatal(err)
}
- if _, err := world.loadNPCs(); err != nil {
+ world.populations = make(map[uint32]npcPopulation)
+ if err := world.preparePopulations(); err != nil {
t.Fatal(err)
}
if err := world.loadUsers(); err != nil {
t.Fatal(err)
}
+ loadTestPopulations(t, world)
return world
}
diff --git a/server/item_database.go b/server/item_database.go
@@ -697,7 +697,7 @@ func (server *server) readItems() (itemStore, error) {
return store, err
}
rows.Close()
- rows, err = server.db.Query("SELECT item_id, player_id, bank_player_id, backpack_id, corpse_id, mission_id, resource_id, position_x, position_y, position_z, slot, reclaim_at FROM item_locations")
+ rows, err = server.db.Query("SELECT item_id, player_id, bank_player_id, backpack_id, corpse_id, mission_id, resource_id, position_x, position_y, position_z, slot, reclaim_at, EXISTS(SELECT 1 FROM npcs WHERE id=corpse_id AND has_corpse) FROM item_locations")
if err != nil {
return store, err
}
@@ -708,7 +708,8 @@ func (server *server) readItems() (itemStore, error) {
var player, bank, backpack, corpse, mission, resource sql.NullInt64
var position [3]float32
var reclaim sql.NullString
- if err := rows.Scan(&id, &player, &bank, &backpack, &corpse, &mission, &resource, &position[0], &position[1], &position[2], &slot, &reclaim); err != nil {
+ var hasCorpse bool
+ if err := rows.Scan(&id, &player, &bank, &backpack, &corpse, &mission, &resource, &position[0], &position[1], &position[2], &slot, &reclaim, &hasCorpse); err != nil {
return store, err
}
server.itemPlacements[id] = itemPlacement{Player: uint32(player.Int64), Bank: uint32(bank.Int64), Backpack: uint32(backpack.Int64), Corpse: uint32(corpse.Int64), Mission: uint32(mission.Int64), Resource: uint32(resource.Int64), Position: position, Slot: slot, ReclaimAt: reclaim.String}
@@ -741,12 +742,12 @@ func (server *server) readItems() (itemStore, error) {
case backpack.Valid:
store.Items[uint32(backpack.Int64)].Slots[fmt.Sprintf("slot_%d", slot+1)] = &id
case corpse.Valid:
- npc := server.characters[uint32(corpse.Int64)]
- if npc == nil || npc.corpse == nil {
+ if !hasCorpse {
return store, fmt.Errorf("item %d belongs to unknown corpse %d", id, corpse.Int64)
}
record := store.Items[id]
- store.Corpses[npc.id] = append(store.Corpses[npc.id], ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: slot, Count: record.Count, Ammo: record.Ammo})
+ corpseID := uint32(corpse.Int64)
+ store.Corpses[corpseID] = append(store.Corpses[corpseID], ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: slot, Count: record.Count, Ammo: record.Ammo})
}
}
return store, rows.Err()
diff --git a/server/item_store.go b/server/item_store.go
@@ -377,7 +377,9 @@ func (server *server) loadItems() error {
server.worldItems = store.WorldItems
server.depletedResources = store.DepletedResources
for id, items := range store.Corpses {
- server.characters[id].corpse.items = items
+ if server.characters[id] != nil {
+ server.characters[id].corpse.items = items
+ }
}
return nil
}
diff --git a/server/mission_boundaries_test.go b/server/mission_boundaries_test.go
@@ -190,7 +190,7 @@ func TestMissionBoundariesVicinityAndHistoryStayInsideTheRuntimeWorld(t *testing
for kind := range uint32(4) {
t.Run(fmt.Sprint(kind), func(t *testing.T) {
world, _ := newMissionBoundaryWorld(t)
- outputs := [3]*combatTestConn{{}, {}, {}}
+ outputs := [3]*chatRecordingConn{{}, {}, {}}
setChatClients(t, world, map[uint32]*chatClient{1: {id: 1, conn: outputs[0]}, 2: {id: 2, conn: outputs[1]}, 3: {id: 3, conn: outputs[2]}})
world.sendVicinity(world.clients[1], kind, "private mission message", nil)
@@ -376,3 +376,19 @@ func TestMissionBoundariesRetirementEvacuatesGuestsAndPreservesTheOtherWorld(t *
}
}
}
+
+// Chat uses a different stream header from world packets.
+type chatRecordingConn struct{ combatTestConn }
+
+func (conn *chatRecordingConn) Write(packet []byte) (int, error) {
+ conn.pending = append(conn.pending, packet...)
+ for len(conn.pending) >= 4 {
+ length := int(binary.BigEndian.Uint16(conn.pending[2:4])) + 4
+ if len(conn.pending) < length {
+ break
+ }
+ conn.packets = append(conn.packets, append([]byte(nil), conn.pending[:length]...))
+ conn.pending = conn.pending[length:]
+ }
+ return len(packet), nil
+}
diff --git a/server/mission_entrance_test.go b/server/mission_entrance_test.go
@@ -28,12 +28,14 @@ func reloadMissionEntranceWorld(t *testing.T) *server {
worldServices: worldServices{geometry: missionGeometryFixture(t)}, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient),
fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character)}
openTestDatabase(t, world)
- if _, err := world.loadNPCs(); err != nil {
+ world.populations = make(map[uint32]npcPopulation)
+ if err := world.preparePopulations(); err != nil {
t.Fatal(err)
}
if err := world.loadUsers(); err != nil {
t.Fatal(err)
}
+ loadTestPopulations(t, world)
return world
}
diff --git a/server/nano_buffs.go b/server/nano_buffs.go
@@ -301,7 +301,15 @@ func writeActiveNanos(tx *sql.Tx, id uint32, effects []activeNano, now time.Time
}
func (server *server) loadActiveNanos() error {
- rows, err := server.db.Query("SELECT character_id, program_id, caster_id, remaining_ns, ticks_left, next_tick_ns FROM active_nanos ORDER BY character_id, program_id")
+ return server.restoreActiveNanos("character_id IN (SELECT id FROM players)")
+}
+
+func (server *server) restoreNPCNanos() error {
+ return server.restoreActiveNanos(fmt.Sprintf("character_id IN (SELECT id FROM characters JOIN npcs USING(id) WHERE playfield=%d)", server.playfield))
+}
+
+func (server *server) restoreActiveNanos(selection string) error {
+ rows, err := server.db.Query("SELECT character_id, program_id, caster_id, remaining_ns, ticks_left, next_tick_ns, EXISTS(SELECT 1 FROM players WHERE id=caster_id) FROM active_nanos WHERE " + selection + " ORDER BY character_id, program_id")
if err != nil {
return err
}
@@ -311,7 +319,8 @@ func (server *server) loadActiveNanos() error {
var id uint32
var effect activeNano
var delay time.Duration
- if err := rows.Scan(&id, &effect.program, &effect.caster, &effect.remaining, &effect.ticksLeft, &delay); err != nil {
+ var casterExists bool
+ if err := rows.Scan(&id, &effect.program, &effect.caster, &effect.remaining, &effect.ticksLeft, &delay, &casterExists); err != nil {
return err
}
periodic := damageOverTimeNano(effect.program)
@@ -321,7 +330,7 @@ func (server *server) loadActiveNanos() error {
return fmt.Errorf("character %d has an unsupported active nano %d", id, effect.program)
}
if periodic != nil {
- if !server.characters[id].npc || server.characters[effect.caster] == nil || effect.ticksLeft > periodic.TickCount {
+ if !server.characters[id].npc || !casterExists || effect.ticksLeft > periodic.TickCount {
return fmt.Errorf("character %d has invalid periodic nano %d", id, effect.program)
}
if effect.ticksLeft != 0 {
@@ -331,7 +340,7 @@ func (server *server) loadActiveNanos() error {
if payment {
healing = &(*gamedata.NanoTemplates[43372].Sections[2].Functions)[0]
}
- if server.characters[id].npc || server.characters[effect.caster] == nil || effect.ticksLeft > healing.TickCount || payment && effect.caster != id {
+ if server.characters[id].npc || !casterExists || effect.ticksLeft > healing.TickCount || payment && effect.caster != id {
return fmt.Errorf("character %d has invalid healing nano %d", id, effect.program)
}
effect.tickDelay = delay
diff --git a/server/npc_data_test.go b/server/npc_data_test.go
@@ -139,3 +139,15 @@ func TestNPCInstanceKeepsDefinitionID(t *testing.T) {
t.Fatal("NPC fixture lost its isolated population or required interior geometry")
}
}
+
+func readNPCSpawns() ([]*character, error) {
+ populations, err := readPopulations()
+ if err != nil {
+ return nil, err
+ }
+ var spawns []*character
+ for _, playfield := range gamedata.NPCs.Playfields {
+ spawns = append(spawns, populations[playfield.ID].spawns()...)
+ }
+ return spawns, nil
+}
diff --git a/server/npcs.go b/server/npcs.go
@@ -66,24 +66,28 @@ func (npc *character) equipNPCOutfit() {
}
}
-func readNPCSpawns() ([]*character, error) {
- data := gamedata.NPCs
+// Catalog ordinals reserve identities even while a zone has no live actors.
+type npcPopulation struct {
+ definition *gamedata.NPCPlayfield
+ first, end uint32
+}
- // Expand shared batch fields into the same live character representation.
- var spawns []*character
+func readPopulations() (map[uint32]npcPopulation, error) {
+ populations := make(map[uint32]npcPopulation)
identity := uint32(1000000)
- for _, playfield := range data.Playfields {
+ for index := range gamedata.NPCs.Playfields {
+ playfield := &gamedata.NPCs.Playfields[index]
if _, exists := gamedata.Playfields[playfield.ID]; !exists {
return nil, fmt.Errorf("NPC data: unknown playfield %d", playfield.ID)
}
+ population := npcPopulation{definition: playfield, first: identity}
for _, district := range playfield.Districts {
for _, group := range district.Groups {
+ identity += uint32(len(group.Positions))
if group.StaticMesh != 0 {
- // Resource placements reserve their source ordinal without creating actors.
- identity += uint32(len(group.Positions))
continue
}
- if data.AppearanceStatuses[group.AppearanceStatus].Confidence == "" || data.PlacementStatuses[group.PlacementStatus].Confidence == "" {
+ if gamedata.NPCs.AppearanceStatuses[group.AppearanceStatus].Confidence == "" || gamedata.NPCs.PlacementStatuses[group.PlacementStatus].Confidence == "" {
return nil, fmt.Errorf("NPC data: %d/%s/%s needs defined appearance and placement statuses", playfield.ID, district.Name, group.TemplateCode)
}
if group.Name == "" || group.MonsterData == 0 {
@@ -92,16 +96,36 @@ func readNPCSpawns() ([]*character, error) {
if group.Levels[0] == 0 || group.Levels[0] > group.Levels[1] {
return nil, fmt.Errorf("NPC data: %d/%s/%s has invalid levels %v", playfield.ID, district.Name, group.TemplateCode, group.Levels)
}
- for index, position := range group.Positions {
- // Spread placements across the authored inclusive range; selection is provisional.
- level := group.Levels[0] + uint16(index%(int(group.Levels[1])-int(group.Levels[0])+1))
- spawn := makeNPCSpawn(&group, level, position)
- spawn.id, spawn.playfield = identity, playfield.ID
- identity++
- spawns = append(spawns, &spawn)
+ }
+ }
+ population.end = identity
+ populations[playfield.ID] = population
+ }
+ return populations, nil
+}
+
+func (population npcPopulation) visit(visit func(uint32, *gamedata.NPCGroup, int, [3]float32)) {
+ identity := population.first
+ for _, district := range population.definition.Districts {
+ for index := range district.Groups {
+ group := &district.Groups[index]
+ for index, position := range group.Positions {
+ if group.StaticMesh == 0 {
+ visit(identity, group, index, position)
}
+ identity++
}
}
}
- return spawns, nil
+}
+
+func (population npcPopulation) spawns() []*character {
+ var spawns []*character
+ population.visit(func(id uint32, group *gamedata.NPCGroup, index int, position [3]float32) {
+ level := group.Levels[0] + uint16(index%(int(group.Levels[1])-int(group.Levels[0])+1))
+ spawn := makeNPCSpawn(group, level, position)
+ spawn.id, spawn.playfield = id, population.definition.ID
+ spawns = append(spawns, &spawn)
+ })
+ return spawns
}
diff --git a/server/pets.go b/server/pets.go
@@ -156,13 +156,17 @@ func (server *server) loadPets() error {
return err
}
entity, owner := server.characters[id], server.characters[pet.owner]
- entity.pet = pet
- entity.combatProfile = petCombatProfile(pet.program, entity.level)
- server.petExpiry = append(server.petExpiry, entity)
- if owner.pets == nil {
- owner.pets = make(map[uint32]bool)
+ if entity != nil {
+ entity.pet = pet
+ entity.combatProfile = petCombatProfile(pet.program, entity.level)
+ server.petExpiry = append(server.petExpiry, entity)
+ }
+ if owner != nil {
+ if owner.pets == nil {
+ owner.pets = make(map[uint32]bool)
+ }
+ owner.pets[id] = true
}
- owner.pets[id] = true
}
if err := rows.Err(); err != nil {
rows.Close()
@@ -171,7 +175,6 @@ func (server *server) loadPets() error {
if err := rows.Close(); err != nil {
return err
}
- server.expirePets(time.Now(), nil)
return nil
}
diff --git a/server/simulation.go b/server/simulation.go
@@ -7,8 +7,10 @@ import (
func (server *server) startSimulation() error {
// Persist and partition startup state before any listener admits traffic.
- if err := server.checkpointWorld(time.Now()); err != nil {
- return err
+ if !server.populationDormant() {
+ if err := server.checkpointWorld(time.Now()); err != nil {
+ return err
+ }
}
states, err := server.partitionWorld()
if err != nil {
@@ -20,10 +22,48 @@ func (server *server) startSimulation() error {
}
server.relinquishWorld()
server.world = world
+ if err := server.resumePopulationWork(); err != nil {
+ return errors.Join(err, world.stop())
+ }
server.tasks = newServiceTasks()
return nil
}
+func (server *server) resumePopulationWork() error {
+ // Timed pets and NPC effects must resume even without a local player.
+ if server.populations != nil {
+ rows, err := server.db.Query(`SELECT DISTINCT playfield FROM characters WHERE id IN
+ (SELECT npc_id FROM pets UNION SELECT character_id FROM active_nanos WHERE character_id>=1000000)`)
+ if err != nil {
+ return err
+ }
+ var awake []uint32
+ for rows.Next() {
+ var playfield uint32
+ if err := rows.Scan(&playfield); err != nil {
+ rows.Close()
+ return err
+ }
+ awake = append(awake, playfield)
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return err
+ }
+ snapshot, err := server.world.snapshot()
+ if err != nil {
+ return err
+ }
+ for _, playfield := range awake {
+ if err := snapshot.zones[playfield].call(zoneActivatePopulation{}); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
func (server *server) shutdown() error {
// Stop inputs while owners can still process their accepted work. The
// directory drains handoffs and each zone's final checkpoint before SQL stops.
diff --git a/server/state.go b/server/state.go
@@ -131,6 +131,8 @@ func (client *worldClient) send(packet []byte) error {
// Game operations run on their owning zone; cross-zone work exchanges commands
// and detached values through the directory and lifecycle coordinator.
type server struct {
+ populationLoaded bool
+ npcOwners map[uint32]uint32
worldServices
browserStreamsOnce sync.Once
browserStreamService *browserStreamRegistry
@@ -175,6 +177,24 @@ type server struct {
}
func newServer() *server {
+ state := newServerBase()
+ if err := state.loadInitialState(); err != nil {
+ panic(err)
+ }
+ return state
+}
+
+func (state *server) loadInitialState() error {
+ if err := state.preparePopulations(); err != nil {
+ return err
+ }
+ if err := state.loadUsers(); err != nil {
+ return err
+ }
+ return state.loadPets()
+}
+
+func newServerBase() *server {
server := &server{
worldServices: worldServices{loginPort: 7500, worldPort: 7501, httpPort: 8080, baseURL: "/"},
gameSeconds: 48600, clockStarted: time.Now(),
@@ -214,31 +234,6 @@ func newServer() *server {
if _, err := server.openDatabase(); err != nil {
panic(err)
}
- initialized, err := server.loadNPCs()
- if err != nil {
- panic(err)
- }
- // Create shared live instances from the loaded NPC definitions.
- if !initialized {
- spawns, err := readNPCSpawns()
- if err != nil {
- panic(err)
- }
- server.placeFallbackNPCs(spawns)
- for _, spawn := range spawns {
- server.addNPC(spawn)
- server.nextNPC = max(server.nextNPC, spawn.id+1)
- if spawn.motion != nil {
- server.mobileNPCs[spawn.playfield] = append(server.mobileNPCs[spawn.playfield], spawn)
- }
- }
- }
- if err := server.loadUsers(); err != nil {
- panic(err)
- }
- if err := server.loadPets(); err != nil {
- panic(err)
- }
return server
}
diff --git a/server/users.go b/server/users.go
@@ -172,8 +172,10 @@ func (server *server) loadUsers() error {
server.characters[mission.owner].missions = append(server.characters[mission.owner].missions, mission)
}
}
- if err := server.expireMissions(time.Now(), nil); err != nil {
- return err
+ if !server.populationDormant() {
+ if err := server.expireMissions(time.Now(), nil); err != nil {
+ return err
+ }
}
// No cast survives process startup; restore its reserved points exactly once.
for _, player := range server.characters {
diff --git a/server/world.sql b/server/world.sql
@@ -168,6 +168,10 @@ CREATE TABLE IF NOT EXISTS active_nanos (
next_tick_ns INTEGER NOT NULL,
PRIMARY KEY (character_id, program_id)
);
+CREATE TABLE IF NOT EXISTS npc_populations (
+ playfield INTEGER PRIMARY KEY
+);
+CREATE INDEX IF NOT EXISTS character_playfields ON characters(playfield);
CREATE TABLE IF NOT EXISTS npcs (
id INTEGER PRIMARY KEY REFERENCES characters(id) ON DELETE CASCADE CHECK (id >= 1000000),
definition TEXT NOT NULL,
diff --git a/server/world_admin.go b/server/world_admin.go
@@ -44,7 +44,7 @@ func (server *server) adminPlayers() ([]mapPlayer, error) {
players := make(map[uint32]mapPlayer)
for _, owner := range snapshot.zones {
query := &zoneAdminPlayers{}
- if err := owner.call(query); err != nil {
+ if err := owner.observe(query); err != nil {
return nil, err
}
for _, player := range query.players {
@@ -74,5 +74,8 @@ func (counts *zoneAdminCounts) execute(state *server) error {
counts.connected++
}
}
+ if state.populationDormant() {
+ return state.visitDormantNPCs(func(_ uint32, _ string, _ [3]float32, _ bool) { counts.npcs++ })
+ }
return nil
}
diff --git a/server/world_directory.go b/server/world_directory.go
@@ -229,6 +229,7 @@ func (directory *worldDirectory) createMission(creation missionCreation) {
return
}
state := creation.state
+ state.populationLoaded = true
state.gameSeconds, state.clockStarted = directory.environment.gameSeconds, directory.environment.clockStarted
state.weather, state.weatherUntil = directory.environment.weather, directory.environment.weatherUntil
state.world = directory.world
diff --git a/server/world_environment.go b/server/world_environment.go
@@ -34,7 +34,7 @@ func (world *worldRuntime) publishEnvironment(change environmentChange) error {
update := worldEnvironmentUpdate{change, make(chan []*zoneRuntime, 1)}
world.environment <- update
for _, owner := range <-update.reply {
- if err := owner.call(change); err != nil {
+ if err := owner.observe(change); err != nil {
return err
}
}
diff --git a/server/world_partition.go b/server/world_partition.go
@@ -9,6 +9,7 @@ func (source *server) partitionWorld() (map[uint32]*server, error) {
zone := func(playfield uint32) *server {
if states[playfield] == nil {
state := source.emptyZone()
+ state.populationLoaded = source.populationLoaded
state.savedNPCs = make(map[uint32]savedNPC)
state.activeNPCs = make(map[uint32]bool)
state.simulatedNPCs = make(map[uint32]*character)
@@ -17,6 +18,12 @@ func (source *server) partitionWorld() (map[uint32]*server, error) {
}
return states[playfield]
}
+ for playfield := range source.populations {
+ zone(playfield)
+ }
+ for _, playfield := range source.npcOwners {
+ zone(playfield)
+ }
for id, actor := range source.characters {
zone(actor.playfield).characters[id] = actor
}
@@ -104,10 +111,11 @@ func (source *server) partitionWorld() (map[uint32]*server, error) {
switch {
case owner != 0:
actor := source.characters[owner]
- if actor == nil {
+ if actor != nil {
+ playfield = actor.playfield
+ } else if playfield = source.npcOwners[owner]; playfield == 0 {
return nil, fmt.Errorf("item %d has no character owner %d", id, owner)
}
- playfield = actor.playfield
case root.Mission != 0:
var exists bool
playfield, exists = missions[root.Mission]
@@ -138,6 +146,7 @@ func (source *server) partitionWorld() (map[uint32]*server, error) {
func (source *server) relinquishWorld() {
source.characters, source.clients, source.fighting = nil, nil, nil
+ source.npcOwners = nil
source.items, source.itemPlacements, source.worldItems = nil, nil, nil
source.savedNPCs, source.activeNPCs, source.depletedResources = nil, nil, nil
source.mobileNPCs, source.simulatedNPCs, source.npcCells, source.npcLocations = nil, nil, nil, nil
diff --git a/server/world_runtime.go b/server/world_runtime.go
@@ -50,6 +50,11 @@ type worldTransfer struct {
func newWorldRuntime(configuration *server, states map[uint32]*server) (*worldRuntime, error) {
// Validate the complete initial ownership graph before starting any workers.
owners := make(map[uint32]uint32)
+ if configuration.populationDormant() {
+ for id, playfield := range configuration.npcOwners {
+ owners[id] = playfield
+ }
+ }
presence := make(map[uint32]playerPresence)
teams := make(map[uint32]*playerTeam)
chatPeople := make(map[uint32]*chatPerson)
@@ -61,7 +66,7 @@ func newWorldRuntime(configuration *server, states map[uint32]*server) (*worldRu
if character.playfield != playfield {
return nil, fmt.Errorf("character %d belongs to playfield %d, not %d", id, character.playfield, playfield)
}
- if _, exists := owners[id]; exists {
+ if previous, exists := owners[id]; exists && previous != playfield {
return nil, fmt.Errorf("character %d has multiple zone owners", id)
}
owners[id] = playfield
diff --git a/server/world_services.go b/server/world_services.go
@@ -8,6 +8,7 @@ import (
// Shared service handles and immutable content contain no live simulation state.
// The directory uses these dependencies to construct independent zone owners.
type worldServices struct {
+ populations map[uint32]npcPopulation
db *sql.DB
databaseWriter *databaseWriter
teamService *teamDirectory
diff --git a/server/world_store.go b/server/world_store.go
@@ -278,21 +278,21 @@ func (write npcWrite) persist(tx *sql.Tx) error {
return nil
}
-func (server *server) loadNPCs() (bool, error) {
- var initialized bool
+func (server *server) loadWorldClock() error {
var started string
- if err := server.db.QueryRow("SELECT npcs_initialized, last_item_id, last_character_id, last_npc_id, game_seconds, clock_started FROM world WHERE id = 1").Scan(
- &initialized, &server.nextItem, &server.nextCharacter, &server.nextNPC, &server.gameSeconds, &started); err != nil {
- return false, err
+ if err := server.db.QueryRow("SELECT last_item_id, last_character_id, last_npc_id, game_seconds, clock_started FROM world WHERE id = 1").Scan(
+ &server.nextItem, &server.nextCharacter, &server.nextNPC, &server.gameSeconds, &started); err != nil {
+ return err
}
var err error
server.clockStarted, err = time.Parse(time.RFC3339Nano, started)
- if err != nil || !initialized {
- return initialized, err
- }
- rows, err := server.db.Query("SELECT id, " + characterColumns + ", " + npcColumns + " FROM characters JOIN npcs USING(id)")
+ return err
+}
+
+func (server *server) restoreNPCs() error {
+ rows, err := server.db.Query("SELECT id, "+characterColumns+", "+npcColumns+" FROM characters JOIN npcs USING(id) WHERE playfield=?", server.playfield)
if err != nil {
- return false, err
+ return err
}
server.savedNPCs = make(map[uint32]savedNPC)
characters := make(map[uint32]*character)
@@ -301,7 +301,7 @@ func (server *server) loadNPCs() (bool, error) {
fields := append([]any{&state.Character.Profile.ID}, state.Character.fields()...)
if err := rows.Scan(append(fields, state.fields()...)...); err != nil {
rows.Close()
- return false, err
+ return err
}
npc := state.Character.character()
npc.npc, npc.npcDefinitionID = true, state.Definition
@@ -343,21 +343,21 @@ func (server *server) loadNPCs() (bool, error) {
}
if err := rows.Err(); err != nil {
rows.Close()
- return false, err
+ return err
}
rows.Close()
// Contribution rows include hidden respawn sources as well as visible NPCs.
- rows, err = server.db.Query("SELECT npc_id, player_id, team_id, damage FROM npc_damage_contributors")
+ rows, err = server.db.Query("SELECT npc_id, player_id, team_id, damage FROM npc_damage_contributors JOIN characters ON characters.id=npc_id WHERE playfield=?", server.playfield)
if err != nil {
- return false, err
+ return err
}
defer rows.Close()
for rows.Next() {
var id, damage uint32
var contributor damageContributor
if err := rows.Scan(&id, &contributor.player, &contributor.team, &damage); err != nil {
- return false, err
+ return err
}
if characters[id].damageContributors == nil {
characters[id].damageContributors = make(map[damageContributor]uint32)
@@ -370,7 +370,7 @@ func (server *server) loadNPCs() (bool, error) {
saved.Contributors[contributor] = damage
server.savedNPCs[id] = saved
}
- return true, rows.Err()
+ return rows.Err()
}
func (server *server) flushWorld() error {
diff --git a/server/zone_checkpoint.go b/server/zone_checkpoint.go
@@ -36,6 +36,9 @@ func (zone *zoneRuntime) finishCheckpoint(state *server, err error) {
// every remaining actor at the current time, regardless of its periodic deadline.
// Inventory and rewards are already durable; do not rewrite them on shutdown.
func (zone *zoneRuntime) finalCheckpoint(state *server, now time.Time) error {
+ if state.populationDormant() {
+ return nil
+ }
checkpoint := state.prepareFinalCheckpoint(now)
if checkpoint.changed() {
if err := state.databaseWriter.commit(checkpoint); err != nil {
diff --git a/server/zone_http.go b/server/zone_http.go
@@ -76,7 +76,12 @@ func (state *server) servePlayerHTTP(w http.ResponseWriter, r *http.Request, pla
http.NotFound(w, r)
return
}
- err = route.zone.call(zonePlayerHTTP{player, r, response, handle})
+ command := zonePlayerHTTP{player, r, response, handle}
+ if r.Method == http.MethodGet && player < 1000000 {
+ err = route.zone.observe(command)
+ } else {
+ err = route.zone.call(command)
+ }
// Retry only a pre-execution ownership change. A handler that ran must
// never repeat its mutation, even if it transferred the player onward.
if err == errZoneOwnerChanged {
diff --git a/server/zone_population.go b/server/zone_population.go
@@ -0,0 +1,207 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "cmp"
+ "database/sql"
+ "fmt"
+ "maps"
+ "slices"
+ "time"
+)
+
+// Reserve source identities without allocating actors or checkpoint copies.
+func (state *server) preparePopulations() error {
+ if err := state.loadWorldClock(); err != nil {
+ return err
+ }
+ var err error
+ if state.populations == nil {
+ state.populations, err = readPopulations()
+ if err != nil {
+ return err
+ }
+ }
+ state.npcOwners = make(map[uint32]uint32)
+ for playfield, population := range state.populations {
+ state.nextNPC = max(state.nextNPC, population.end)
+ population.visit(func(id uint32, _ *gamedata.NPCGroup, _ int, _ [3]float32) {
+ state.npcOwners[id] = playfield
+ })
+ }
+ if _, err := state.db.Exec("UPDATE world SET last_npc_id=?1 WHERE id=1 AND last_npc_id<?1", state.nextNPC); err != nil {
+ return err
+ }
+ rows, err := state.db.Query("SELECT id, playfield FROM characters JOIN npcs USING(id)")
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id, playfield uint32
+ if err := rows.Scan(&id, &playfield); err != nil {
+ return err
+ }
+ state.npcOwners[id] = playfield
+ }
+ return rows.Err()
+}
+
+func (state *server) populationDormant() bool {
+ return state.populations != nil && !state.populationLoaded
+}
+
+type populationWrite uint32
+
+func (playfield populationWrite) persist(tx *sql.Tx) error {
+ _, err := tx.Exec("INSERT INTO npc_populations(playfield) VALUES (?)", uint32(playfield))
+ return err
+}
+
+func (state *server) populationSaved() (bool, error) {
+ var saved bool
+ err := state.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM npc_populations WHERE playfield=?1)
+ OR EXISTS(SELECT 1 FROM characters JOIN npcs USING(id) WHERE playfield=?1)`, state.playfield).Scan(&saved)
+ return saved, err
+}
+
+// Activation runs on the zone owner. Failed reads or writes discard the draft,
+// so retries cannot publish half a population or overwrite committed health.
+func (state *server) activatePopulation() error {
+ if !state.populationDormant() {
+ return nil
+ }
+ saved, err := state.populationSaved()
+ if err != nil {
+ return err
+ }
+ draft := state.emptyZone()
+ draft.playfield = state.playfield
+ if saved {
+ if err := draft.restoreNPCs(); err != nil {
+ return err
+ }
+ if err := draft.restoreNPCNanos(); err != nil {
+ return err
+ }
+ if err := draft.loadPets(); err != nil {
+ return err
+ }
+ } else {
+ if population, exists := state.populations[state.playfield]; exists {
+ spawns := population.spawns()
+ draft.placeFallbackNPCs(spawns)
+ for _, npc := range spawns {
+ draft.addNPC(npc)
+ if npc.motion != nil {
+ draft.mobileNPCs[npc.playfield] = append(draft.mobileNPCs[npc.playfield], npc)
+ }
+ }
+ }
+ write := draft.prepareNPCWrite(itemStore{flush: true}, nil)
+ if err := state.commitWrite(databaseBatch{write, populationWrite(state.playfield)}); err != nil {
+ return err
+ }
+ draft.applyNPCCheckpoint(write.checkpoint)
+ }
+
+ // Item instances stay with their zone; restored corpses reconnect to them.
+ for id, placement := range state.itemPlacements {
+ if placement.Corpse == 0 {
+ continue
+ }
+ npc := draft.characters[placement.Corpse]
+ if npc == nil || npc.corpse == nil {
+ return fmt.Errorf("item %d has no restored corpse %d", id, placement.Corpse)
+ }
+ record := state.items[id]
+ npc.corpse.items = append(npc.corpse.items, ownedItem{ID: id, Type: record.Type, Template: record.Template,
+ Quality: record.Quality, Count: record.Count, Ammo: record.Ammo, Slot: placement.Slot})
+ }
+ for _, npc := range draft.characters {
+ if npc.corpse != nil {
+ slices.SortFunc(npc.corpse.items, func(a, b ownedItem) int { return cmp.Compare(a.Slot, b.Slot) })
+ }
+ }
+ maps.Copy(state.characters, draft.characters)
+ state.savedNPCs, state.activeNPCs = draft.savedNPCs, nil
+ state.mobileNPCs = draft.mobileNPCs
+ state.npcCells, state.npcLocations = draft.npcCells, draft.npcLocations
+ state.npcRespawns, state.corpseExpiry, state.petExpiry = draft.npcRespawns, draft.corpseExpiry, draft.petExpiry
+ state.simulatedNPCs = nil
+ state.navigationStopped = false
+ state.lastNPCUpdate = time.Time{}
+ state.populationLoaded = true
+ return nil
+}
+
+// The owner checkpoints before releasing actors. Routing and offline player
+// records remain available; subsequent gameplay reloads the committed NPC state.
+func (zone *zoneRuntime) hibernate(state *server, now time.Time) (bool, error) {
+ if !state.populationLoaded || state.populations == nil || len(state.clients) != 0 || now.Sub(zone.lastOccupied) < 5*time.Minute || zone.checkpointDone != nil {
+ return false, nil
+ }
+ // Pets can notify remote owners, and active effects must finish their ticks.
+ if len(state.petExpiry) != 0 {
+ return false, nil
+ }
+ for _, actor := range state.characters {
+ if actor.npc && len(actor.activeNanos) != 0 {
+ return false, nil
+ }
+ }
+ if err := zone.finalCheckpoint(state, now); err != nil {
+ return false, err
+ }
+ state.stopNavigation()
+ for id, actor := range state.characters {
+ if actor.npc {
+ delete(state.characters, id)
+ }
+ }
+ state.savedNPCs, state.activeNPCs = nil, nil
+ state.mobileNPCs = make(map[uint32][]*character)
+ state.npcCells, state.npcLocations, state.simulatedNPCs = nil, nil, nil
+ state.npcRespawns, state.corpseExpiry, state.petExpiry = nil, nil, nil
+ clear(state.fighting)
+ clear(zone.incomingAttacks)
+ state.populationLoaded = false
+ return true, nil
+}
+
+// Catalog previews and committed positions remain inspectable without actors.
+func (state *server) visitDormantNPCs(visit func(uint32, string, [3]float32, bool)) error {
+ saved, err := state.populationSaved()
+ if err != nil {
+ return err
+ }
+ if !saved {
+ if population, exists := state.populations[state.playfield]; exists {
+ population.visit(func(id uint32, group *gamedata.NPCGroup, _ int, position [3]float32) {
+ visit(id, group.Name, position, true)
+ })
+ }
+ return nil
+ }
+ rows, err := state.db.Query(`SELECT id, name, position_x, position_y, position_z, health>0
+ FROM characters JOIN npcs USING(id) WHERE playfield=? AND present`, state.playfield)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id uint32
+ var name string
+ var position [3]float32
+ var alive bool
+ if err := rows.Scan(&id, &name, &position[0], &position[1], &position[2], &alive); err != nil {
+ return err
+ }
+ visit(id, name, position, alive)
+ }
+ return rows.Err()
+}
+
+type zoneActivatePopulation struct{}
+
+func (zoneActivatePopulation) execute(*server) error { return nil }
diff --git a/server/zone_population_test.go b/server/zone_population_test.go
@@ -0,0 +1,368 @@
+package main
+
+import (
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+type populationObservation struct {
+ loaded bool
+ npcs int
+ health uint32
+}
+
+func (query *populationObservation) execute(state *server) error {
+ query.loaded = state.populationLoaded
+ query.npcs, query.health = 0, 0
+ for _, actor := range state.characters {
+ if actor.npc {
+ query.npcs++
+ query.health = actor.health
+ }
+ }
+ return nil
+}
+
+type populationDamage struct{}
+
+func (populationDamage) execute(state *server) error {
+ state.characters[1000000].health = 17
+ return nil
+}
+
+type populationIdle struct {
+ elapsed time.Duration
+ slept bool
+}
+
+func (command *populationIdle) execute(state *server) error {
+ var err error
+ command.slept, err = state.zone.hibernate(state, state.zone.lastOccupied.Add(command.elapsed))
+ return err
+}
+
+func TestDormantPopulationAdminViewsDoNotActivateNPCs(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newDormantServerForTest(t)
+ startTestService(t, world)
+ response := httptest.NewRecorder()
+ world.controlPage(response, httptest.NewRequest("GET", "/admin", nil))
+ if response.Code != 200 || !strings.Contains(response.Body.String(), "NPCs<strong>1</strong>") {
+ t.Fatal("missing dormant catalog count", response.Code)
+ }
+ response = httptest.NewRecorder()
+ world.mapEntities(response, httptest.NewRequest("GET", "/admin/map/entities?view=950&npcs=1&left=0&bottom=0&right=100&top=100", nil))
+ if response.Code != 200 || !strings.Contains(response.Body.String(), "Edited NPC") {
+ t.Fatal("missing dormant NPC marker", response.Code, response.Body.String())
+ }
+ owner, err := world.world.owner(1000000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := &populationObservation{}
+ if err := owner.observe(query); err != nil {
+ t.Fatal(err)
+ }
+ var persisted int
+ if err := world.db.QueryRow("SELECT COUNT(*) FROM npcs").Scan(&persisted); err != nil {
+ t.Fatal(err)
+ }
+ if query.loaded || query.npcs != 0 || persisted != 0 {
+ t.Fatal("admin inspection activated population", query, persisted)
+ }
+}
+
+func TestDormantPopulationConcurrentActivationAndIdleRecovery(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newDormantServerForTest(t)
+ shutdown := startTestService(t, world)
+ owner, err := world.world.owner(1000000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var callers sync.WaitGroup
+ for range 12 {
+ callers.Go(func() {
+ query := &populationObservation{}
+ if err := owner.call(query); err != nil {
+ t.Error(err)
+ } else if !query.loaded || query.npcs != 1 {
+ t.Error("incomplete activation", query)
+ }
+ })
+ }
+ callers.Wait()
+ if err := owner.call(populationDamage{}); err != nil {
+ t.Fatal(err)
+ }
+ before := &populationIdle{elapsed: 5*time.Minute - time.Nanosecond}
+ if err := owner.observe(before); err != nil || before.slept {
+ t.Fatal("slept before grace period", err)
+ }
+ idle := &populationIdle{elapsed: 5 * time.Minute}
+ if err := owner.observe(idle); err != nil || !idle.slept {
+ t.Fatal("did not hibernate", err)
+ }
+ query := &populationObservation{}
+ if err := owner.observe(query); err != nil {
+ t.Fatal(err)
+ }
+ if query.loaded || query.npcs != 0 {
+ t.Fatal("hibernation retained actors", query)
+ }
+ if err := owner.call(query); err != nil {
+ t.Fatal(err)
+ }
+ if !query.loaded || query.npcs != 1 || query.health != 17 {
+ t.Fatal("wake lost checkpoint", query)
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+
+ cold := newDormantServerForTest(t)
+ startTestService(t, cold)
+ owner, err = cold.world.owner(1000000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query = &populationObservation{}
+ if err := owner.observe(query); err != nil || query.loaded {
+ t.Fatal("cold startup materialized population", err, query)
+ }
+ if err := owner.call(query); err != nil {
+ t.Fatal(err)
+ }
+ if query.npcs != 1 || query.health != 17 {
+ t.Fatal("cold activation lost damage", query)
+ }
+}
+
+func TestDormantPopulationFailedCheckpointKeepsLiveState(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newDormantServerForTest(t)
+ startTestService(t, world)
+ owner, err := world.world.owner(1000000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := owner.call(populationDamage{}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER reject_idle BEFORE UPDATE ON characters BEGIN SELECT RAISE(ABORT, 'checkpoint'); END"); err != nil {
+ t.Fatal(err)
+ }
+ idle := &populationIdle{elapsed: 5 * time.Minute}
+ if err := owner.observe(idle); err == nil || idle.slept {
+ t.Fatal("failed checkpoint discarded live state", err)
+ }
+ query := &populationObservation{}
+ if err := owner.observe(query); err != nil {
+ t.Fatal(err)
+ }
+ if !query.loaded || query.npcs != 1 || query.health != 17 {
+ t.Fatal("failed hibernation lost actor", query)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_idle"); err != nil {
+ t.Fatal(err)
+ }
+ if err := owner.observe(idle); err != nil || !idle.slept {
+ t.Fatal("checkpoint retry failed", err)
+ }
+}
+
+func TestDormantPopulationActivationFailureDoesNotBlockOtherZone(t *testing.T) {
+ data := testNPCData()
+ other := data.Playfields[0]
+ other.ID = 800
+ other.Districts = slices.Clone(other.Districts)
+ other.Districts[0].Groups = slices.Clone(other.Districts[0].Groups)
+ other.Districts[0].Groups[0].ID = "test/other"
+ data.Playfields = append(data.Playfields, other)
+ useNPCData(t, data)
+ world := newDormantServerForTest(t)
+ startTestService(t, world)
+ first, err := world.world.owner(1000000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := world.world.owner(1000001)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER reject_population BEFORE INSERT ON npcs WHEN NEW.id=1000000 BEGIN SELECT RAISE(ABORT, 'population'); END"); err != nil {
+ t.Fatal(err)
+ }
+ if err := first.call(zoneActivatePopulation{}); err == nil {
+ t.Fatal("activation failure was hidden")
+ }
+ query := &populationObservation{}
+ if err := first.observe(query); err != nil || query.loaded || query.npcs != 0 {
+ t.Fatal("failed activation published actors", err, query)
+ }
+ if err := second.call(query); err != nil || query.npcs != 1 {
+ t.Fatal("other zone could not activate", err, query)
+ }
+ var populations, npcs int
+ if err := world.db.QueryRow("SELECT COUNT(*) FROM npc_populations").Scan(&populations); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT COUNT(*) FROM npcs").Scan(&npcs); err != nil {
+ t.Fatal(err)
+ }
+ if populations != 1 || npcs != 1 {
+ t.Fatal("failed activation partially committed", populations, npcs)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_population"); err != nil {
+ t.Fatal(err)
+ }
+ if err := first.call(query); err != nil || query.npcs != 1 {
+ t.Fatal("activation retry failed", err, query)
+ }
+}
+
+type populationExpiredCorpse struct{}
+
+func (populationExpiredCorpse) execute(state *server) error {
+ npc := state.characters[1000000]
+ npc.health = 0
+ npc.corpse = &npcCorpse{expiresAt: time.Now().Add(-time.Minute)}
+ state.corpseExpiry = append(state.corpseExpiry, npc)
+ state.npcRespawns = append(state.npcRespawns, npcRespawn{npc: npc, at: time.Now().Add(-time.Second)})
+ return nil
+}
+
+func TestDormantPopulationWakeProcessesElapsedCorpseAndRespawn(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newDormantServerForTest(t)
+ startTestService(t, world)
+ owner, err := world.world.owner(1000000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := owner.call(populationExpiredCorpse{}); err != nil {
+ t.Fatal(err)
+ }
+ idle := &populationIdle{elapsed: 5 * time.Minute}
+ if err := owner.observe(idle); err != nil || !idle.slept {
+ t.Fatal("did not checkpoint expiry deadlines", err)
+ }
+ query := &populationObservation{}
+ if err := owner.call(query); err != nil {
+ t.Fatal(err)
+ }
+ if query.npcs != 1 || query.health == 0 {
+ t.Fatal("elapsed deadlines did not produce one live replacement", query)
+ }
+ var id uint32
+ if err := world.db.QueryRow("SELECT id FROM npcs WHERE present").Scan(&id); err != nil || id != 1000001 {
+ t.Fatal("respawn was not committed with a new identity", id, err)
+ }
+}
+
+func TestDormantPopulationGraceStartsAfterLastDeparture(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newDormantServerForTest(t)
+ player := world.newCharacter()
+ if err := world.saveUser(player); err != nil {
+ t.Fatal(err)
+ }
+ startTestService(t, world)
+ owner, err := world.world.owner(player.id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ client := &worldClient{id: player.id, conn: &combatTestConn{}}
+ if err := owner.joinWorldClient(client, player.id); err != nil {
+ t.Fatal(err)
+ }
+ idle := &populationIdle{elapsed: 10 * time.Minute}
+ if err := owner.observe(idle); err != nil || idle.slept {
+ t.Fatal("zone slept with a connected player", err)
+ }
+ owner.leaveWorldClient(client)
+ idle.elapsed = 5*time.Minute - time.Nanosecond
+ if err := owner.observe(idle); err != nil || idle.slept {
+ t.Fatal("departure lost the grace period", err)
+ }
+ idle.elapsed = 5 * time.Minute
+ if err := owner.observe(idle); err != nil || !idle.slept {
+ t.Fatal("empty zone did not hibernate", err)
+ }
+}
+
+func TestDormantPopulationRestartsPetWorkWithoutLocalPlayer(t *testing.T) {
+ useNPCData(t, testNPCData())
+ fixture, _ := newPetSummonWorld(t)
+ if err := (zoneSummonPet{}).execute(fixture); err != nil {
+ t.Fatal(err)
+ }
+ fixture.characters[1].playfield = 800
+ if err := fixture.savePosition(fixture.characters[1]); err != nil {
+ t.Fatal(err)
+ }
+ if err := fixture.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ world := newDormantServerForTest(t)
+ startTestService(t, world)
+ petZone, err := world.world.owner(1000001)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := &populationObservation{}
+ if err := petZone.observe(query); err != nil || !query.loaded || query.npcs != 2 {
+ t.Fatal("remote pet work did not resume", err, query)
+ }
+ idle := &populationIdle{elapsed: 10 * time.Minute}
+ if err := petZone.observe(idle); err != nil || idle.slept {
+ t.Fatal("zone suspended a live pet", err)
+ }
+ playerZone, err := world.world.owner(1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := playerZone.observe(query); err != nil || query.loaded {
+ t.Fatal("offline owner unnecessarily activated its zone", err, query)
+ }
+}
+
+func TestDormantPopulationRestoresEffectWithRemoteCaster(t *testing.T) {
+ useNPCData(t, testNPCData())
+ fixture, _ := newPeriodicNanoWorld(t)
+ at := castPeriodicNano(t, fixture, 43376)
+ fixture.characters[1].playfield = 800
+ if err := fixture.savePosition(fixture.characters[1]); err != nil {
+ t.Fatal(err)
+ }
+ if err := fixture.checkpointWorld(at.Add(time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ world := newDormantServerForTest(t)
+ startTestService(t, world)
+ owner, err := world.world.owner(1000000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := owner.observe(zoneTestCommand(func(state *server) error {
+ if !state.populationLoaded || state.characters[1000000] == nil {
+ t.Error("pending NPC effect did not resume its zone")
+ return nil
+ }
+ effects := state.characters[1000000].activeNanos
+ if len(effects) != 1 || effects[0].caster != 1 || effects[0].ticksLeft != 8 {
+ t.Error("pending effect lost its remote caster or ticks", effects)
+ }
+ return nil
+ })); err != nil {
+ t.Fatal(err)
+ }
+ idle := &populationIdle{elapsed: 10 * time.Minute}
+ if err := owner.observe(idle); err != nil || idle.slept {
+ t.Fatal("zone suspended pending NPC effects", err)
+ }
+}
diff --git a/server/zone_runtime.go b/server/zone_runtime.go
@@ -10,6 +10,7 @@ import (
// A zone receives commands and advances its own state on one goroutine. The
// caller transfers the state at construction and must subsequently use commands.
type zoneRuntime struct {
+ lastOccupied time.Time
commands chan zoneRequest
quiescing chan struct{}
quiesced chan struct{}
@@ -29,6 +30,7 @@ type zoneCommand interface {
}
type zoneRequest struct {
+ observe bool
command zoneCommand
done chan error
}
@@ -65,22 +67,32 @@ func newZoneRuntime(state *server) *zoneRuntime {
func (zone *zoneRuntime) run(state *server) {
defer close(zone.done)
- movement := time.NewTicker(time.Second / 60)
- actions := time.NewTicker(250 * time.Millisecond)
- crossings := time.NewTicker(100 * time.Millisecond)
- checkpoints := time.NewTicker(time.Second)
- defer movement.Stop()
- defer actions.Stop()
- defer crossings.Stop()
- defer checkpoints.Stop()
- movementTicks, actionTicks, crossingTicks, checkpointTicks := movement.C, actions.C, crossings.C, checkpoints.C
+ var movement, actions, crossings, checkpoints *time.Ticker
+ var movementTicks, actionTicks, crossingTicks, checkpointTicks <-chan time.Time
+ startTicks := func() {
+ movement = time.NewTicker(time.Second / 60)
+ actions = time.NewTicker(250 * time.Millisecond)
+ crossings = time.NewTicker(100 * time.Millisecond)
+ checkpoints = time.NewTicker(time.Second)
+ movementTicks, actionTicks, crossingTicks, checkpointTicks = movement.C, actions.C, crossings.C, checkpoints.C
+ zone.lastOccupied = time.Now()
+ }
+ pauseTicks := func() {
+ if movement != nil {
+ movement.Stop()
+ actions.Stop()
+ crossings.Stop()
+ checkpoints.Stop()
+ }
+ movementTicks, actionTicks, crossingTicks, checkpointTicks = nil, nil, nil, nil
+ }
+ defer pauseTicks()
+ if !state.populationDormant() {
+ startTicks()
+ }
quiescing := zone.quiescing
stopTicks := func() {
- movement.Stop()
- actions.Stop()
- crossings.Stop()
- checkpoints.Stop()
- movementTicks, actionTicks, crossingTicks, checkpointTicks = nil, nil, nil, nil
+ pauseTicks()
quiescing = nil
close(zone.quiesced)
}
@@ -88,11 +100,30 @@ func (zone *zoneRuntime) run(state *server) {
for {
select {
case request := <-zone.commands:
+ if !request.observe && state.populationDormant() {
+ if err := state.activatePopulation(); err != nil {
+ request.done <- err
+ continue
+ }
+ if quiescing != nil {
+ startTicks()
+ }
+ state.expirePets(time.Now(), nil)
+ state.advanceCorpseExpiry(time.Now())
+ state.advanceNPCRespawns(time.Now())
+ }
if packet, ok := request.command.(zonePacket); ok && state.world != nil && missionLifecyclePacket(packet.body) {
state.world.missionOperations <- missionOperation{zone: zone, packet: packet, done: request.done}
continue
}
+ occupied := len(state.clients) != 0
err := request.command.execute(state)
+ if occupied || len(state.clients) != 0 {
+ zone.lastOccupied = time.Now()
+ }
+ if state.populationDormant() {
+ pauseTicks()
+ }
if state.retiredMission != nil && quiescing != nil {
stopTicks()
}
@@ -114,7 +145,15 @@ func (zone *zoneRuntime) run(state *server) {
zone.publishPresence(state)
case now := <-checkpointTicks:
started := time.Now()
- zone.startCheckpoint(state, now)
+ asleep, err := zone.hibernate(state, now)
+ if err != nil {
+ log.Printf("Zone %d hibernation: %v", state.playfield, err)
+ }
+ if asleep {
+ pauseTicks()
+ } else if !state.populationDormant() {
+ zone.startCheckpoint(state, now)
+ }
reportSimulationTick(state.playfield, "checkpoint", now, started)
case err := <-zone.checkpointDone:
zone.finishCheckpoint(state, err)
@@ -139,7 +178,16 @@ func (zone *zoneRuntime) quiesce() {
}
func (zone *zoneRuntime) call(command zoneCommand) error {
- request := zoneRequest{command: command, done: make(chan error, 1)}
+ return zone.request(zoneRequest{command: command})
+}
+
+// Observations and environment defaults do not wake a dormant population.
+func (zone *zoneRuntime) observe(command zoneCommand) error {
+ return zone.request(zoneRequest{command: command, observe: true})
+}
+
+func (zone *zoneRuntime) request(request zoneRequest) error {
+ request.done = make(chan error, 1)
select {
case zone.commands <- request:
return <-request.done