tools/data/generate_npcs.py (15489B)
1 import collections 2 import json 3 import math 4 import pathlib 5 6 import ruamel.yaml 7 8 import npc_assignments 9 10 11 # These appearance assignments are provisional, not recovered NPC templates. 12 appearances = { 13 'ANDR': 17649, 'ANUN': 38389, 'ANVI': 17651, 'AQUA': 30369, 14 'AUTO': 40059, 'BABY': 40065, 'BIOF': 30258, 'BLUB': 40075, 15 'BREI': 17706, 'BRON': 30346, 'CARR': 40486, 'CYBO': 17643, 16 'CLAW': 38387, 'EYEM': 17653, 'FLEA': 17657, 'HAMM': 30383, 17 'GFLS': 17691, 'HOVE': 20614, 'LEET': 17655, 'LIZA': 22794, 'MALL': 17660, 18 'MECH': 17720, 'NANO': 38394, 'PILI': 17710, 'PIRA': 95357, 'PIXI': 38414, 19 'PUKO': 95355, 'REET': 30365, 'ROLL': 17687, 'SABR': 30356, 20 'SALA': 30354, 'SCOR': 17693, 'SHAD': 30464, 'SKSP': 30379, 21 'SLAY': 22821, 'SNAK': 30252, 'STAL': 17708, 'STAN': 85351, 'STON': 30377, 22 'TENT': 17695, 'WARD': 17697, 'WOLV': 30348, 'YUTT': 22802, 23 'UNBR': 45603, 'WACO': 17714, 24 # Dungeon codes matched to named 14.9.1 appearance records and guide context. 25 'ARAS': 158175, 'MOLE': 158176, 26 'ASSU': 155962, 'DRSH': 203736, 'EMSE': 203731, 'FASO': 203729, 27 'MDPA': 203747, 'MENI': 203726, 'MUGG': 203734, 'NUBR': 203730, 28 'RESC': 204178, 'STFE': 203739, 'STFO': 203744, 'VEAE': 203748, 29 'VOVG': 203733, 'WOST': 203854, 30 } 31 # Numbered codes use provisional species models, not recovered variant stats. 32 families = { 33 'AD': 17649, 'AN': 38389, 'AS': 40059, 'BB': 40075, 'BE': 17706, 34 'BR': 30346, 'CL': 38387, 'CY': 17643, 'ER': 31762, 'EY': 17653, 35 'FL': 17657, 'GO': 17691, 'GU': 40069, 'HA': 30383, 'JU': 22798, 36 'LE': 17655, 'LZ': 22794, 'ME': 26048, 'ML': 17660, 'MN': 30375, 37 'NF': 38394, 'NK': 30358, 'OT': 22790, 'PI': 17710, 'PU': 95355, 38 'PX': 38414, 'RH': 17664, 'RR': 17687, 'RT': 30365, 'SD': 22821, 39 'SG': 30260, 'SH': 30464, 'SK': 40067, 'SL': 17708, 'SN': 30252, 40 'SW': 17712, 'TD': 22804, 'TM': 17695, 'WC': 17714, 'WD': 17697, 41 'WO': 30348, 'YU': 22802, 42 } 43 44 # Human body records require matching breed and sex to initialize their materials. 45 # Build 1 is provisional; these values do not recover clothing or head selection. 46 human_appearances = { 47 26074: 0x115, 26076: 0x195, 26082: 0x195, 26088: 0x115, 48 26090: 0x195, 26092: 0x115, 26097: 0xc5, 26103: 0xc5, 49 26135: 0x125, 26137: 0x1a5, 26143: 0x1b5, 26147: 0x135, 50 26149: 0x1b5, 26151: 0x135, 26155: 0x1b5, 26159: 0x135, 51 152239: 0x115, 152241: 0xc5, 159085: 0xc5, 52 203726: 0x135, 203727: 0x1b5, 203728: 0x135, 203729: 0x135, 53 203730: 0x1b5, 203731: 0x1b5, 203733: 0x115, 203734: 0x115, 54 203736: 0x195, 203739: 0x115, 203743: 0x115, 203744: 0x115, 55 203746: 0x135, 203747: 0x1b5, 203748: 0x135, 203854: 0xc5, 56 204178: 0x1b5, 205867: 0x115, 206249: 0x115, 206250: 0x115, 57 206251: 0x115, 58 } 59 60 61 def appearance(template_code, playfield, monsters, names): 62 monster_data = appearances.get(template_code) 63 if monster_data is None and template_code[2:].isdigit(): 64 monster_data = families.get(template_code[:2]) 65 if monster_data is not None: 66 name = 'Reet' if monster_data == 30365 else monsters[monster_data]['name'].title() 67 result = [name, monster_data, 0xe5, 'inferred_species', 'Species assignment is provisional; original template not recovered.'] 68 else: 69 # Human conventions are inferred from codes and their authored locations. 70 human = (template_code[:1] in ['H', 'N'] and template_code[1:].isdigit() 71 or template_code in ['OTBG', 'OTGD', 'CLBG', 'CLGD', 'NEBG', 'NEGD'] 72 or 'shop' in playfield['name'].lower() or 'backyard' in playfield['name'].lower()) 73 if human: 74 result = ['Placeholder ' + template_code, 26092, 0x315, 'placeholder_human', 75 'Human role inferred from code or shop/backyard location; generic Solitus appearance.'] 76 else: 77 result = ['Placeholder ' + template_code, 17655, 0xe5, 'placeholder_creature', 78 'Original template unresolved; Leet used as a visible stand-in.'] 79 80 # Per-code evidence can resolve a name or a base model independently. 81 if template_code in names.get('templates', {}): 82 mapping = names['templates'][template_code] 83 result[0] = mapping['name'] 84 if mapping.get('monster_data'): 85 result[1:4] = [mapping['monster_data'], 0xe5, 'inferred_species'] 86 result[4] = 'Base appearance inferred; exact variant, equipment and original template remain unknown.' 87 result[4] += ' Name confidence: ' + mapping['confidence'] + '. ' + mapping['comment'] 88 result[4] += ' Source: ' + names['sources'][mapping['source']] 89 90 # Local name evidence takes precedence without resolving a placeholder model. 91 if playfield['playfield'] in names.get('playfields', {}): 92 mapping = names['playfields'][playfield['playfield']] 93 if template_code in mapping['names']: 94 result[0] = mapping['names'][template_code] 95 result[4] += ' Name confidence: ' + mapping['confidence'] + '. ' + mapping['comment'] 96 result[4] += ' Source: ' + names['sources'][mapping['source']] 97 98 # Keep faction and head bits while pairing a human body with human materials. 99 if result[1] in human_appearances: 100 result[2] = result[2] & ~0x1ff | human_appearances[result[1]] 101 return result 102 103 104 def append_group(lines, code, name, monster_data, breed, levels, status, placement, comment, positions, definition_id, source_index): 105 # One batch shares provenance and appearance; XYZ rows remain easy to edit. 106 lines.extend([ 107 f' - id: {json.dumps(definition_id)}', 108 f' source_index: {source_index}', 109 f' template_code: {json.dumps(code)}', 110 f' name: {json.dumps(name)}', 111 f' monster_data: {monster_data}', 112 f' appearance: {breed}', 113 f' levels: {json.dumps(levels)}', 114 f' appearance_status: {status}', 115 f' placement_status: {placement}', 116 f' comment: {json.dumps(comment)}', 117 ' positions:', 118 ]) 119 for x, y, z in positions: 120 lines.append(f' - [{x:.9g}, {y:.9g}, {z:.9g}]') 121 122 def generate(catalog, monsters, version, names): 123 assert all(identity in monsters for identity in list(appearances.values()) + list(families.values())) 124 assert all(mapping['monster_data'] in monsters for mapping in names.get('templates', {}).values() 125 if mapping.get('monster_data')) 126 # Keep every requested instance; historical templates and allocation are unknown. 127 lines = [ 128 '# NPC population reconstruction from the original 11.0 disc.' if version == '11.0' else '# NPC population reconstruction from client ' + version + '.', 129 '# Source: local/reports/original-npc-spawns.json and local/reports/original-monsters.json.' if version == '11.0' else '# Source: local/data/npc-spawns.json and local/data/monsters.json.', 130 '# Editable YAML. Regenerating with tools/data/generate_npcs.py overwrites edits and comments.' if version == '11.0' else '# Extraction candidate; review changes against server/gamedata before editing maintained YAML.', 131 '# Appearance and placement statuses are independent; neither implies recovered AI.', 132 'appearance_statuses:', 133 ' inferred_species:', 134 ' confidence: inferred', 135 ' comment: "Species inferred from template codes; full original NPC templates remain unknown."', 136 ' placeholder_human:', 137 ' confidence: placeholder', 138 ' comment: "Human classification is inferred; name, model, clothes and role are placeholders."', 139 ' placeholder_creature:', 140 ' confidence: placeholder', 141 ' comment: "Unknown creature identity; uses the original Leet appearance as a stand-in."', 142 'placement_statuses:', 143 ' authored_point:', 144 ' confidence: approximate', 145 ' comment: "XYZ is an authored point; assigning this NPC to it is an inferred allocation."', 146 ' spread_authored_point:', 147 ' confidence: approximate', 148 ' comment: "Generated offset within an authored radius; original sampling and ground adjustment unknown."', 149 ' district_center_fallback:', 150 ' confidence: approximate', 151 ' comment: "No points authored for this population; generated grid around the district centre."', 152 ' fixed_point:', 153 ' confidence: authored', 154 ' comment: "XYZ preserved from the fixed spawn record; original heading units remain unknown."', 155 'level_policy:', 156 ' confidence: inferred', 157 ' comment: "Placements cycle through the authored inclusive level range; original selection and distribution are unknown. Each replacement retains its selected level."', 158 'playfields:', 159 ] 160 coverage = {'appearance_counts': collections.Counter(), 'placement_counts': collections.Counter(), 161 'templates': {}, 'playfields': []} 162 total = 0 163 for playfield in catalog: 164 if playfield['playfield'] in [100, 102, 103, 1410]: 165 continue 166 count = 0 167 playfield_lines = [] 168 for district_index, district in enumerate(playfield['districts']): 169 district_lines = [] 170 point_index = 0 171 requested = sum(group['count'] for group in district['spawn_groups']) 172 for group_index, group in enumerate(district['spawn_groups']): 173 name, monster_data, breed, status, comment = appearance(group['template_hash'], playfield, monsters, names) 174 coverage['appearance_counts'][status] += group['count'] 175 coverage['templates'].setdefault(group['template_hash'], collections.Counter())[status] += group['count'] 176 positions = collections.defaultdict(list) 177 for _ in range(group['count']): 178 if district['spawn_points']: 179 point = point_index % len(district['spawn_points']) 180 cycle = point_index // len(district['spawn_points']) 181 x, y, z, radius = district['spawn_points'][point] 182 placement = 'authored_point' 183 if cycle: 184 # Spread repeated occupants within the point radius, near its height. 185 cycles = math.ceil(requested / len(district['spawn_points'])) 186 distance = min(radius, 2) * math.sqrt(cycle / cycles) 187 x += math.cos(point_index * 2.399963229728653) * distance 188 z += math.sin(point_index * 2.399963229728653) * distance 189 placement = 'spread_authored_point' 190 else: 191 # Missing point lists get a repeatable two-metre grid around the centre. 192 width = math.ceil(math.sqrt(requested)) 193 x, y, z = district['center'] 194 x += (point_index % width - (width - 1) / 2) * 2 195 z += (point_index // width - (width - 1) / 2) * 2 196 placement = 'district_center_fallback' 197 point_index += 1 198 count += 1 199 coverage['placement_counts'][placement] += 1 200 positions[placement].append((x, y, z)) 201 for placement, points in positions.items(): 202 append_group(district_lines, group['template_hash'], name, monster_data, breed, 203 [district['npc_min_level'], district['npc_max_level']], status, placement, comment, points, 204 f"{playfield['playfield']}/district/{district_index}/group/{group_index}/{placement}", group_index) 205 # Preserve all fixed positions and levels; heading units remain unknown. 206 for spawn_index, spawn in enumerate(district['fixed_spawns']): 207 name, monster_data, breed, status, comment = appearance(spawn['template_hash'], playfield, monsters, names) 208 x, y, z = spawn['position'] 209 count += 1 210 coverage['appearance_counts'][status] += 1 211 coverage['templates'].setdefault(spawn['template_hash'], collections.Counter())[status] += 1 212 coverage['placement_counts']['fixed_point'] += 1 213 append_group(district_lines, spawn['template_hash'], name, monster_data, breed, 214 [spawn['min_level'], spawn['max_level']], status, 'fixed_point', comment, [(x, y, z)], 215 f"{playfield['playfield']}/district/{district_index}/fixed/{spawn_index}", spawn_index) 216 if district_lines: 217 playfield_lines.extend([f' - name: {json.dumps(district["name"])}', 218 f' source_index: {district_index}', ' groups:']) 219 playfield_lines.extend(district_lines) 220 if count: 221 total += count 222 coverage['playfields'].append({'playfield': playfield['playfield'], 'name': playfield['name'], 'count': count}) 223 lines.extend(['', f'- id: {playfield["playfield"]}', 224 f' name: {json.dumps(playfield["name"])}', ' districts:']) 225 lines.extend(playfield_lines) 226 coverage['total'] = total 227 return '\n'.join(lines) + '\n', coverage 228 229 230 def main(): 231 catalog = json.loads(pathlib.Path('local/data/npc-spawns.json').read_text()) 232 monsters = {monster['monster_data']: monster for monster in 233 json.loads(pathlib.Path('local/data/monsters.json').read_text())} 234 names = ruamel.yaml.YAML(typ='safe').load(pathlib.Path('server/gamedata/npc_names.yaml').read_text()) 235 names['playfields'] = {int(key): value for key, value in names['playfields'].items()} 236 generated, coverage = generate(catalog, monsters, '14.9.1', names) 237 238 # Apply reviewed context choices after preserving the original allocation. 239 yaml = ruamel.yaml.YAML() 240 population = yaml.load(generated) 241 npc_assignments.apply_to_population(population, npc_assignments.load_reviewed_groups()) 242 evidence = ruamel.yaml.YAML(typ='safe').load(pathlib.Path('server/gamedata/population_evidence.yaml').read_text()) 243 population['appearance_statuses'] = evidence['appearance_statuses'] 244 coverage['appearance_counts'], coverage['templates'] = collections.Counter(), {} 245 for playfield in population['playfields']: 246 for district in playfield['districts']: 247 for group in district['groups']: 248 count = len(group['positions']) 249 coverage['appearance_counts'][group['appearance_status']] += count 250 coverage['templates'].setdefault(group['template_code'], collections.Counter())[group['appearance_status']] += count 251 252 # Extraction is a review input; maintained embedded definitions are edited directly. 253 pathlib.Path('local/reports').mkdir(parents=True, exist_ok=True) 254 with pathlib.Path('local/reports/npc_spawns.generated.yaml').open('w', encoding='ascii') as output: 255 yaml.dump(population, output) 256 pathlib.Path('local/reports/npc-coverage.json').write_text(json.dumps(coverage, indent=2, sort_keys=True) + '\n') 257 print('Generated', coverage['total'], '14.9.1 NPCs in', len(coverage['playfields']), 'playfields') 258 print('Appearances:', dict(coverage['appearance_counts'])) 259 260 261 if __name__ == '__main__': 262 main()