aorecomp

Anarchy Online classic in the browser

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


server/zone_population.go (6451B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"cmp"
      6 	"database/sql"
      7 	"fmt"
      8 	"maps"
      9 	"slices"
     10 	"time"
     11 )
     12 
     13 // Reserve source identities without allocating actors or checkpoint copies.
     14 func (state *server) preparePopulations() error {
     15 	if err := state.loadWorldClock(); err != nil {
     16 		return err
     17 	}
     18 	var err error
     19 	if state.populations == nil {
     20 		state.populations, err = readPopulations()
     21 		if err != nil {
     22 			return err
     23 		}
     24 	}
     25 	state.npcOwners = make(map[uint32]uint32)
     26 	for playfield, population := range state.populations {
     27 		state.nextNPC = max(state.nextNPC, population.end)
     28 		population.visit(func(id uint32, _ *gamedata.NPCGroup, _ int, _ [3]float32) {
     29 			state.npcOwners[id] = playfield
     30 		})
     31 	}
     32 	if _, err := state.db.Exec("UPDATE world SET last_npc_id=?1 WHERE id=1 AND last_npc_id<?1", state.nextNPC); err != nil {
     33 		return err
     34 	}
     35 	rows, err := state.db.Query("SELECT id, playfield FROM characters JOIN npcs USING(id)")
     36 	if err != nil {
     37 		return err
     38 	}
     39 	defer rows.Close()
     40 	for rows.Next() {
     41 		var id, playfield uint32
     42 		if err := rows.Scan(&id, &playfield); err != nil {
     43 			return err
     44 		}
     45 		state.npcOwners[id] = playfield
     46 	}
     47 	return rows.Err()
     48 }
     49 
     50 func (state *server) populationDormant() bool {
     51 	return state.populations != nil && !state.populationLoaded
     52 }
     53 
     54 type populationWrite uint32
     55 
     56 func (playfield populationWrite) persist(tx *sql.Tx) error {
     57 	_, err := tx.Exec("INSERT INTO npc_populations(playfield) VALUES (?)", uint32(playfield))
     58 	return err
     59 }
     60 
     61 func (state *server) populationSaved() (bool, error) {
     62 	var saved bool
     63 	err := state.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM npc_populations WHERE playfield=?1)
     64 		OR EXISTS(SELECT 1 FROM characters JOIN npcs USING(id) WHERE playfield=?1)`, state.playfield).Scan(&saved)
     65 	return saved, err
     66 }
     67 
     68 // Activation runs on the zone owner. Failed reads or writes discard the draft,
     69 // so retries cannot publish half a population or overwrite committed health.
     70 func (state *server) activatePopulation() error {
     71 	if !state.populationDormant() {
     72 		return nil
     73 	}
     74 	saved, err := state.populationSaved()
     75 	if err != nil {
     76 		return err
     77 	}
     78 	draft := state.emptyZone()
     79 	draft.playfield = state.playfield
     80 	if saved {
     81 		if err := draft.restoreNPCs(); err != nil {
     82 			return err
     83 		}
     84 		if err := draft.restoreNPCNanos(); err != nil {
     85 			return err
     86 		}
     87 		if err := draft.loadPets(); err != nil {
     88 			return err
     89 		}
     90 	} else {
     91 		if population, exists := state.populations[state.playfield]; exists {
     92 			spawns := population.spawns()
     93 			draft.placeFallbackNPCs(spawns)
     94 			for _, npc := range spawns {
     95 				draft.addNPC(npc)
     96 				if npc.motion != nil {
     97 					draft.mobileNPCs[npc.playfield] = append(draft.mobileNPCs[npc.playfield], npc)
     98 				}
     99 			}
    100 		}
    101 		write := draft.prepareNPCWrite(itemStore{flush: true}, nil)
    102 		if err := state.commitWrite(databaseBatch{write, populationWrite(state.playfield)}); err != nil {
    103 			return err
    104 		}
    105 		draft.applyNPCCheckpoint(write.checkpoint)
    106 	}
    107 
    108 	// Item instances stay with their zone; restored corpses reconnect to them.
    109 	for id, placement := range state.itemPlacements {
    110 		if placement.Corpse == 0 {
    111 			continue
    112 		}
    113 		npc := draft.characters[placement.Corpse]
    114 		if npc == nil || npc.corpse == nil {
    115 			return fmt.Errorf("item %d has no restored corpse %d", id, placement.Corpse)
    116 		}
    117 		record := state.items[id]
    118 		npc.corpse.items = append(npc.corpse.items, ownedItem{ID: id, Type: record.Type, Template: record.Template,
    119 			Quality: record.Quality, Count: record.Count, Ammo: record.Ammo, Slot: placement.Slot})
    120 	}
    121 	for _, npc := range draft.characters {
    122 		if npc.corpse != nil {
    123 			slices.SortFunc(npc.corpse.items, func(a, b ownedItem) int { return cmp.Compare(a.Slot, b.Slot) })
    124 		}
    125 	}
    126 	maps.Copy(state.characters, draft.characters)
    127 	state.savedNPCs, state.activeNPCs = draft.savedNPCs, nil
    128 	state.mobileNPCs = draft.mobileNPCs
    129 	state.npcCells, state.npcLocations = draft.npcCells, draft.npcLocations
    130 	state.npcRespawns, state.corpseExpiry, state.petExpiry = draft.npcRespawns, draft.corpseExpiry, draft.petExpiry
    131 	state.simulatedNPCs = nil
    132 	state.navigationStopped = false
    133 	state.lastNPCUpdate = time.Time{}
    134 	state.populationLoaded = true
    135 	return nil
    136 }
    137 
    138 // The owner checkpoints before releasing actors. Routing and offline player
    139 // records remain available; subsequent gameplay reloads the committed NPC state.
    140 func (zone *zoneRuntime) hibernate(state *server, now time.Time) (bool, error) {
    141 	if !state.populationLoaded || state.populations == nil || len(state.clients) != 0 || now.Sub(zone.lastOccupied) < 5*time.Minute || zone.checkpointDone != nil {
    142 		return false, nil
    143 	}
    144 	// Pets can notify remote owners, and active effects must finish their ticks.
    145 	if len(state.petExpiry) != 0 {
    146 		return false, nil
    147 	}
    148 	for _, actor := range state.characters {
    149 		if actor.npc && len(actor.activeNanos) != 0 {
    150 			return false, nil
    151 		}
    152 	}
    153 	if err := zone.finalCheckpoint(state, now); err != nil {
    154 		return false, err
    155 	}
    156 	state.stopNavigation()
    157 	for id, actor := range state.characters {
    158 		if actor.npc {
    159 			delete(state.characters, id)
    160 		}
    161 	}
    162 	state.savedNPCs, state.activeNPCs = nil, nil
    163 	state.mobileNPCs = make(map[uint32][]*character)
    164 	state.npcCells, state.npcLocations, state.simulatedNPCs = nil, nil, nil
    165 	state.npcRespawns, state.corpseExpiry, state.petExpiry = nil, nil, nil
    166 	clear(state.fighting)
    167 	clear(zone.incomingAttacks)
    168 	state.populationLoaded = false
    169 	return true, nil
    170 }
    171 
    172 // Catalog previews and committed positions remain inspectable without actors.
    173 func (state *server) visitDormantNPCs(visit func(uint32, string, [3]float32, bool)) error {
    174 	saved, err := state.populationSaved()
    175 	if err != nil {
    176 		return err
    177 	}
    178 	if !saved {
    179 		if population, exists := state.populations[state.playfield]; exists {
    180 			population.visit(func(id uint32, group *gamedata.NPCGroup, _ int, position [3]float32) {
    181 				visit(id, group.Name, position, true)
    182 			})
    183 		}
    184 		return nil
    185 	}
    186 	rows, err := state.db.Query(`SELECT id, name, position_x, position_y, position_z, health>0
    187 		FROM characters JOIN npcs USING(id) WHERE playfield=? AND present`, state.playfield)
    188 	if err != nil {
    189 		return err
    190 	}
    191 	defer rows.Close()
    192 	for rows.Next() {
    193 		var id uint32
    194 		var name string
    195 		var position [3]float32
    196 		var alive bool
    197 		if err := rows.Scan(&id, &name, &position[0], &position[1], &position[2], &alive); err != nil {
    198 			return err
    199 		}
    200 		visit(id, name, position, alive)
    201 	}
    202 	return rows.Err()
    203 }
    204 
    205 type zoneActivatePopulation struct{}
    206 
    207 func (zoneActivatePopulation) execute(*server) error { return nil }