#!/usr/bin/env python3
"""Generate the figures of the engine chapter, docs/engine/.

The figures are original schematic drawings. The timed-update figure reads the
16 records of the timed-callback table from your own DOS START.EXE
(data-segment offset 0x5bfc, data image at file offset 0x2e360; see
docs/executable/data/TIMING.md#d-5bfc): the interval and the initial switch of each
entry. The clock figure is a schematic of the two tick counters described in
docs/engine/CLOCK.md; it carries no measured values. The block-event figure
transcribes the event sources of docs/engine/README.md. No game graphics are used.

Usage:
    python3 scripts/engine/make_engine_figures.py [START.EXE] [output_directory]

The defaults are data/originals/eob2/START.EXE and docs/engine/img/.
"""
import hashlib
import sys
from html import escape
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
EXE = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / 'data/originals/eob2/START.EXE'
OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else ROOT / 'docs/engine/img'
SHA256 = '2bb5edf06d966a4dbf40dd4866733a9ce37e47c5ace052615df4b6b69d4cb8b4'

d = EXE.read_bytes()
if hashlib.sha256(d).hexdigest() != SHA256:
    sys.exit(f'{EXE}: unexpected SHA-256; this script reads the DOS START.EXE listed in docs/files/INVENTORY.md')
DS = 0x2e360


def timed_entry(i):
    base = DS + 0x5bfc + 16 * i
    interval = int.from_bytes(d[base + 4:base + 8], 'little', signed=True)
    enabled = d[base + 0xf] != 0
    return interval, enabled


ENTRIES = [timed_entry(i) for i in range(16)]

FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
SURF, BORDER, INK, INK2, MUTED, GRID = '#fcfcfb', '#dddcd7', '#0b0b0b', '#52514e', '#8a8984', '#eeede9'
BLUE, LIGHT, ORANGE, SHADE = '#2a78d6', '#dbe8f8', '#eb6834', '#f1f0ec'


def text(x, y, s, size=12, fill=INK, weight=None, anchor='start'):
    w = ' font-weight="bold"' if weight else ''
    return (f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" fill="{fill}"{w} '
            f'text-anchor="{anchor}" dominant-baseline="central">{escape(s)}</text>')


def frame(W, H, title, desc):
    return [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" '
            f'role="img" font-family="{FONT}">',
            f'<title>{escape(title)}</title>', f'<desc>{escape(desc)}</desc>',
            f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{SURF}" stroke="{BORDER}"/>']


def write(name, parts):
    parts.append('</svg>')
    OUT.mkdir(parents=True, exist_ok=True)
    (OUT / name).write_text('\n'.join(parts) + '\n', encoding='utf-8')
    print(OUT / name)


# ------------------------------------------------------------- the two counters
def clock():
    W, H = 700, 330
    x0, x1, y0, y1 = 70, 670, 90, 270
    # Real-time segments: (label, length, paused)
    segs = [('play', 3, False), ('camp menu', 2, True), ('play', 2, False),
            ('level load', 1, True), ('play', 2, False)]
    total = sum(s[1] for s in segs)
    X = lambda t: x0 + (x1 - x0) * t / total
    Y = lambda v: y1 - (y1 - y0) * v / total
    desc = ('Schematic of the two tick counters against real time. The free-running counter rises steadily '
            'all the time. The shared counter rises with it during play but stays flat while the camp menu '
            'is open and while a level loads; every deadline is a value of the shared counter, so timed '
            'updates, character timers and timed scripts wait during these pauses.')
    out = frame(W, H, 'Two counters, one of which pauses', desc)
    out.append(text(20, 26, 'Two counters, one of which pauses', 14, weight=True))
    out.append(text(20, 46, 'Schematic: ticks counted against real time; no measured values.', 12, INK2))
    t = 0
    for label, length, paused in segs:
        if paused:
            out.append(f'<rect x="{X(t):.1f}" y="{y0-10}" width="{X(t+length)-X(t):.1f}" height="{y1-y0+10}" fill="{SHADE}"/>')
            out.append(text((X(t) + X(t + length)) / 2, y0 - 18, label + ': paused', 11, INK2, anchor='middle'))
        t += length
    out.append(f'<line x1="{x0}" y1="{y1}" x2="{x1}" y2="{y1}" stroke="{INK2}"/>')
    out.append(f'<line x1="{x0}" y1="{y0-10}" x2="{x0}" y2="{y1}" stroke="{INK2}"/>')
    out.append(text((x0 + x1) / 2, y1 + 20, 'Real time', 11, INK2, anchor='middle'))
    out.append(f'<text x="{x0-14}" y="{(y0+y1)/2}" font-size="11" fill="{INK2}" text-anchor="middle" '
               f'transform="rotate(-90 {x0-14} {(y0+y1)/2})">Ticks</text>')
    # free-running counter: straight line
    out.append(f'<line x1="{X(0):.1f}" y1="{Y(0):.1f}" x2="{X(total):.1f}" y2="{Y(total):.1f}" '
               f'stroke="{ORANGE}" stroke-width="2.5" stroke-dasharray="7 4"/>')
    # shared counter: flat during pauses
    pts, t, v = [(X(0), Y(0))], 0, 0
    for _, length, paused in segs:
        t += length
        if not paused:
            v += length
        pts.append((X(t), Y(v)))
    out.append('<polyline points="' + ' '.join(f'{a:.1f},{b:.1f}' for a, b in pts) +
               f'" fill="none" stroke="{BLUE}" stroke-width="3"/>')
    ly = y1 + 44
    out.append(f'<line x1="{x0}" y1="{ly}" x2="{x0+28}" y2="{ly}" stroke="{BLUE}" stroke-width="3"/>')
    out.append(text(x0 + 34, ly, 'Shared counter: every deadline', 12))
    out.append(f'<line x1="{x0+260}" y1="{ly}" x2="{x0+288}" y2="{ly}" stroke="{ORANGE}" stroke-width="2.5" stroke-dasharray="7 4"/>')
    out.append(text(x0 + 294, ly, 'Free-running counter: waits, never stops', 12))
    write('engine-two-counters.svg', out)


# ------------------------------------------------------------- the timed updates
def timed_updates():
    rows = [
        ('0', 'Blink the portrait being exchanged (inferred)', ENTRIES[0]),
        ('1', 'Advance the flying objects', ENTRIES[1]),
        ('2–5', 'Monster update groups 0 to 3', ENTRIES[2]),
        ('6–11', 'Timers of characters 1 to 6', ENTRIES[6]),
        ('12', 'Advance the moving doors', ENTRIES[12]),
        ('13', 'Animate teleporters and temporary walls', ENTRIES[13]),
        ('14', 'Food', ENTRIES[14]),
        ('15', 'Monster idle animation (inferred)', ENTRIES[15]),
    ]
    after = ['Step-triggered script', 'Timed block scripts', 'Temporary walls']
    W = 700
    top, rh = 96, 34
    H = top + len(rows) * rh + 40 + len(after) * 30 + 30
    desc = ('The timed updates in the order the game checks them at each pass, with their interval in ticks '
            'and whether they are on at the start. Entry 0, blink the portrait being exchanged (an inferred role), every '
            f'{ENTRIES[0][0]} ticks, off until an exchange. Entry 1, flying objects, every {ENTRIES[1][0]}. '
            f'Entries 2 to 5, monster groups, every {ENTRIES[2][0]} until a level sets its own interval. '
            'Entries 6 to 11, character timers, at the next deadline of the character, off until a timer is '
            f'set. Entry 12, doors, every {ENTRIES[12][0]}. Entry 13, teleporter and temporary wall animation, '
            f'every {ENTRIES[13][0]}. Entry 14, food, every {ENTRIES[14][0]}. Entry 15, monster idle animation (an inferred role), '
            f'every {ENTRIES[15][0]}. Then come the step-triggered script, the timed block scripts and the '
            'expiry of temporary walls.')
    out = frame(W, H, 'The timed updates of one pass, in order', desc)
    out.append(text(20, 26, 'The timed updates of one pass, in order', 14, weight=True))
    out.append(text(20, 46, 'Each runs when its deadline has passed, then sets its next one an interval later.', 12, INK2))
    out.append(text(60, 76, 'Entry', 11, INK2, True, 'middle'))
    out.append(text(110, 76, 'Update', 11, INK2, True))
    out.append(text(520, 76, 'Interval', 11, INK2, True, 'middle'))
    out.append(text(625, 76, 'At start', 11, INK2, True, 'middle'))
    for k, (num, label, (interval, enabled)) in enumerate(rows):
        y = top + k * rh
        out.append(f'<rect x="20" y="{y}" width="{W-40}" height="{rh-6}" rx="5" fill="{LIGHT if enabled else SHADE}"/>')
        out.append(text(60, y + (rh - 6) / 2, num, 12, INK, True, 'middle'))
        out.append(text(110, y + (rh - 6) / 2, label, 12))
        iv = 'next deadline' if num == '6–11' else (f'{interval} ticks' if num != '2–5' else f'{interval} or the level’s')
        out.append(text(520, y + (rh - 6) / 2, iv, 12, INK, anchor='middle'))
        out.append(text(625, y + (rh - 6) / 2, 'on' if enabled else 'off', 12, BLUE if enabled else MUTED, True, 'middle'))
    y = top + len(rows) * rh + 14
    out.append(text(20, y, 'Then, in this order:', 12, INK2, True))
    for i, label in enumerate(after):
        yy = y + 22 + i * 30
        out.append(f'<rect x="40" y="{yy-11}" width="300" height="24" rx="5" fill="{SURF}" stroke="{BORDER}"/>')
        out.append(text(54, yy + 1, f'{i + 1}. {label}', 12))
    write('engine-timed-updates.svg', out)


# ------------------------------------------------------------- block events
def block_events():
    sources = [
        ('The party moves', 'leave, enter'),
        ('A monster is placed or leaves a block', 'monster enter, exit'),
        ('An item is dropped or picked up', 'item placed, removed'),
        ('An item is used', 'item used, block in front'),
        ('A wall decoration is used', 'wall decoration'),
        ('A spell is cast', 'spell cast, party block'),
        ('A timed block script is due', 'timer'),
        ('The step limit is reached', 'step count, block [00:00]'),
    ]
    W, top, rh = 700, 84, 44
    H = top + len(sources) * rh + 20
    desc = ('Eight sources send block events to the block event dispatcher: the party moves (leave and enter '
            'events), a monster is placed or leaves a block (monster enter and exit), an item is dropped or '
            'picked up (item placed and removed), an item is used (item used, on the block in front), a wall '
            'decoration is used, a spell is cast (on the party block), a timed block script is due (timer) and '
            'the step limit is reached (step count, on block [00:00]). If the block has a script and accepts the '
            'event, the script runs and can change walls, items, monsters and the party, which can send further '
            'events.')
    out = frame(W, H, 'Who can start a block script', desc)
    out.append(text(20, 26, 'Who can start a block script', 14, weight=True))
    out.append(text(20, 46, 'Each source sends an event to a block; the order of execution is not shown.', 12, INK2))
    bx, bw = 20, 300
    dx, dy, dw, dh = 370, top + len(sources) * rh / 2 - 60, 160, 120
    for k, (who, event) in enumerate(sources):
        y = top + k * rh
        out.append(f'<rect x="{bx}" y="{y}" width="{bw}" height="{rh-8}" rx="6" fill="{LIGHT}" stroke="{BLUE}" stroke-width="1"/>')
        out.append(text(bx + 12, y + 12, who, 12, INK, True))
        out.append(text(bx + 12, y + 27, event, 11, INK2))
        cy = y + (rh - 8) / 2
        out.append(f'<line x1="{bx+bw}" y1="{cy:.1f}" x2="{dx}" y2="{dy + dh/2:.1f}" stroke="{MUTED}" stroke-width="1.2"/>')
    out.append(f'<rect x="{dx}" y="{dy:.1f}" width="{dw}" height="{dh}" rx="8" fill="{SURF}" stroke="{INK2}" stroke-width="1.5"/>')
    for i, line in enumerate(['Block event', 'dispatcher', '', 'runs the script if the', 'block accepts the event']):
        out.append(text(dx + dw / 2, dy + 22 + i * 18, line, 12, INK, i < 2, 'middle'))
    rx = dx + dw + 24
    out.append(f'<line x1="{dx+dw}" y1="{dy+dh/2:.1f}" x2="{rx}" y2="{dy+dh/2:.1f}" stroke="{INK2}" stroke-width="1.5"/>')
    out.append(f'<path d="M{rx-7},{dy+dh/2-5:.1f} L{rx},{dy+dh/2:.1f} L{rx-7},{dy+dh/2+5:.1f} Z" fill="{INK2}"/>')
    out.append(f'<rect x="{rx}" y="{dy+10:.1f}" width="{W-20-rx}" height="{dh-20}" rx="8" fill="{BLUE}"/>')
    for i, line in enumerate(['The script runs:', 'walls, items,', 'monsters, party']):
        out.append(text(rx + (W - 20 - rx) / 2, dy + 38 + i * 20, line, 12, '#ffffff', i == 0, 'middle'))
    out.append(text(rx + (W - 20 - rx) / 2, dy + dh + 18, 'its changes send', 11, INK2, anchor='middle'))
    out.append(text(rx + (W - 20 - rx) / 2, dy + dh + 33, 'further events', 11, INK2, anchor='middle'))
    write('engine-block-events.svg', out)


# ------------------------------------------------------------- one pass
def one_pass():
    steps = [
        ('Party check', 'if no one can act: the defeat sequence'),
        ('Input', 'buttons, then keyboard commands'),
        ('Timed updates that are due', 'in table order; then the step-triggered script,'),
        ('', 'timed block scripts, temporary walls'),
        ('Redraw', 'once, if the view was marked as changed'),
        ('Ambient sound', 'a new one queued when its deadline has passed'),
        ('Sound flush', 'the sound still pending is played'),
    ]
    rows = [(1, 0), (2, 1), (3, 2), (4, 4), (5, 5), (6, 6)]
    W, top, rh = 700, 80, 62
    H = top + len(rows) * rh + 10
    desc = ('One pass of the game loop, in order: 1, party check, which starts the defeat sequence when no one '
            'can act; 2, input, buttons then keyboard commands; 3, the timed updates that are due, in table order, '
            'then the step-triggered script, the timed block scripts and the temporary walls; 4, redraw once if '
            'the view was marked as changed; 5, a new ambient sound queued when its deadline has passed; 6, the '
            'sound still pending is played. Then the next pass starts at once: there is no fixed frame rate.')
    out = frame(W, H, 'One pass of the game loop', desc)
    out.append(text(20, 26, 'One pass of the game loop', 14, weight=True))
    out.append(text(20, 46, 'The next pass starts as soon as this one ends: there is no fixed frame rate.', 12, INK2))
    bx, bw = 60, 520
    for k, (num, idx) in enumerate(rows):
        y = top + k * rh
        title, sub = steps[idx]
        sub2 = steps[idx + 1][1] if idx == 2 else None
        out.append(f'<rect x="{bx}" y="{y}" width="{bw}" height="{rh-16}" rx="8" fill="{LIGHT}" stroke="{BLUE}" stroke-width="1.2"/>')
        out.append(f'<circle cx="{bx}" cy="{y + (rh-16)/2}" r="15" fill="{BLUE}"/>')
        out.append(text(bx, y + (rh - 16) / 2, str(num), 13, '#ffffff', True, 'middle'))
        out.append(text(bx + 28, y + 14, title, 13, INK, True))
        out.append(text(bx + 28, y + 31, sub if not sub2 else f'{sub} {sub2}', 11 if sub2 else 11.5, INK2))
        if k < len(rows) - 1:
            ax = bx + bw / 2
            out.append(f'<line x1="{ax}" y1="{y+rh-16}" x2="{ax}" y2="{y+rh-3}" stroke="{INK2}" stroke-width="1.5"/>')
            out.append(f'<path d="M{ax-5},{y+rh-8} L{ax},{y+rh-1} L{ax+5},{y+rh-8} Z" fill="{INK2}"/>')
    # loop back
    rx = bx + bw + 40
    y_last = top + (len(rows) - 1) * rh + (rh - 16) / 2
    y_first = top + (rh - 16) / 2
    out.append(f'<path d="M{bx+bw},{y_last} H{rx} V{y_first} H{bx+bw+8}" fill="none" stroke="{ORANGE}" stroke-width="2"/>')
    out.append(f'<path d="M{bx+bw+14},{y_first-5} L{bx+bw+6},{y_first} L{bx+bw+14},{y_first+5} Z" fill="{ORANGE}"/>')
    out.append(f'<text x="{rx+14}" y="{(y_first+y_last)/2}" font-size="12" fill="{ORANGE}" font-weight="bold" '
               f'text-anchor="middle" transform="rotate(90 {rx+14} {(y_first+y_last)/2})">next pass</text>')
    write('engine-one-pass.svg', out)


# ------------------------------------------------------------- decision chains
def flows():
    """The decision chains of the engine pages; they transcribe the text of those pages."""
    sys.path[:0] = [str(Path(__file__).resolve().parent), str(ROOT / 'scripts/common')]
    import flowcharts
    flowcharts.chain(
        OUT / 'engine-timed-scripts.svg', 'After the timed updates',
        'At every pass, the step-triggered script, then each timed block script.',
        'What the game checks after the timed updates of a pass. If the step limit is nonzero and the step count '
        'is above it, a step-count event goes to block [00:00] and the step counter returns to 0. Then, for each '
        'timed entry, if the counter has strictly passed its deadline, a timer event goes to its block and its '
        'next deadline becomes the counter plus its interval.',
        [('ask', 'Is the step limit nonzero, with\nthe step count above it?', 'yes',
          'Step-count event to block [00:00];\nthe step counter back to 0', 'in both cases'),
         ('step', 'For each timed entry'),
         ('ask', 'Has the counter strictly passed\nits deadline?', 'yes',
          'Timer event to its block; next\ndeadline = counter + interval', None)],
        'An entry whose deadline has not passed waits for a later pass.')
    flowcharts.chain(
        OUT / 'engine-defeat.svg', 'When no character can act',
        'The check of each pass, and what follows a defeat.',
        'What the game does when no character can act. If any character can act, the pass continues. Otherwise '
        'the game redraws the portraits; if Khelben\'s vision flag is set, it plays the Kheldran scene. It then '
        'offers to load a saved game: refusing returns to DOS; in the load menu, leaving or a failed load '
        'returns to DOS, and a loaded game continues the pass.',
        [('ask', 'Can any character act?', 'yes', 'The pass continues', 'no'),
         ('step', 'Redraw the portraits'),
         ('ask', "Is Khelben's vision flag set?", 'yes', 'The Kheldran scene plays', 'in both cases'),
         ('ask', 'Load a saved game?', 'no', 'Return to DOS', 'yes'),
         ('ask', 'Load menu: is a game loaded?', 'left or failed', 'Return to DOS', 'loaded'),
         ('step', 'The pass continues with the loaded game')])
    flowcharts.chain(
        OUT / 'engine-character-timers.svg', 'Setting a character timer',
        'A character holds its timers in pairs of a deadline and a code.',
        "How a character timer is set. If the character's update is off, pair 0 takes the timer and the update "
        'is switched on for its deadline. Otherwise the update is brought forward if the new deadline is '
        'earlier; then a pair that holds the same code is replaced, so that timer restarts; failing that, the '
        'first free pair takes it; with no free pair, the timer is written before the first pair, which is a bug.',
        [('step', 'Set a timer: a duration and a code'),
         ('ask', "Is the character's update on?", 'no',
          'Pair 0 takes the timer; the update\nis switched on for its deadline', 'yes'),
         ('step', 'The update is brought forward if\nthe new deadline is earlier'),
         ('ask', 'Does a pair hold the same code?', 'yes', 'That pair is replaced:\nthe timer restarts', 'no'),
         ('ask', 'Is a pair free?', 'yes', 'The first free pair takes it', 'no'),
         ('step', 'Written before the first pair: a bug')])


if __name__ == '__main__':
    assert [e[0] for e in ENTRIES] == [9, 3, 20, 20, 20, 20, 50, 50, 50, 50, 50, 50, 5, 10, 1080, 25], ENTRIES
    assert [e[1] for e in ENTRIES] == [False, True] + [True] * 4 + [False] * 6 + [True] * 4
    clock()
    timed_updates()
    block_events()
    one_pass()
    flows()
