To provide routines handling low-level Z-machine facilities.


§1. Begin Z-only matter.

#Ifdef TARGET_ZCODE;

§2. Summary. This segment closely parallels "Glulx.i6t", which provides exactly equivalent functionality (indeed, usually the same-named functions and in the same order) for the Glulx VM. This is intended to make the rest of the template code independent of the choice of VM, although that is more of an ideal than a reality, because there are so many fiddly differences in some of the grammar and dictionary tables that it is not really practical for the parser (for instance) to call VM-neutral routines to get the data it wants out of these arrays.

§3. Variables and Arrays.

Global xcommsdir; true if command recording is on
Global transcript_mode; true if game scripting is on

Constant INPUT_BUFFER_LEN = 120; Length of buffer array

Array  buffer    -> 123;            Buffer for parsing main line of input
Array  buffer2   -> 123;            Buffers for supplementary questions
Array  buffer3   -> 123;            Buffer retaining input for "again"
Array  parse     buffer 63;         Parse table mirroring it
Array  parse2    buffer 63;         

Global dict_start;
Global dict_entry_size;
Global dict_end;

§4. Release Number. Like all software, IF story files have release numbers to mark revised versions being circulated: unlike most software, and partly for traditional reasons, the version number is recorded not in some print statement or variable but is branded on, so to speak, in a specific memory location of the story file header.

VM_Describe_Release() describes the release and is used as part of the "banner", IF's equivalent to a title page.

[ VM_Describe_Release i;
    print "Release ", (HDR_GAMERELEASE-->0) & $03ff, " / Serial number ";
    for (i=0 : i<6 : i++) print (char) HDR_GAMESERIAL->i;
];

§5. Keyboard Input. The VM must provide three routines for keyboard input:

There are elaborations to due with mouse clicks, but this isn't the place to document all of that.

[ VM_KeyChar win  key;
    if (win) @set_window win;
    @read_char 1 -> key;
    return key;
];

[ VM_KeyDelay tenths  key;
    @read_char 1 tenths VM_KeyDelay_Interrupt -> key;
    return key;
];
[ VM_KeyDelay_Interrupt; rtrue; ];

[ VM_ReadKeyboard  a_buffer a_table i;
    read a_buffer a_table;
    if (KIT_CONFIGURATION_BITMAP & ECHO_COMMANDS_TCBIT) {
        print "** ";
        for (i=2: i<=(a_buffer->1)+1: i++) print (char) a_buffer->i;
        print "^";
    }
];

§6. Buffer Functions. A "buffer", in this sense, is an array containing a stream of characters typed from the keyboard; a "parse buffer" is an array which resolves this into individual words, pointing to the relevant entries in the dictionary structure. Because each VM has its own format for each of these arrays (not to mention the dictionary), we have to provide some standard operations needed by the rest of the template as routines for each VM.

The Z-machine buffer and parse buffer formats are documented in the DM4.

VM_CopyBuffer(to, from) copies one buffer into another.

VM_Tokenise(buff, parse_buff) takes the text in the buffer buff and produces the corresponding data in the parse buffer parse_buff — this is called tokenisation since the characters are divided into words: in traditional computing jargon, such clumps of characters treated syntactically as units are called tokens.

LTI_Insert is documented in the DM4 and the LTI prefix stands for "Language To Informese": it's used only by translations into non-English languages of play, and is not called in the template.

[ VM_CopyBuffer bto bfrom i;
    for (i=0: i<INPUT_BUFFER_LEN: i++) bto->i = bfrom->i;
];

[ VM_PrintToBuffer buf len a b c;
    @output_stream 3 buf;
    switch (metaclass(a)) {
        String: print (string) a;
        Routine: a(b, c);
        Object, Class: if (b) PrintOrRun(a, b, true); else print (name) a;
    }
    @output_stream -3;
    if (buf-->0 > len) print "Error: Overflow in VM_PrintToBuffer.^";
    return buf-->0;
];

[ VM_Tokenise b p; b->(2 + b->1) = 0; @tokenise b p; ];

[ LTI_Insert i ch  b y;
    Protect us from strict mode, as this isn't an array in quite the
    sense it expects
    b = buffer;

    Insert character ch into buffer at point i.
    Being careful not to let the buffer possibly overflow:
    y = b->1;
    if (y > b->0) y = b->0;

    Move the subsequent text along one character:
    for (y=y+2 : y>i : y--) b->y = b->(y-1);
    b->i = ch;

    And the text is now one character longer:
    if (b->1 < b->0) (b->1)++;
];

§7. Dictionary Functions. Again, the dictionary structure is differently arranged on the different VMs. This is a data structure containing, in compressed form, the text of all the words to be recognised by tokenisation (above). In I6 for Z, a dictionary word value is represented at run-time by its record number in the dictionary, 0, 1, 2, ..., in alphabetical order.

VM_InvalidDictionaryAddress(A) tests whether A is a valid record address in the dictionary data structure.

VM_DictionaryAddressToNumber(A) and VM_NumberToDictionaryAddress(N) convert between record numbers and dictionary addresses.

[ VM_InvalidDictionaryAddress addr;
    if ((UnsignedCompare(addr, dict_start) < 0) ||
        (UnsignedCompare(addr, dict_end) >= 0) ||
        ((addr - dict_start) % dict_entry_size ~= 0)) rtrue;
    rfalse;
];

[ VM_DictionaryAddressToNumber w; return (w-(HDR_DICTIONARY-->0 + 7))/9; ];
[ VM_NumberToDictionaryAddress n; return HDR_DICTIONARY-->0 + 7 + 9*n; ];

§8. Command Tables. The VM is also generated containing a data structure for the grammar produced by I6's Verb and Extend directives: this is essentially a list of command verbs such as DROP or PUSH, together with a list of synonyms, and then the grammar for the subsequent commands to be recognised by the parser.

[ VM_CommandTableAddress i;
    return (HDR_STATICMEMORY-->0)-->i;
];

[ VM_PrintCommandWords i da j;
    da = HDR_DICTIONARY-->0;
    for (j=0 : j<(da+5)-->0 : j++)
        if (da->(j*9 + 14) == $ff-i)
            print "'", (address) VM_NumberToDictionaryAddress(j), "' ";
];

§9. RNG. No routine is needed for extracting a random number, since I6's built-in random function does that, but it's useful to abstract the process of seeding the RNG so that it produces a repeatable sequence of "random" numbers from here on: the necessary opcodes are different for the two VMs.

[ VM_Seed_RNG n;
    if (n > 0) n = -n;
    @random n -> n;
];

§10. Memory Allocation. This is dynamic memory allocation: something which is never practicable in the Z-machine, because the whole address range is already claimed, but which is viable on recent revisions of Glulx.

[ VM_AllocateMemory amount;
    return 0;
];

[ VM_FreeMemory address;
];

§11. Audiovisual Resources. The Z-machine only barely supports figures and sound effects, and only in version 6 of the Z-machine, which Inform 7 no longer supports. Sound effects have a longer pedigree and Infocom used them on some version 5 and even some version 3 works: really, though, from an Inform point of view we would prefer that anyone needing figures and sounds use Glulx instead. (Inform 6 remains available for those who really need to make audiovisual effects in these long-gone formats.)

[ VM_Picture resource_ID;
];

[ VM_SoundEffect resource_ID;
];

§12. Typography. Relatively few typographic effects are available on the Z-machine, so that many of the semantic markups for text which would be distinguishable on Glulx are indistinguishable here.

[ VM_Style sty;
    switch (sty) {
        NORMAL_VMSTY, NOTE_VMSTY: style roman;
        HEADER_VMSTY, SUBHEADER_VMSTY, ALERT_VMSTY: style bold;
    }
];

§13. Character Casing. The following are the equivalent of tolower and toupper, the traditional C library functions for forcing letters into lower and upper case form, for the ZSCII character set.

[ VM_UpperToLowerCase c;
    if (c < 'A') return c;
    if (c <= 'Z') return c + 32;
    if (c < 158) return c;
    if (c <= 160) return c - 3;
    if (c < 167) return c;
    if (c <= 168) return c - 3;
    if (c < 175) return c;
    if (c <= 180) return c - 6;
    if (c < 186) return c;
    if (c <= 190) return c - 5;
    if (c < 196) return c;
    if (c <= 200) return c - 5;
    if (c == 202) return c - 1;
    if (c == 204) return c - 1;
    if (c < 208) return c;
    if (c <= 210) return c - 3;
    if (c == 212) return c - 1;
    if (c == 214) return c - 1;
    if (c == 217) return c - 2;
    if (c == 218) return c - 2;
    if (c == 221) return c - 1;
    return c;
];

[ VM_LowerToUpperCase c;
    if (c < 'a') return c;
    if (c <= 'z') return c - 32;
    if (c < 155) return c;
    if (c <= 157) return c + 3;
    if (c < 164) return c;
    if (c <= 165) return c + 3;
    if (c < 169) return c;
    if (c <= 174) return c + 6;
    if (c < 181) return c;
    if (c <= 185) return c + 5;
    if (c < 191) return c;
    if (c <= 195) return c + 5;
    if (c == 201) return c + 1;
    if (c == 203) return c + 1;
    if (c < 205) return c;
    if (c <= 207) return c + 3;
    if (c == 211) return c + 1;
    if (c == 213) return c + 1;
    if (c == 215) return c + 2;
    if (c == 216) return c + 2;
    if (c == 220) return c + 1;
    return c;
];

§14. The Screen. Our generic screen model is that the screen is made up of windows: we tend to refer only to two of these, the main window and the status line, but others may also exist from time to time. Windows have unique ID numbers: the special window ID \(-1\) means "all windows" or "the entire screen", which usually amounts to the same thing.

Screen height and width are measured in characters, with respect to the fixed-pitch font used for the status line. The main window normally contains variable-pitch text which may even have been kerned, and character dimensions make little sense there.

Clearing all windows (WIN_ALL here) has the side-effect of collapsing the status line, so we need to ensure that statuswin_cursize is reduced to 0, in order to keep it accurate.

[ VM_ClearScreen window;
    switch (window) {
        WIN_ALL:    @erase_window -1; statuswin_cursize = 0;
        WIN_STATUS: @erase_window 1;
        WIN_MAIN:   @erase_window 0;
    }
];

[ VM_ScreenWidth  width charw; return (HDR_SCREENWCHARS->0); ];

[ VM_ScreenHeight; return (HDR_SCREENHLINES->0); ];

§15. Window Colours. Each window can have its own foreground and background colours.

The colour of individual letters or words of type is not controllable in Glulx, to the frustration of many, and so the template layer of I7 has no framework for handling this (even though it is controllable on the Z-machine, which is greatly superior in this respect).

[ VM_SetWindowColours f b window;
    if (clr_on && f && b) {
        if (window == 0) {  if setting both together, set reverse
            clr_fgstatus = b;
            clr_bgstatus = f;
            }
        if (window == 1) {
            clr_fgstatus = f;
            clr_bgstatus = b;
        }
        if (window == 0 or 2) {
            clr_fg = f;
            clr_bg = b;
        }
        if (statuswin_current)
            @set_colour clr_fgstatus clr_bgstatus;
        else
            @set_colour clr_fg clr_bg;
    }
];

[ VM_RestoreWindowColours; compare I6 library patch L61007
    if (clr_on) { check colour has been used
        VM_SetWindowColours(clr_fg, clr_bg, 2); make sure both sets of variables are restored
        VM_SetWindowColours(clr_fgstatus, clr_bgstatus, 1, true);
        VM_ClearScreen();
    }
];

§16. Main Window. The part of the screen on which commands and responses are printed, which ordinarily occupies almost all of the screen area.

VM_MainWindow() switches printing back from another window, usually the status line, to the main window. Note that the Z-machine implementation emulates the Glulx model of window rather than text colours.

[ VM_MainWindow;
    if (statuswin_current) {
        if (clr_on && clr_bgstatus > 1) @set_colour clr_fg clr_bg;
        else style roman;
        @set_window 0;
    }
    statuswin_current = false;
];

§17. Status Line. Despite the name, the status line need not be a single line at the top of the screen: that's only the conventional default arrangement. It can expand to become the equivalent of an old-fashioned VT220 terminal, with menus and grids and mazes displayed lovingly in character graphics, or it can close up to invisibility.

VM_StatusLineHeight(n) sets the status line to have a height of n lines of type. (The width of the status line is always the width of the whole screen, and the position is always at the top, so the height is the only controllable aspect.) The \(n=0\) case makes the status line disappear.

VM_MoveCursorInStatusLine(x, y) switches printing to the status line, positioning the "cursor" — the position at which printing will begin — at the given character grid position \((x, y)\). Line 1 represents the top line; line 2 is underneath, and so on; columns are similarly numbered from 1 at the left.

[ VM_MoveCursorInStatusLine line column; 1-based position on text grid
    if (~~statuswin_current) {
         @set_window 1;
         if (clr_on && clr_bgstatus > 1) @set_colour clr_fgstatus clr_bgstatus;
         else                            style reverse;
    }
    if (line == 0) {
        line = 1;
        column = 1;
    }
    @set_cursor line column;
    statuswin_current = true;
];

[ VM_StatusLineHeight height  wx wy x y charh;
    if (statuswin_cursize ~= height)
        @split_window height;
    statuswin_cursize = height;
];

§18. Quotation Boxes. No routine is needed to produce quotation boxes: the I6 box statement generates the necessary Z-machine opcodes all by itself.

§19. Undo. These simply wrap the relevant opcodes.

[ VM_Undo result_code;
    @restore_undo result_code;
    return result_code;
];

[ VM_Save_Undo result_code;
    @save_undo result_code;
    return result_code;
];

§20. Veneer.

[ Unsigned__Compare x y u v;
    @je x y ?rfalse; i.e., return 0
    @jl x 0 ?XNegative;
    So here x >= 0 and x ~= y
    @jl y 0 ?XPosYNeg;

    Here x >=0, y >= 0, x ~= y

    @jg x y ?rtrue; i.e., return 1
    @ret -1;

    .XPosYNeg;
    Here x >= 0, y < 0, x ~= y
    @ret -1;

    .XNegative;
    @jl y 0 ?~rtrue; if x < 0, y >= 0, return 1

    Here x < 0, y < 0, x ~= y
    @jg x y ?rtrue;
    @ret -1;
];

[ RT__ChLDW base offset;
    @loadw base offset -> sp;
    @ret sp;
];

§21. End Z-only matter.

#Endif; TARGET_ZCODE