1 /* fastmem.c - Memory related functions (fast version without virtual memory)
2 * Copyright (c) 1995-1997 Stefan Jokisch
4 * This file is part of Frotz.
6 * Frotz is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Frotz is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
22 * New undo mechanism added by Jim Dunleavy <jim.dunleavy@erha.ie>
26 * Glk and Blorb support added by Tor Andersson.
36 extern void seed_random (int);
37 extern void restart_screen (void);
38 extern void refresh_text_style (void);
39 extern void call (zword, int, zword *, int);
40 extern void split_window (zword);
41 extern void script_open (void);
42 extern void script_close (void);
44 extern zword save_quetzal (FILE *, FILE *, int);
45 extern zword restore_quetzal (FILE *, FILE *, int);
47 extern void erase_window (zword);
49 extern void (*op0_opcodes[]) (void);
50 extern void (*op1_opcodes[]) (void);
51 extern void (*op2_opcodes[]) (void);
52 extern void (*var_opcodes[]) (void);
57 static FILE *story_fp = NULL;
58 static size_t blorb_ofs = 0;
59 static size_t blorb_len = 0;
62 * Data for the undo mechanism.
63 * This undo mechanism is based on the scheme used in Evin Robertson's
65 * Undo blocks are stored as differences between states.
68 typedef struct undo_struct undo_t;
77 /* undo diff and stack data follow */
80 static undo_t *first_undo = NULL, *last_undo = NULL, *curr_undo = NULL;
81 static zbyte *undo_mem = NULL, *prev_zmp, *undo_diff;
83 static int undo_count = 0;
86 * get_header_extension
88 * Read a value from the header extension (former mouse table).
92 zword get_header_extension (int entry)
97 if (h_extension_table == 0 || entry > hx_table_size)
100 addr = h_extension_table + 2 * entry;
101 LOW_WORD (addr, val);
105 }/* get_header_extension */
108 * set_header_extension
110 * Set an entry in the header extension (former mouse table).
114 void set_header_extension (int entry, zword val)
118 if (h_extension_table == 0 || entry > hx_table_size)
121 addr = h_extension_table + 2 * entry;
122 SET_WORD (addr, val);
124 }/* set_header_extension */
129 * Set all header fields which hold information about the interpreter.
133 void restart_header (void)
142 SET_BYTE (H_CONFIG, h_config);
143 SET_WORD (H_FLAGS, h_flags);
145 if (h_version >= V4) {
146 SET_BYTE (H_INTERPRETER_NUMBER, h_interpreter_number);
147 SET_BYTE (H_INTERPRETER_VERSION, h_interpreter_version);
148 SET_BYTE (H_SCREEN_ROWS, h_screen_rows);
149 SET_BYTE (H_SCREEN_COLS, h_screen_cols);
152 /* It's less trouble to use font size 1x1 for V5 games, especially
153 because of a bug in the unreleased German version of "Zork 1" */
155 if (h_version != V6) {
156 screen_x_size = (zword) h_screen_cols;
157 screen_y_size = (zword) h_screen_rows;
161 screen_x_size = h_screen_width;
162 screen_y_size = h_screen_height;
163 font_x_size = h_font_width;
164 font_y_size = h_font_height;
167 if (h_version >= V5) {
168 SET_WORD (H_SCREEN_WIDTH, screen_x_size);
169 SET_WORD (H_SCREEN_HEIGHT, screen_y_size);
170 SET_BYTE (H_FONT_HEIGHT, font_y_size);
171 SET_BYTE (H_FONT_WIDTH, font_x_size);
172 SET_BYTE (H_DEFAULT_BACKGROUND, h_default_background);
173 SET_BYTE (H_DEFAULT_FOREGROUND, h_default_foreground);
177 for (i = 0; i < 8; i++)
178 storeb ((zword) (H_USER_NAME + i), h_user_name[i]);
180 SET_BYTE (H_STANDARD_HIGH, h_standard_high);
181 SET_BYTE (H_STANDARD_LOW, h_standard_low);
183 }/* restart_header */
188 * Allocate memory and load the story file.
192 void init_memory (void)
204 { SHERLOCK, 21, "871214" },
205 { SHERLOCK, 26, "880127" },
206 { BEYOND_ZORK, 47, "870915" },
207 { BEYOND_ZORK, 49, "870917" },
208 { BEYOND_ZORK, 51, "870923" },
209 { BEYOND_ZORK, 57, "871221" },
210 { ZORK_ZERO, 296, "881019" },
211 { ZORK_ZERO, 366, "890323" },
212 { ZORK_ZERO, 383, "890602" },
213 { ZORK_ZERO, 393, "890714" },
214 { SHOGUN, 292, "890314" },
215 { SHOGUN, 295, "890321" },
216 { SHOGUN, 311, "890510" },
217 { SHOGUN, 322, "890706" },
218 { ARTHUR, 54, "890606" },
219 { ARTHUR, 63, "890622" },
220 { ARTHUR, 74, "890714" },
221 { JOURNEY, 26, "890316" },
222 { JOURNEY, 30, "890322" },
223 { JOURNEY, 77, "890616" },
224 { JOURNEY, 83, "890706" },
225 { LURKING_HORROR, 203, "870506" },
226 { LURKING_HORROR, 219, "870912" },
227 { LURKING_HORROR, 221, "870918" },
228 { UNKNOWN, 0, "------" }
231 /* Open story file */
234 giblorb_result_t res;
235 char magic[4] = "XXXX";
238 if ((file = glkunix_stream_open_pathname(story_name, 0, 0)) == NULL)
239 os_fatal ("Cannot open story file");
241 fread(magic, 1, 4, file);
243 if (!memcmp(magic, "FORM", 4))
245 if (giblorb_set_resource_map(file))
246 os_fatal("This Blorb file seems to be invalid.");
248 map = giblorb_get_resource_map();
250 if (giblorb_load_resource(map, giblorb_method_FilePos,
251 &res, giblorb_ID_Exec, 0))
252 os_fatal("This Blorb file does not contain an executable chunk.");
253 if (res.chunktype != giblorb_make_id('Z','C','O','D'))
254 os_fatal("This Blorb file contains an executable chunk, but it is not a Z-code file.");
257 blorb_ofs = res.data.startpos;
258 blorb_len = res.length;
264 fseek(story_fp, 0, SEEK_END);
265 blorb_len = ftell(story_fp);
271 os_fatal("This file is too small to be a Z-code file.");
273 /* Allocate memory for story header */
275 if ((zmp = (zbyte *) malloc (64)) == NULL)
276 os_fatal ("Out of memory");
278 /* Load header into memory */
280 fseek(story_fp, blorb_ofs, 0);
282 if (fread (zmp, 1, 64, story_fp) != 64)
283 os_fatal ("Story file read error");
285 /* Copy header fields to global variables */
287 LOW_BYTE (H_VERSION, h_version);
289 if (h_version < V1 || h_version > V8)
290 os_fatal ("Unknown Z-code version");
293 os_fatal ("Cannot play Z-code version 6");
295 LOW_BYTE (H_CONFIG, h_config);
297 if (h_version == V3 && (h_config & CONFIG_BYTE_SWAPPED))
298 os_fatal ("Byte swapped story file");
300 LOW_WORD (H_RELEASE, h_release);
301 LOW_WORD (H_RESIDENT_SIZE, h_resident_size);
302 LOW_WORD (H_START_PC, h_start_pc);
303 LOW_WORD (H_DICTIONARY, h_dictionary);
304 LOW_WORD (H_OBJECTS, h_objects);
305 LOW_WORD (H_GLOBALS, h_globals);
306 LOW_WORD (H_DYNAMIC_SIZE, h_dynamic_size);
307 LOW_WORD (H_FLAGS, h_flags);
309 for (i = 0, addr = H_SERIAL; i < 6; i++, addr++)
310 LOW_BYTE (addr, h_serial[i]);
312 /* Auto-detect buggy story files that need special fixes */
316 for (i = 0; records[i].story_id != UNKNOWN; i++) {
318 if (h_release == records[i].release) {
320 for (j = 0; j < 6; j++)
321 if (h_serial[j] != records[i].serial[j])
324 story_id = records[i].story_id;
328 no_match: ; /* null statement */
332 LOW_WORD (H_ABBREVIATIONS, h_abbreviations);
333 LOW_WORD (H_FILE_SIZE, h_file_size);
335 /* Calculate story file size in bytes */
337 if (h_file_size != 0) {
339 story_size = (long) 2 * h_file_size;
346 } else { /* some old games lack the file size entry */
348 story_size = blorb_len;
351 LOW_WORD (H_CHECKSUM, h_checksum);
352 LOW_WORD (H_ALPHABET, h_alphabet);
353 LOW_WORD (H_FUNCTIONS_OFFSET, h_functions_offset);
354 LOW_WORD (H_STRINGS_OFFSET, h_strings_offset);
355 LOW_WORD (H_TERMINATING_KEYS, h_terminating_keys);
356 LOW_WORD (H_EXTENSION_TABLE, h_extension_table);
358 /* Zork Zero Macintosh doesn't have the graphics flag set */
360 if (story_id == ZORK_ZERO && h_release == 296)
361 h_flags |= GRAPHICS_FLAG;
363 /* Adjust opcode tables */
365 if (h_version <= V4) {
366 op0_opcodes[0x09] = z_pop;
367 op1_opcodes[0x0f] = z_not;
369 op0_opcodes[0x09] = z_catch;
370 op1_opcodes[0x0f] = z_call_n;
373 /* Allocate memory for story data */
375 if ((zmp = (zbyte *) realloc (zmp, story_size)) == NULL)
376 os_fatal ("Out of memory");
378 /* Load story file in chunks of 32KB */
382 for (size = 64; size < story_size; size += n) {
384 if (story_size - size < 0x8000)
385 n = (unsigned) (story_size - size);
389 if (fread (pcp, 1, n, story_fp) != n)
390 os_fatal ("Story file read error");
394 /* Read header extension table */
396 hx_table_size = get_header_extension (HX_TABLE_SIZE);
397 hx_unicode_table = get_header_extension (HX_UNICODE_TABLE);
404 * Allocate memory for multiple undo. It is important not to occupy
405 * all the memory available, since the IO interface may need memory
406 * during the game, e.g. for loading sounds or pictures.
410 void init_undo (void)
414 reserved = NULL; /* makes compilers shut up */
416 if (reserve_mem != 0) {
417 if ((reserved = malloc (reserve_mem)) == NULL)
421 /* Allocate h_dynamic_size bytes for previous dynamic zmp state
422 + 1.5 h_dynamic_size for Quetzal diff + 2. */
423 undo_mem = malloc ((h_dynamic_size * 5) / 2 + 2);
424 if (undo_mem != NULL) {
426 undo_diff = undo_mem + h_dynamic_size;
427 memcpy (prev_zmp, zmp, h_dynamic_size);
429 f_setup.undo_slots = 0;
431 if (reserve_mem != 0)
439 * Free count undo blocks from the beginning of the undo list.
443 static void free_undo (int count)
447 if (count > undo_count)
451 if (curr_undo == first_undo)
452 curr_undo = curr_undo->next;
453 first_undo = first_undo->next;
458 first_undo->prev = NULL;
466 * Close the story file and deallocate memory.
470 void reset_memory (void)
479 free_undo (undo_count);
494 * Write a byte value to the dynamic Z-machine memory.
498 void storeb (zword addr, zbyte value)
501 if (addr >= h_dynamic_size)
502 runtime_error (ERR_STORE_RANGE);
504 if (addr == H_FLAGS + 1) { /* flags register is modified */
506 h_flags &= ~(SCRIPTING_FLAG | FIXED_FONT_FLAG);
507 h_flags |= value & (SCRIPTING_FLAG | FIXED_FONT_FLAG);
509 if (value & SCRIPTING_FLAG) {
517 /* TOR - glkified / refresh_text_style (); */
521 SET_BYTE (addr, value);
528 * Write a word value to the dynamic Z-machine memory.
532 void storew (zword addr, zword value)
535 storeb ((zword) (addr + 0), hi (value));
536 storeb ((zword) (addr + 1), lo (value));
541 * z_restart, re-load dynamic area, clear the stack and set the PC.
547 void z_restart (void)
549 static bool first_restart = TRUE;
553 os_restart_game (RESTART_BEGIN);
557 if (!first_restart) {
559 fseek (story_fp, blorb_ofs, SEEK_SET);
561 if (fread (zmp, 1, h_dynamic_size, story_fp) != h_dynamic_size)
562 os_fatal ("Story file read error");
564 } else first_restart = FALSE;
569 sp = fp = stack + STACK_SIZE;
572 if (h_version != V6) {
574 long pc = (long) h_start_pc;
577 } else call (h_start_pc, 0, NULL, 0);
579 os_restart_game (RESTART_END);
584 * z_restore, restore [a part of] a Z-machine state from disk
586 * zargs[0] = address of area to restore (optional)
587 * zargs[1] = number of bytes to restore
588 * zargs[2] = address of suggested file name
592 void z_restore (void)
600 /* Get the file name */
602 /* Open auxilary file */
604 if ((gfp = frotzopenprompt(FILE_LOAD_AUX)) == NULL)
607 /* Load auxilary file */
609 success = fread (zmp + zargs[0], 1, zargs[1], gfp);
611 /* Close auxilary file */
624 if ((gfp = frotzopenprompt(FILE_RESTORE)) == NULL)
627 if (f_setup.save_quetzal) {
628 success = restore_quetzal (gfp, story_fp, blorb_ofs);
633 release = (unsigned) fgetc (gfp) << 8;
634 release |= fgetc (gfp);
639 /* Check the release number */
641 if (release == h_release) {
643 pc = (long) fgetc (gfp) << 16;
644 pc |= (unsigned) fgetc (gfp) << 8;
649 sp = stack + (fgetc (gfp) << 8);
651 fp = stack + (fgetc (gfp) << 8);
654 for (i = (int) (sp - stack); i < STACK_SIZE; i++) {
655 stack[i] = (unsigned) fgetc (gfp) << 8;
656 stack[i] |= fgetc (gfp);
659 fseek (story_fp, blorb_ofs, SEEK_SET);
661 for (addr = 0; addr < h_dynamic_size; addr++) {
662 int skip = fgetc (gfp);
663 for (i = 0; i < skip; i++)
664 zmp[addr++] = fgetc (story_fp);
665 zmp[addr] = fgetc (gfp);
666 (void) fgetc (story_fp);
669 /* Check for errors */
671 if (ferror (gfp) || ferror (story_fp) || addr != h_dynamic_size)
679 } else print_string ("Invalid save file\n");
682 if ((short) success >= 0) {
684 /* Close game file */
688 if ((short) success > 0) {
689 zbyte old_screen_rows;
690 zbyte old_screen_cols;
692 /* In V3, reset the upper window. */
696 LOW_BYTE (H_SCREEN_ROWS, old_screen_rows);
697 LOW_BYTE (H_SCREEN_COLS, old_screen_cols);
699 /* Reload cached header fields. */
703 * Since QUETZAL files may be saved on many different machines,
704 * the screen sizes may vary a lot. Erasing the status window
705 * seems to cover up most of the resulting badness.
707 if (h_version > V3 && h_version != V6
708 && (h_screen_rows != old_screen_rows
709 || h_screen_cols != old_screen_cols))
713 os_fatal ("Error reading save file");
728 * Set diff to a Quetzal-like difference between a and b,
729 * copying a to b as we go. It is assumed that diff points to a
730 * buffer which is large enough to hold the diff.
731 * mem_size is the number of bytes to compare.
732 * Returns the number of bytes copied to diff.
736 static long mem_diff (zbyte *a, zbyte *b, zword mem_size, zbyte *diff)
738 unsigned size = mem_size;
744 for (j = 0; size > 0 && (c = *a++ ^ *b++) == 0; j++)
746 if (size == 0) break;
760 *p++ = (j & 0x7f) | 0x80;
761 *p++ = (j & 0x7f80) >> 7;
773 * Applies a quetzal-like diff to dest
777 static void mem_undiff (zbyte *diff, long diff_length, zbyte *dest)
781 while (diff_length) {
788 return; /* Incomplete run */
793 return; /* Incomplete extended run */
796 runlen = (runlen & 0x7f) | (((unsigned) c) << 7);
809 * This function does the dirty work for z_restore_undo.
813 int restore_undo (void)
816 if (f_setup.undo_slots == 0) /* undo feature unavailable */
820 if (curr_undo == NULL) /* no saved game state */
826 memcpy (zmp, prev_zmp, h_dynamic_size);
827 SET_PC (curr_undo->pc);
828 sp = stack + STACK_SIZE - curr_undo->stack_size;
829 fp = stack + curr_undo->frame_offset;
830 frame_count = curr_undo->frame_count;
831 mem_undiff ((zbyte *) (curr_undo + 1), curr_undo->diff_size, prev_zmp);
832 memcpy (sp, (zbyte *)(curr_undo + 1) + curr_undo->diff_size,
833 curr_undo->stack_size * sizeof (*sp));
835 curr_undo = curr_undo->prev;
844 * z_restore_undo, restore a Z-machine state from memory.
850 void z_restore_undo (void)
853 store ((zword) restore_undo ());
855 }/* z_restore_undo */
858 * z_save, save [a part of] the Z-machine state to disk.
860 * zargs[0] = address of memory area to save (optional)
861 * zargs[1] = number of bytes to save
862 * zargs[2] = address of suggested file name
874 /* Open auxilary file */
876 if ((gfp = frotzopenprompt (FILE_SAVE_AUX)) == NULL)
879 /* Write auxilary file */
881 success = fwrite (zmp + zargs[0], zargs[1], 1, gfp);
883 /* Close auxilary file */
897 if ((gfp = frotzopenprompt (FILE_SAVE)) == NULL)
900 if (f_setup.save_quetzal) {
901 success = save_quetzal (gfp, story_fp, blorb_ofs);
903 /* Write game file */
905 fputc ((int) hi (h_release), gfp);
906 fputc ((int) lo (h_release), gfp);
907 fputc ((int) hi (h_checksum), gfp);
908 fputc ((int) lo (h_checksum), gfp);
912 fputc ((int) (pc >> 16) & 0xff, gfp);
913 fputc ((int) (pc >> 8) & 0xff, gfp);
914 fputc ((int) (pc) & 0xff, gfp);
916 nsp = (int) (sp - stack);
917 nfp = (int) (fp - stack);
919 fputc ((int) hi (nsp), gfp);
920 fputc ((int) lo (nsp), gfp);
921 fputc ((int) hi (nfp), gfp);
922 fputc ((int) lo (nfp), gfp);
924 for (i = nsp; i < STACK_SIZE; i++) {
925 fputc ((int) hi (stack[i]), gfp);
926 fputc ((int) lo (stack[i]), gfp);
929 fseek (story_fp, blorb_ofs, SEEK_SET);
931 for (addr = 0, skip = 0; addr < h_dynamic_size; addr++)
932 if (zmp[addr] != fgetc (story_fp) || skip == 255 || addr + 1 == h_dynamic_size) {
934 fputc (zmp[addr], gfp);
939 /* Close game file and check for errors */
941 if (fclose (gfp) == EOF || ferror (story_fp)) {
942 print_string ("Error writing save file\n");
964 * This function does the dirty work for z_save_undo.
974 if (f_setup.undo_slots == 0) /* undo feature unavailable */
977 /* save undo possible */
979 while (last_undo != curr_undo) {
981 last_undo = last_undo->prev;
986 last_undo->next = NULL;
990 if (undo_count == f_setup.undo_slots)
993 diff_size = mem_diff (zmp, prev_zmp, h_dynamic_size, undo_diff);
994 stack_size = stack + STACK_SIZE - sp;
996 p = malloc (sizeof (undo_t) + diff_size + stack_size * sizeof (*sp));
999 } while (!p && undo_count);
1003 p->frame_count = frame_count;
1004 p->diff_size = diff_size;
1005 p->stack_size = stack_size;
1006 p->frame_offset = fp - stack;
1007 memcpy (p + 1, undo_diff, diff_size);
1008 memcpy ((zbyte *)(p + 1) + diff_size, sp, stack_size * sizeof (*sp));
1014 last_undo->next = p;
1015 p->prev = last_undo;
1018 curr_undo = last_undo = p;
1025 * z_save_undo, save the current Z-machine state for a future undo.
1031 void z_save_undo (void)
1034 store ((zword) save_undo ());
1039 * z_verify, check the story file integrity.
1045 void z_verify (void)
1050 /* Sum all bytes in story file except header bytes */
1052 fseek (story_fp, blorb_ofs + 64, SEEK_SET);
1054 for (i = 64; i < story_size; i++)
1055 checksum += fgetc (story_fp);
1057 /* Branch if the checksums are equal */
1059 branch (checksum == h_checksum);