aorecomp

Anarchy Online classic in the browser

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


server/gamedata/load.go (14740B)


      1 package gamedata
      2 
      3 import (
      4 	"embed"
      5 	"fmt"
      6 	"io"
      7 	"io/fs"
      8 	"slices"
      9 	"sort"
     10 
     11 	"go.yaml.in/yaml/v3"
     12 )
     13 
     14 //go:embed *.yaml zones/*.yaml items/*.yaml
     15 var files embed.FS
     16 
     17 var (
     18 	NPCs               NPCData
     19 	NPCCombatProfiles  map[uint32]map[uint16]*NPCCombatProfile
     20 	LootPools          map[string]*LootPool
     21 	LootTables         map[string]*LootTable
     22 	NPCLootTables      = make(map[string]*LootTable)
     23 	ExperienceLevels   []uint32
     24 	NPCNames           NPCNameData
     25 	NPCGroups          = make(map[string]*NPCGroup)
     26 	PopulationSources  []*NPCPopulationSource
     27 	PopulationEvidence NPCExtractionEvidence
     28 	Monsters           []Monster
     29 	MonsterTemplates   = make(map[uint32]*Monster)
     30 	Items              ItemCatalog
     31 	ItemTemplates      = make(map[uint32]*Item)
     32 	ItemFamilies       = make(map[uint32][2]uint32)
     33 	NanoTemplates      = make(map[uint32]*Item)
     34 	MapCoordinates     MapCoordinateData
     35 	TerrainEvidence    TerrainExtractionEvidence
     36 	Playfields         map[uint32]Playfield
     37 	ShopMachines       map[uint32]ShopMachine
     38 	MissionBooths      map[uint32]MissionBooth
     39 	MissionTemplates   map[uint32]MissionTemplate
     40 	MissionLevels      map[uint16][11]uint16
     41 	ShopStock          map[uint32][]ShopItem
     42 	ItemCombinations   map[uint32]map[uint32]ItemCombination
     43 	PlayerAppearances  struct {
     44 		Heads  []PlayerHead `yaml:"heads"`
     45 		Bodies []PlayerBody `yaml:"bodies"`
     46 	}
     47 	CorpsePoses map[uint32]struct {
     48 		Mesh      uint32       `yaml:"mesh"`
     49 		Animation uint32       `yaml:"animation"`
     50 		Vertices  [][3]float32 `yaml:"vertices"`
     51 	}
     52 	BankTerminals map[uint32]struct {
     53 		Playfield uint32     `yaml:"playfield"`
     54 		Position  [3]float32 `yaml:"position"`
     55 	}
     56 	ClinicTerminals map[uint32]struct {
     57 		Playfield uint32     `yaml:"playfield"`
     58 		Position  [3]float32 `yaml:"position"`
     59 	}
     60 	InformationItems map[uint32]struct {
     61 		Template  uint32     `yaml:"template"`
     62 		Playfield uint32     `yaml:"playfield"`
     63 		Position  [3]float32 `yaml:"position"`
     64 	}
     65 	InsuranceTerminals struct {
     66 		Scanners map[uint32]struct {
     67 			Template  uint32     `yaml:"template"`
     68 			Playfield uint32     `yaml:"playfield"`
     69 			Position  [3]float32 `yaml:"position"`
     70 			Arrival   struct {
     71 				Position [3]float32 `yaml:"position"`
     72 				Rotation [4]float32 `yaml:"rotation"`
     73 			} `yaml:"arrival"`
     74 		} `yaml:"scanners"`
     75 		Reclaim map[uint32]struct {
     76 			Playfield uint32     `yaml:"playfield"`
     77 			Position  [3]float32 `yaml:"position"`
     78 		} `yaml:"reclaim"`
     79 	}
     80 	ProfessionTitles map[uint16]struct {
     81 		Health [6]uint32 `yaml:"health"`
     82 		Nano   [6]uint32 `yaml:"nano"`
     83 		IP     [6]uint32 `yaml:"ip"`
     84 	}
     85 	IPTraining struct {
     86 		TitleLevels [6]uint32 `yaml:"title_levels"`
     87 		Breeds      map[uint16]struct {
     88 			Base    [6]uint32 `yaml:"base"`
     89 			Maximum [6]uint32 `yaml:"maximum"`
     90 			Cost    [6]uint32 `yaml:"cost"`
     91 		} `yaml:"breeds"`
     92 		Professions map[uint16]map[uint32]uint32 `yaml:"professions"`
     93 		Limits      map[uint32]struct {
     94 			Titles   [6]uint32 `yaml:"titles"`
     95 			PerLevel uint32    `yaml:"per_level"`
     96 		} `yaml:"limits"`
     97 		Weights map[uint32][6]uint32 `yaml:"weights"`
     98 	}
     99 )
    100 
    101 func init() {
    102 	// Load population provenance and confidence descriptions before linking zones.
    103 	var population struct {
    104 		NPCData               `yaml:",inline"`
    105 		NPCExtractionEvidence `yaml:",inline"`
    106 	}
    107 	loadYAML("population_evidence.yaml", &population)
    108 	NPCs = population.NPCData
    109 	PopulationEvidence = population.NPCExtractionEvidence
    110 	loadYAML("npc_names.yaml", &NPCNames)
    111 	loadYAML("monsters.yaml", &Monsters)
    112 	for index := range Monsters {
    113 		MonsterTemplates[Monsters[index].MonsterData] = &Monsters[index]
    114 	}
    115 	loadYAML("corpse_poses.yaml", &CorpsePoses)
    116 	for identity, pose := range CorpsePoses {
    117 		monster := MonsterTemplates[identity]
    118 		if monster == nil || len(monster.DeathAnimations) == 0 || monster.Mesh != pose.Mesh || monster.DeathAnimations[0] != pose.Animation || len(pose.Vertices) == 0 {
    119 			panic(fmt.Errorf("corpse pose does not match monster %d", identity))
    120 		}
    121 	}
    122 	loadYAML("map_coordinates.yaml", &MapCoordinates)
    123 	loadYAML("terrain_evidence.yaml", &TerrainEvidence)
    124 	loadYAML("playfields.yaml", &Playfields)
    125 	loadYAML("player_appearances.yaml", &PlayerAppearances)
    126 	loadYAML("banks.yaml", &BankTerminals)
    127 	loadYAML("clinics.yaml", &ClinicTerminals)
    128 	loadYAML("information.yaml", &InformationItems)
    129 	loadYAML("insurance.yaml", &InsuranceTerminals)
    130 	loadYAML("shops.yaml", &ShopMachines)
    131 	loadYAML("mission_booths.yaml", &MissionBooths)
    132 	loadYAML("missions.yaml", &MissionTemplates)
    133 	loadYAML("mission_levels.yaml", &MissionLevels)
    134 	if len(MissionLevels) != 200 {
    135 		panic("mission levels must cover classic character levels 1..200")
    136 	}
    137 	for level := uint16(1); level <= 200; level++ {
    138 		levels := MissionLevels[level]
    139 		for index, selected := range levels {
    140 			if selected == 0 || selected > 250 || index > 0 && selected < levels[index-1] || levels[5] != level {
    141 				panic(fmt.Errorf("invalid mission level selection for character level %d", level))
    142 			}
    143 		}
    144 	}
    145 	loadYAML("shop_stock.yaml", &ShopStock)
    146 	loadYAML("profession_resources.yaml", &ProfessionTitles)
    147 	loadYAML("experience.yaml", &ExperienceLevels)
    148 	loadYAML("ip_training.yaml", &IPTraining)
    149 
    150 	zones, err := fs.Glob(files, "zones/*.yaml")
    151 	if err != nil {
    152 		panic(err)
    153 	}
    154 	for _, name := range zones {
    155 		var playfield NPCPlayfield
    156 		loadYAML(name, &playfield)
    157 		if playfield.Source != nil {
    158 			if playfield.Source.Playfield != playfield.ID {
    159 				panic(fmt.Errorf("gamedata %s: source playfield does not match id", name))
    160 			}
    161 			PopulationSources = append(PopulationSources, playfield.Source)
    162 		}
    163 		for index := range playfield.Districts {
    164 			district := &playfield.Districts[index]
    165 			if district.SourceIndex != nil {
    166 				if playfield.Source == nil || *district.SourceIndex < 0 || *district.SourceIndex >= len(playfield.Source.Districts) {
    167 					panic(fmt.Errorf("gamedata %s: district %q has an invalid source_index", name, district.Name))
    168 				}
    169 				district.Source = &playfield.Source.Districts[*district.SourceIndex]
    170 			}
    171 			for index := range district.Groups {
    172 				group := &district.Groups[index]
    173 				if group.ID == "" || NPCGroups[group.ID] != nil {
    174 					panic(fmt.Errorf("gamedata %s: missing or duplicate NPC group id %q", name, group.ID))
    175 				}
    176 				NPCGroups[group.ID] = group
    177 				applyNPCOutfit(group)
    178 				if group.ShopTemplate != 0 && len(ShopStock[group.ShopTemplate]) == 0 {
    179 					panic(fmt.Errorf("gamedata %s: NPC %q has no shop stock for %d", name, group.ID, group.ShopTemplate))
    180 				}
    181 				if group.SourceIndex == nil {
    182 					continue
    183 				}
    184 				if district.Source == nil || *group.SourceIndex < 0 {
    185 					panic(fmt.Errorf("gamedata %s: NPC %q has an invalid source_index", name, group.ID))
    186 				}
    187 				if group.PlacementStatus == "fixed_point" {
    188 					if *group.SourceIndex >= len(district.Source.FixedSpawns) {
    189 						panic(fmt.Errorf("gamedata %s: NPC %q has an invalid fixed source_index", name, group.ID))
    190 					}
    191 					group.FixedSource = &district.Source.FixedSpawns[*group.SourceIndex]
    192 				} else {
    193 					if *group.SourceIndex >= len(district.Source.SpawnGroups) {
    194 						panic(fmt.Errorf("gamedata %s: NPC %q has an invalid group source_index", name, group.ID))
    195 					}
    196 					group.Source = &district.Source.SpawnGroups[*group.SourceIndex]
    197 				}
    198 			}
    199 		}
    200 		if len(playfield.Districts) != 0 {
    201 			NPCs.Playfields = append(NPCs.Playfields, playfield)
    202 		}
    203 	}
    204 	sort.Slice(NPCs.Playfields, func(i, j int) bool { return NPCs.Playfields[i].ID < NPCs.Playfields[j].ID })
    205 	sort.Slice(PopulationSources, func(i, j int) bool { return PopulationSources[i].Playfield < PopulationSources[j].Playfield })
    206 
    207 	// Stream individual item documents so parsing never builds a catalog-sized tree.
    208 	loadYAML("items.yaml", &Items)
    209 	count := uint32(0)
    210 	for _, records := range Items.Coverage.RecordCounts {
    211 		count += records
    212 	}
    213 	Items.Items = make([]Item, 0, count)
    214 	parts, err := fs.Glob(files, "items/*.yaml")
    215 	if err != nil {
    216 		panic(err)
    217 	}
    218 	texts := make(map[string]string)
    219 	for _, name := range parts {
    220 		loadItems(name, texts)
    221 	}
    222 	for index := range Items.Items {
    223 		if Items.Items[index].RecordType == 1000020 {
    224 			ItemTemplates[Items.Items[index].ID] = &Items.Items[index]
    225 		} else if Items.Items[index].RecordType == 1040005 {
    226 			NanoTemplates[Items.Items[index].ID] = &Items.Items[index]
    227 		}
    228 	}
    229 
    230 	// Reviewed families retain both endpoints for any supported intermediate QL.
    231 	var families [][2]uint32
    232 	loadYAML("item_families.yaml", &families)
    233 	for _, pair := range families {
    234 		first, second := ItemTemplates[pair[0]], ItemTemplates[pair[1]]
    235 		if first == nil || second == nil || first.Quality == nil || second.Quality == nil ||
    236 			*first.Quality == 0 || *first.Quality >= *second.Quality || first.HeaderWords[0] != second.HeaderWords[0] ||
    237 			ItemFamilies[pair[0]] != [2]uint32{} || ItemFamilies[pair[1]] != [2]uint32{} {
    238 			panic(fmt.Errorf("invalid or overlapping item family %d/%d", pair[0], pair[1]))
    239 		}
    240 		ItemFamilies[pair[0]], ItemFamilies[pair[1]] = pair, pair
    241 	}
    242 
    243 	// Stock rows specify their own quality within explicit original family intervals.
    244 	for vendor, stock := range ShopStock {
    245 		if ItemTemplates[vendor] == nil || ItemTemplates[vendor].HeaderWords[0] != 51035 {
    246 			panic(fmt.Errorf("invalid shop stock owner %d", vendor))
    247 		}
    248 		for _, item := range stock {
    249 			if !ItemQualitySupported(item.Template, item.Quality) {
    250 				panic(fmt.Errorf("invalid shop stock %d: template %d quality %d", vendor, item.Template, item.Quality))
    251 			}
    252 		}
    253 	}
    254 
    255 	// Accepted contracts retain the advertised selected quality, including intermediates.
    256 	for booth, mission := range MissionTemplates {
    257 		if ItemTemplates[mission.PassageDoor] == nil || ItemTemplates[mission.PassageDoor].HeaderWords[0] != 51016 {
    258 			panic(fmt.Errorf("invalid mission door %d: template %d", booth, mission.PassageDoor))
    259 		}
    260 		if len(mission.RewardItems) == 0 && mission.RewardQuality != 0 {
    261 			panic(fmt.Errorf("mission %d reward quality has no item pool", booth))
    262 		}
    263 		for _, template := range mission.RewardItems {
    264 			item := ItemTemplates[template]
    265 			if item == nil || item.Quality == nil || *item.Quality == 0 || mission.RewardQuality != 0 && !ItemQualitySupported(template, mission.RewardQuality) {
    266 				panic(fmt.Errorf("invalid mission reward %d: template %d quality %d", booth, template, mission.RewardQuality))
    267 			}
    268 		}
    269 	}
    270 
    271 	// Fixed-QL recipes identify both inputs and which ones their result replaces.
    272 	loadYAML("item_combinations.yaml", &ItemCombinations)
    273 	for first, targets := range ItemCombinations {
    274 		for second, recipe := range targets {
    275 			for _, template := range []uint32{first, second, recipe.Result} {
    276 				if item := ItemTemplates[template]; item == nil || item.Quality == nil || *item.Quality == 0 {
    277 					panic(fmt.Errorf("item combination %d/%d has invalid template %d", first, second, template))
    278 				}
    279 			}
    280 			if !recipe.Consume[0] && !recipe.Consume[1] {
    281 				panic(fmt.Errorf("item combination %d/%d consumes no input", first, second))
    282 			}
    283 		}
    284 	}
    285 
    286 	// Expand bounded level anchors before validating every resolved combat profile.
    287 	loadYAML("npc_combat.yaml", &NPCCombatProfiles)
    288 	if err := interpolateNPCProfiles(NPCCombatProfiles); err != nil {
    289 		panic(err)
    290 	}
    291 	for monster, levels := range NPCCombatProfiles {
    292 		for level, profile := range levels {
    293 			for stat, value := range profile.Skills {
    294 				if _, known := IPTraining.Weights[stat]; !known || value < 0 || value > 65535 {
    295 					panic(fmt.Errorf("NPC combat profile %d/%d has invalid raw skill %d", monster, level, stat))
    296 				}
    297 			}
    298 			for stat, value := range profile.Modifiers {
    299 				if stat != 276 && stat != 277 && (stat < 90 || stat > 97 || value < 0) {
    300 					panic(fmt.Errorf("NPC combat profile %d/%d has unsupported modifier %d", monster, level, stat))
    301 				}
    302 			}
    303 			// Template-specific encounters must match an admitted original population.
    304 			for index, id := range profile.Groups {
    305 				group := NPCGroups[id]
    306 				if group == nil || slices.Contains(profile.Groups[:index], id) || !group.SupportsCombatProfile(monster, profile) {
    307 					panic(fmt.Errorf("NPC combat profile %d/%d has invalid group %q", monster, level, id))
    308 				}
    309 			}
    310 			if len(profile.TemplateCodes) != 0 {
    311 				for index, code := range profile.TemplateCodes {
    312 					if code == "" || slices.Contains(profile.TemplateCodes[:index], code) {
    313 						panic(fmt.Errorf("NPC combat profile %d/%d has an empty or duplicate template code", monster, level))
    314 					}
    315 				}
    316 				matched := false
    317 				for _, group := range NPCGroups {
    318 					if group.SupportsCombatProfile(monster, profile) &&
    319 						level >= group.Levels[0] && level <= group.Levels[1] {
    320 						matched = true
    321 						break
    322 					}
    323 				}
    324 				if !matched {
    325 					panic(fmt.Errorf("NPC combat profile %d/%d has no admitted population for %v", monster, level, profile.TemplateCodes))
    326 				}
    327 			}
    328 			first, second := ItemTemplates[profile.Weapon[0]], ItemTemplates[profile.Weapon[1]]
    329 			if MonsterTemplates[monster] == nil || level == 0 || profile.Health == 0 ||
    330 				first == nil || second == nil || first.HeaderWords[0] != 51018 || second.HeaderWords[0] != 51018 ||
    331 				first.Quality == nil || second.Quality == nil || *first.Quality > uint32(level) || *second.Quality < uint32(level) ||
    332 				profile.AggDef < -100 || profile.AggDef > 100 {
    333 				panic(fmt.Errorf("NPC combat profile %d/%d has invalid health, weapon or AggDef", monster, level))
    334 			}
    335 			if profile.Credits[0] > profile.Credits[1] || profile.Credits[1] > 100000 {
    336 				panic(fmt.Errorf("NPC combat profile %d/%d has invalid corpse cash", monster, level))
    337 			}
    338 			for _, drop := range profile.Loot {
    339 				if drop.Chance > 100 || drop.Quality[0] > drop.Quality[1] || drop.Evidence == "" && drop.Inference == "" ||
    340 					!ItemQualitySupported(drop.Template, drop.Quality[0]) || !ItemQualitySupported(drop.Template, drop.Quality[1]) {
    341 					panic(fmt.Errorf("NPC combat profile %d/%d has invalid loot %d", monster, level, drop.Template))
    342 				}
    343 			}
    344 		}
    345 	}
    346 	loadLoot()
    347 }
    348 
    349 func loadYAML(name string, value any) {
    350 	file, err := files.Open(name)
    351 	if err != nil {
    352 		panic(err)
    353 	}
    354 	defer file.Close()
    355 	decoder := yaml.NewDecoder(file)
    356 	decoder.KnownFields(true)
    357 	if err := decoder.Decode(value); err != nil {
    358 		panic(fmt.Errorf("gamedata %s: %w", name, err))
    359 	}
    360 }
    361 
    362 func loadItems(name string, texts map[string]string) {
    363 	file, err := files.Open(name)
    364 	if err != nil {
    365 		panic(err)
    366 	}
    367 	defer file.Close()
    368 	decoder := yaml.NewDecoder(file)
    369 	decoder.KnownFields(true)
    370 	for {
    371 		var item Item
    372 		err := decoder.Decode(&item)
    373 		if err == io.EOF {
    374 			return
    375 		}
    376 		if err != nil {
    377 			panic(fmt.Errorf("gamedata %s: %w", name, err))
    378 		}
    379 		// Quality variants share immutable text; the temporary index dies at startup.
    380 		for _, value := range []*string{&item.Name, &item.Description} {
    381 			if shared, ok := texts[*value]; ok {
    382 				*value = shared
    383 			} else {
    384 				texts[*value] = *value
    385 			}
    386 		}
    387 		Items.Items = append(Items.Items, item)
    388 	}
    389 }