#!/usr/bin/env python3
"""Extract the dungeon-view tables of Eye of the Beholder II (DOS) as JSON.

Reads your own copy of START.EXE, checks that it is the documented release,
and prints the tables used to draw the view, as described in
docs/view/README.md. Nothing is written to the game directory.

Usage:
    python3 scripts/view/extract_view_tables.py path/to/START.EXE > view-tables.json
"""

import hashlib
import json
import struct
import sys

SHA256 = '2bb5edf06d966a4dbf40dd4866733a9ce37e47c5ace052615df4b6b69d4cb8b4'
DS = 0x2e360          # physical offset of data-segment offset 0
SEGMENT_TABLE = 0x2d520


def main():
    if len(sys.argv) != 2:
        sys.exit(__doc__)
    exe = open(sys.argv[1], 'rb').read()
    if hashlib.sha256(exe).hexdigest() != SHA256:
        sys.exit('START.EXE does not match the documented release (SHA-256 differs).')

    def s8(off, n):
        return [b - 256 if b > 127 else b for b in exe[DS + off:DS + off + n]]

    def u8(off, n):
        return list(exe[DS + off:DS + off + n])

    def s16(off, n):
        return list(struct.unpack_from('<%dh' % n, exe, DS + off))

    def rows(values, width):
        return [values[i:i + width] for i in range(0, len(values), width)]

    side_names = {0x9444: 'front', 0xdf2b: 'right-hand', 0xdf4a: 'left-hand'}
    deco_faces = []
    for k in range(36):
        off, seg = struct.unpack_from('<HH', exe, DS + 0x50b + 4 * k)
        deco_faces.append(side_names.get(off) if (off, seg) != (0, 0) else None)

    # Teleporter points live in another segment (relocated operand 0x250).
    seg = struct.unpack_from('<H', exe, SEGMENT_TABLE + 0x250)[0]
    tp = [b - 256 if b > 127 else b for b in exe[0x3200 + seg * 16:0x3200 + seg * 16 + 156]]

    tables = {
        'direction_steps': s8(0x20e9, 4),
        'view_sides': {'front': u8(0x22b8, 4), 'left_blocks_show': u8(0x22bc, 4),
                       'right_blocks_show': u8(0x22c0, 4)},
        'view_offsets_by_direction': rows(s8(0x22c4, 72), 18),
        'object_draw_order': u8(0x711, 18),
        'spots_by_block': [rows(s16(0x23ec + 20 * b, 10), 2) for b in range(18)],
        'spot_by_facing_and_position': rows(u8(0x2352, 16), 4),
        'depth_class_by_block': u8(0x2330, 18),
        'item_scale_by_depth_and_spot': rows(s8(0x478, 16), 4),
        'item_door_clip_block': s8(0x466, 18),
        'niche_y_by_depth': s16(0x488, 4),
        'item_spread': s16(0x48e, 8),
        'niche_x_by_block': s16(0x230c, 18),
        'decoration_face_by_block_and_pass': rows(deco_faces, 2),
        'decoration_position_by_block_and_pass': rows(s8(0x59b, 36), 2),
        'decoration_front_shift_by_block': s16(0x5bf, 18),
        'monster_steps_by_depth': s8(0x4ae, 3),
        'monster_frames_alternate': rows(s8(0x4b1, 32), 4),
        'monster_frames_normal': rows(s8(0x4d1, 32), 4),
        'monster_slot_by_facing_and_position': rows(u8(0x4f1, 20), 5),
        'monster_lift_centre_then_other': s8(0x505, 6),
        'flight_scale_by_block_and_spot': rows(s8(0x667, 72), 4),
        'flight_slot_by_facing_and_position': rows(u8(0x6af, 20), 5),
        'item_shape_by_icon': s8(0x2590, 112),
        'flight_shape_by_item_shape': s8(0x2601, 41),
        'flight_mirror_by_direction_and_position': rows(u8(0x6c3, 16), 4),
        'door_bottom_top_by_depth': {'bottom': s8(0x5e3, 3), 'top': s8(0x5e7, 3)},
        'door_frame_rows_by_depth': {'top': s8(0x45e, 4), 'bottom': s8(0x462, 4)},
        'door_first_reference_by_wall': s8(0x5eb, 53),
        'door_graphic_by_wall': s8(0x620, 53),
        'door_raise_by_depth': s8(0x655, 3),
        'door_part_by_depth': s8(0x65d, 3),
        'door_force_by_shape': s8(0x661, 6),
        'teleporter_offset_x_by_t': u8(0x6d3, 3),
        'teleporter_y_by_t': u8(0x6d6, 3),
        'teleporter_points_by_set': [rows(tp[26 * k:26 * k + 26], 2) for k in range(6)],
        'teleporter_sparkle_rectangles': rows(u8(0xfbe, 24), 4),
        'temporary_wall_start_x_by_block': s16(0x6d9, 15),
        'temporary_wall_rectangles': [u8(0xfd6 + 6 * k, 4) for k in range(6)],
        'temporary_wall_rows_per_row_y_shape_by_depth': {
            'rows': s8(0x6fd, 3), 'per_row': s8(0x700, 3),
            'y': s8(0x703, 3), 'shape': s8(0x706, 3)},
        'wall_clip_by_block_and_face': rows(s8(0x92, 324), 18),
        'door_clip_by_block_and_face': [rows(s8(0x1d6 + 36 * b, 36), 2) for b in range(18)],
    }
    json.dump(tables, sys.stdout, indent=1)
    print()


if __name__ == '__main__':
    main()
