aorecomp

Anarchy Online classic in the browser

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


tools/data/extract_terrain.py (6076B)


      1 import hashlib
      2 import json
      3 import pathlib
      4 import struct
      5 import zlib
      6 
      7 import ao_database
      8 import yaml
      9 
     10 # Read the selected client's ground archives through the shared resource reader.
     11 client = pathlib.Path('anarchy-vanilla-14.9.1')
     12 assert (client / 'version.id').read_text().strip() == '14.9.1'
     13 database = ao_database.Database(client)
     14 records = sorted(identity for kind, identity in database.records if kind == 1000009)
     15 
     16 pathlib.Path('data').mkdir(exist_ok=True)
     17 catalog = []
     18 without_heights = []
     19 with database.file, open('data/terrain.bin.tmp', 'wb') as output:
     20     output.write(b'AOTERR02' + struct.pack('<I', 0))
     21     for identity in records:
     22         ground = database.read(1000009, identity)
     23         assert ground[:4] in [b'CHGA', b'GNDA', b'UOHA'], (identity, ground[:24].hex())
     24         display_width, display_height, spacing, scale = struct.unpack_from('<HHff', ground, 12)
     25         marker = b'\x08\x09\x00\x00\x00\x00\x00\x00\x00'
     26         if marker not in ground:
     27             without_heights.append(identity)
     28             continue
     29 
     30         # Archive fields 4-7 hold vertex dimensions, row modulo and texture count.
     31         cursor = ground.index(marker)
     32         dimensions = []
     33         for field in [4, 5, 6, 7]:
     34             entry = cursor - (8 - field) * 17
     35             assert ground[entry:entry + 13] == bytes([field]) + struct.pack('<III', 3, 4, 4)
     36             dimensions.append(struct.unpack_from('<I', ground, entry + 13)[0])
     37         width, height = dimensions[0] - 1, dimensions[1] - 1
     38         assert dimensions[2] == width + 1
     39         block_cells = min(width & -width, height & -height, 64)
     40         side = block_cells + 1
     41 
     42         # Reconstruct every compressed block from its two-dimensional deltas.
     43         size = struct.unpack_from('<I', ground, cursor + 9)[0]
     44         cursor += 13
     45         end = cursor + size
     46         chunks = []
     47         while cursor < end:
     48             length = struct.unpack_from('<I', ground, cursor)[0]
     49             cursor += 4
     50             deltas = zlib.decompress(ground[cursor:cursor + length])
     51             cursor += length
     52             assert len(deltas) == side * side, (identity, len(deltas), side)
     53             values = bytearray(len(deltas))
     54             for point, delta in enumerate(deltas):
     55                 column, row = point % side, point // side
     56                 left = values[point - 1] if column else 0
     57                 above = values[point - side] if row else 0
     58                 diagonal = values[point - side - 1] if column and row else 0
     59                 values[point] = (delta + left + above - diagonal) & 255
     60             chunks.append(values)
     61         assert cursor == end
     62         assert ground[cursor:cursor + 9] == b'\x09\x09\x00\x00\x00\x00\x00\x00\x00'
     63         small_size = struct.unpack_from('<I', ground, cursor + 9)[0]
     64         small = ground[cursor + 13:cursor + 13 + small_size]
     65         assert len(small) == len(chunks) * 8
     66         across = width // block_cells
     67         assert len(chunks) == across * (height // block_cells), (identity, width, height, len(chunks), across)
     68         corner_mismatches = []
     69         for chunk_index, chunk in enumerate(chunks):
     70             # Coarse corner samples are separate data, not full-grid checksums.
     71             assert struct.unpack_from('<I', small, chunk_index * 8)[0] == 4
     72             if bytes(chunk[point] for point in [0, side - 1, side * (side - 1), side * side - 1]) != small[chunk_index * 8 + 4:chunk_index * 8 + 8]:
     73                 corner_mismatches.append(chunk_index)
     74             if chunk_index % across:
     75                 assert chunk[::side] == chunks[chunk_index - 1][side - 1::side], (identity, chunk_index, 'X seam')
     76             if chunk_index >= across:
     77                 assert chunk[:side] == chunks[chunk_index - across][-side:], (identity, chunk_index, 'Z seam')
     78 
     79         # Stitch shared-edge tiles into the actual archived row-major vertex grid.
     80         grid = bytearray((width + 1) * (height + 1))
     81         for chunk_index, chunk in enumerate(chunks):
     82             x, z = chunk_index % across * block_cells, chunk_index // across * block_cells
     83             for row in range(side):
     84                 start = (z + row) * (width + 1) + x
     85                 grid[start:start + side] = chunk[row * side:row * side + side]
     86         assert 0 < display_width <= width and 0 < display_height <= height
     87         output.write(struct.pack('<IHHHHff', identity, width, height, display_width, display_height, spacing, scale))
     88         output.write(grid)
     89         catalog.append({'playfield': identity, 'width': width, 'height': height,
     90                         'display_width': display_width, 'display_height': display_height,
     91                         'spacing': spacing, 'height_scale': scale, 'chunks': len(chunks), 'block_cells': block_cells,
     92                         'grid_sha256': hashlib.sha256(grid).hexdigest(),
     93                         'coarse_corner_mismatches': corner_mismatches})
     94     output.seek(8)
     95     output.write(struct.pack('<I', len(catalog)))
     96 pathlib.Path('data/terrain.bin.tmp').replace('data/terrain.bin')
     97 
     98 # Retain decoding coverage and identities independently of the runtime implementation.
     99 pathlib.Path('local/reports').mkdir(parents=True, exist_ok=True)
    100 evidence = {
    101     'client_version': '14.9.1',
    102     'source_index_sha256': hashlib.sha256(database.index).hexdigest(),
    103     'terrain_file_sha256': hashlib.sha256(pathlib.Path('data/terrain.bin').read_bytes()).hexdigest(),
    104     'decoded': catalog, 'records_without_height_table': without_heights,
    105     'checks': ['Every compressed block matches its archived dimensions; coarse corners are retained as independent samples.',
    106                'Every shared X and Z block edge matches exactly.'],
    107 }
    108 pathlib.Path('local/reports/terrain-extraction-evidence.json').write_text(json.dumps(evidence, indent=2) + '\n')
    109 pathlib.Path('server/gamedata/terrain_evidence.yaml').write_text(yaml.safe_dump(evidence, sort_keys=False, width=120))
    110 print('Decoded', len(catalog), 'terrain grids;', len(without_heights), 'tilemap records have no height table')
    111 print('Grid bytes:', sum((item['width'] + 1) * (item['height'] + 1) for item in catalog))