Debian Codegraph @

terps/plus/plusmain.c

raw symbols SCIP
1 //
2 // plusmain.c
3 // The Plus interpreter
4 //
5 // Created by Petter Sjölund on 2022-05-06.
6 //
7
8 #include <ctype.h>
9 #include <math.h>
10 #include <stdarg.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <time.h>
15
16 #include "glk.h"
17 #ifdef SPATTERLIGHT
18 #include "glkimp.h"
19 #endif
20 #include "glkstart.h"
21
22 #include "animations.h"
23 #include "apple2detect.h"
24 #include "atari8detect.h"
25 #include "c64detect.h"
26 #include "common.h"
27 #include "definitions.h"
28 #include "gameinfo.h"
29 #include "graphics.h"
30 #include "layouttext.h"
31 #include "loaddatabase.h"
32 #include "parseinput.h"
33 #include "restorestate.h"
34 #include "stdetect.h"
35
36 const char *game_file = NULL;
37 char *DirPath = ".";
38 size_t DirPathLength = 1;
39
40 uint8_t *mem;
41 size_t memlen;
42
43 const char *sys[MAX_SYSMESS];
44
45 uint64_t BitFlags = 0;
46 int Options; /* Option flags set */
47
48 int split_screen = 1;
49 int lastwasnewline = 1;
50 int pendingcomma = 0;
51 int should_restart = 0;
52
53 glui32 TopWidth, TopHeight;
54
55 winid_t Bottom, Top, Graphics;
56
57 strid_t Transcript = NULL;
58
59 struct GameInfo *Game = NULL;
60
61 SystemType CurrentSys = SYS_UNKNOWN;
62
63 uint16_t header[64];
64
65 int16_t Counters[64]; /* Range unknown */
66 #define MAX_LOOPS 32
67
68 int loops[MAX_LOOPS];
69 int loop_index;
70 int keep_going = 0;
71 int startover = 0;
72 int found_match = 0;
73
74 /* JustStarted is only used for the error message "Can't undo on first move" */
75 int JustStarted = 1;
76
77 /* JustRestarted is only used to adjust newlines and room descriptions in the transcript */
78 extern int JustRestarted;
79
80 int showing_inventory = 0;
81
82 Header GameHeader;
83 Item *Items;
84 Room *Rooms;
85
86 ObjectImage *ObjectImages;
87 char **Messages;
88 Action *Actions;
89
90 int ImageWidth = 280;
91 int ImageHeight = 158;
92
93 glui32 TimerRate = 0;
94
95 static char DelimiterChar = '_';
96
97 GLK_ATTRIBUTE_NORETURN void CleanupAndExit(void)
98 {
99 if (Transcript)
100 glk_stream_close(Transcript, NULL);
101 glk_exit();
102 }
103
104 GLK_ATTRIBUTE_NORETURN void Fatal(const char *x)
105 {
106 fprintf(stderr, "%s!\n", x);
107 if (Bottom)
108 Display(Bottom, "%s\n", x);
109 CleanupAndExit();
110 }
111
112 void *MemAlloc(size_t size)
113 {
114 void *t = (void *)malloc(size);
115 if (t == NULL)
116 Fatal("Out of memory");
117 return (t);
118 }
119
120 void SetBit(int bit)
121 {
122 BitFlags |= (uint64_t)1 << bit;
123 }
124
125 void ResetBit(int bit)
126 {
127 BitFlags &= ~((uint64_t)1 << bit);
128 }
129
130 int IsSet(int bit)
131 {
132 return ((BitFlags & ((uint64_t)1 << bit)) != 0);
133 }
134
135 static strid_t room_description_stream = NULL;
136
137 void Display(winid_t w, const char *fmt, ...)
138 {
139 va_list ap;
140 char msg[2048];
141
142 int size = sizeof msg;
143
144 va_start(ap, fmt);
145 vsnprintf(msg, size, fmt, ap);
146 va_end(ap);
147
148 glk_put_string_stream(glk_window_get_stream(w), msg);
149 }
150
151 static const glui32 OptimalPictureSize(glui32 *width, glui32 *height)
152 {
153 int w = ImageWidth;
154 int h = ImageHeight;
155
156 *width = w;
157 *height = h;
158 int multiplier = 1;
159 glui32 graphwidth, graphheight;
160 glk_window_get_size(Graphics, &graphwidth, &graphheight);
161 multiplier = graphheight / h;
162 if (w * multiplier > graphwidth)
163 multiplier = graphwidth / w;
164
165 if (multiplier == 0)
166 multiplier = 1;
167
168 *width = w * multiplier;
169 *height = h * multiplier;
170
171 return multiplier;
172 }
173
174 static winid_t FindGlkWindowWithRock(glui32 rock);
175
176 void OpenGraphicsWindow(void)
177 {
178 if (!IsSet(GRAPHICSBIT))
179 return;
180 glui32 graphwidth, graphheight, optimal_width, optimal_height;
181 y_offset = 0;
182
183 if (Top == NULL)
184 Top = FindGlkWindowWithRock(GLK_STATUS_ROCK);
185 if (Graphics == NULL)
186 Graphics = FindGlkWindowWithRock(GLK_GRAPHICS_ROCK);
187 if (Graphics == NULL && Top != NULL) {
188 glk_window_get_size(Top, &TopWidth, &TopHeight);
189 glk_window_close(Top, NULL);
190 Graphics = glk_window_open(Bottom, winmethod_Above | winmethod_Proportional,
191 60, wintype_Graphics, GLK_GRAPHICS_ROCK);
192 glk_window_get_size(Graphics, &graphwidth, &graphheight);
193 pixel_size = OptimalPictureSize(&optimal_width, &optimal_height);
194 x_offset = ((int)graphwidth - (int)optimal_width) / 2;
195
196 if (graphheight > optimal_height) {
197 winid_t parent = glk_window_get_parent(Graphics);
198 glk_window_set_arrangement(parent, winmethod_Above | winmethod_Fixed,
199 optimal_height, NULL);
200 }
201
202 /* Set the graphics window background to match
203 * the main window background, best as we can,
204 * and clear the window.
205 */
206 glui32 background_color;
207 if (glk_style_measure(Bottom, style_Normal, stylehint_BackColor,
208 &background_color)) {
209 glk_window_set_background_color(Graphics, background_color);
210 glk_window_clear(Graphics);
211 }
212
213 Top = glk_window_open(Bottom, winmethod_Above | winmethod_Fixed, TopHeight,
214 wintype_TextGrid, GLK_STATUS_ROCK);
215 glk_window_get_size(Top, &TopWidth, &TopHeight);
216 } else {
217 if (!Graphics)
218 Graphics = glk_window_open(Bottom, winmethod_Above | winmethod_Proportional, 60,
219 wintype_Graphics, GLK_GRAPHICS_ROCK);
220 glk_window_get_size(Graphics, &graphwidth, &graphheight);
221 pixel_size = OptimalPictureSize(&optimal_width, &optimal_height);
222 x_offset = (graphwidth - optimal_width) / 2;
223 winid_t parent = glk_window_get_parent(Graphics);
224 if (parent)
225 glk_window_set_arrangement(parent, winmethod_Above | winmethod_Fixed,
226 optimal_height, NULL);
227 }
228
229 right_margin = optimal_width + x_offset;
230 }
231
232 void CloseGraphicsWindow(void)
233 {
234 if (Graphics == NULL)
235 Graphics = FindGlkWindowWithRock(GLK_GRAPHICS_ROCK);
236 if (Graphics) {
237 glk_window_close(Graphics, NULL);
238 Graphics = NULL;
239 glk_window_get_size(Top, &TopWidth, &TopHeight);
240 }
241 }
242
243 void SetTimer(glui32 milliseconds)
244 {
245 TimerRate = milliseconds;
246 glk_request_timer_events(milliseconds);
247 }
248
249 void UpdateSettings(void)
250 {
251 #ifdef SPATTERLIGHT
252 if (gli_sa_delays)
253 Options &= ~NO_DELAYS;
254 else
255 Options |= NO_DELAYS;
256
257 switch (gli_sa_inventory) {
258 case 0:
259 Options &= ~(FORCE_INVENTORY | FORCE_INVENTORY_OFF);
260 break;
261 case 1:
262 Options = (Options | FORCE_INVENTORY) & ~FORCE_INVENTORY_OFF;
263 break;
264 case 2:
265 Options = (Options | FORCE_INVENTORY_OFF) & ~FORCE_INVENTORY;
266 break;
267 }
268
269 if (gli_enable_graphics) {
270 SetBit(GRAPHICSBIT);
271 } else {
272 ResetBit(GRAPHICSBIT);
273 }
274 #endif
275 }
276
277 static void FlushRoomDescription(char *buf, int transcript);
278 static void ListInventory(int upper);
279
280 static void UpdateClaymorgueInventory(void)
281 {
282 char *buf = MemAlloc(1000);
283 buf = memset(buf, 0, 1000);
284 room_description_stream = glk_stream_open_memory(buf, 1000, filemode_Write, 0);
285 ListInventory(1);
286 FlushRoomDescription(buf, 0);
287 DrawRoomImage(33);
288 for (int ct = 0; ct <= GameHeader.NumObjImg; ct++)
289 if (ObjectImages[ct].Room == 33 && Items[ObjectImages[ct].Object].Location == CARRIED) {
290 DrawItemImage(ObjectImages[ct].Image);
291 }
292 }
293
294 void UpdateColorCycling(void);
295
296 static int AnimationCounter = 0;
297
298 void Updates(event_t ev)
299 {
300 if (ev.type == evtype_Arrange) {
301 SavedImgType = LastImgType;
302 SavedImgIndex = LastImgIndex;
303 CloseGraphicsWindow();
304 UpdateSettings();
305 OpenGraphicsWindow();
306 if (AnimationRunning && LastAnimationBackground) {
307 char buf[5];
308 snprintf(buf, sizeof buf, "S0%02d", LastAnimationBackground);
309 DrawImageWithName(buf);
310 } else {
311 SetBit(DRAWBIT);
312 if (showing_inventory == 1) {
313 UpdateClaymorgueInventory();
314 } else {
315 Look(0);
316 if (SavedImgType == IMG_OBJECT)
317 DrawItemImage(SavedImgIndex);
318 else if (SavedImgType == IMG_SPECIAL)
319 DrawCloseup(SavedImgIndex);
320 }
321 }
322 } else if (ev.type == evtype_Timer) {
323 AnimationCounter++;
324 if (AnimationRunning) {
325 int factor = MAX(TimerRate, 1);
326 int rate = MAX(AnimTimerRate / factor, 1);
327 if (!IsSet(GRAPHICSBIT)) {
328 StopAnimation();
329 } else if (AnimationCounter % rate == 0) {
330 UpdateAnimation();
331 }
332 }
333 if (ColorCyclingRunning && IsSet(GRAPHICSBIT))
334 UpdateColorCycling();
335 }
336 }
337
338 static int DelayCounter = 0;
339
340 void AnyKey(int timeout, int message)
341 {
342 if (message) {
343 SystemMessage(HIT_ANY);
344 }
345
346 glk_request_char_event(Bottom);
347
348 event_t ev;
349 int result = 0;
350
351 int cancel_after_delay = 0;
352
353 if (CurrentGame == CLAYMORGUE)
354 timeout = 0;
355
356 if (timeout)
357 cancel_after_delay = (AnimationRunning == 0 && ColorCyclingRunning == 0);
358
359 if (cancel_after_delay && TimerRate == 0)
360 SetTimer(3000);
361
362 do {
363 glk_select(&ev);
364 if (ev.type == evtype_CharInput) {
365 result = 1;
366 } else {
367 DelayCounter++;
368 if (cancel_after_delay && ev.type == evtype_Timer) {
369 int factor = MAX(TimerRate, 1);
370 int rate = MAX(3000 / factor, 1);
371 if (DelayCounter % rate == 0) {
372 result = 1;
373 glk_cancel_char_event(Bottom);
374 if (TimerRate == 3000)
375 SetTimer(0);
376 DelayCounter = 0;
377 }
378 }
379
380 if (!AnimationRunning && !cancel_after_delay && timeout) {
381 if (TimerRate == 0)
382 SetTimer(3000);
383 cancel_after_delay = 1;
384 }
385
386 Updates(ev);
387 }
388 } while (result == 0);
389
390 return;
391 }
392
393 static void PrintWindowDelimiter(void)
394 {
395 glk_window_get_size(Top, &TopWidth, &TopHeight);
396 glk_window_move_cursor(Top, 0, TopHeight - 1);
397 glk_stream_set_current(glk_window_get_stream(Top));
398 for (int i = 0; i < TopWidth; i++)
399 glk_put_char(DelimiterChar);
400 }
401
402 static void FlushRoomDescription(char *buf, int transcript)
403 {
404 glk_stream_close(room_description_stream, 0);
405
406 if (Transcript && transcript) {
407 if (!lastwasnewline)
408 glk_put_string_stream(Transcript, "\n");
409 glk_put_string_stream(Transcript, "\n");
410 size_t buflen = strlen(buf);
411 char *roomtranscript = MemAlloc(buflen);
412 buflen -= 2;
413 strncpy(roomtranscript, buf, buflen);
414 roomtranscript[buflen] = '\0';
415 glk_put_string_stream(Transcript, roomtranscript);
416 free(roomtranscript);
417 glk_put_string_stream(Transcript, " ");
418 }
419
420 int print_delimiter = 1;
421
422 if (split_screen) {
423 glk_window_clear(Top);
424 glk_window_get_size(Top, &TopWidth, &TopHeight);
425 int rows, length;
426 char *text_with_breaks = LineBreakText(buf, TopWidth, &rows, &length);
427
428 glui32 bottomheight;
429 glk_window_get_size(Bottom, NULL, &bottomheight);
430 winid_t o2 = glk_window_get_parent(Top);
431 if (!(bottomheight < 3 && TopHeight < rows)) {
432 glk_window_get_size(Top, &TopWidth, &TopHeight);
433 glk_window_set_arrangement(o2, winmethod_Above | winmethod_Fixed, rows,
434 Top);
435 } else {
436 print_delimiter = 0;
437 }
438
439 int line = 0;
440 int index = 0;
441 int i;
442 if (TopWidth > 2047)
443 TopWidth = 2047;
444 char string[2048];
445 for (line = 0; line < rows && index < length; line++) {
446 for (i = 0; i < TopWidth; i++) {
447 string[i] = text_with_breaks[index++];
448 if (string[i] == 10 || string[i] == 13 || index >= length)
449 break;
450 }
451 if (i < TopWidth + 1) {
452 string[i++] = '\n';
453 }
454 string[i] = 0;
455 if (strlen(string) == 0)
456 break;
457 glk_window_move_cursor(Top, 0, line);
458 Display(Top, "%s", string);
459 }
460
461 if (line < rows - 1) {
462 glk_window_get_size(Top, &TopWidth, &TopHeight);
463 glk_window_set_arrangement(o2, winmethod_Above | winmethod_Fixed,
464 MIN(rows - 1, TopHeight - 1), Top);
465 }
466
467 free(text_with_breaks);
468 } else {
469 Display(Bottom, "%s", buf);
470 }
471
472 if (print_delimiter) {
473 PrintWindowDelimiter();
474 }
475
476 if (buf != NULL) {
477 free(buf);
478 buf = NULL;
479 }
480 }
481
482 static void WriteToRoomDescriptionStream(const char *fmt, ...)
483 #ifdef __GNUC__
484 __attribute__((__format__(__printf__, 1, 2)))
485 #endif
486 ;
487
488 static void WriteToRoomDescriptionStream(const char *fmt, ...)
489 {
490 if (room_description_stream == NULL)
491 return;
492 va_list ap;
493 char msg[2048];
494
495 va_start(ap, fmt);
496 vsnprintf(msg, sizeof msg, fmt, ap);
497 va_end(ap);
498
499 glk_put_string_stream(room_description_stream, msg);
500 }
501
502 static void ListExits(void)
503 {
504 int ct = 0;
505 int numexits = 0;
506
507 for (int i = 0; i < 6; i++)
508 if (Rooms[MyLoc].Exits[i] != 0)
509 numexits++;
510
511 if (numexits == 0) {
512 WriteToRoomDescriptionStream("\n");
513 return;
514 }
515 if (numexits > 1)
516 WriteToRoomDescriptionStream(" I see exits ");
517 else
518 WriteToRoomDescriptionStream(" %s", sys[EXITS]);
519
520 for (int i = 0; i < 6; i++)
521 if (Rooms[MyLoc].Exits[i] != 0) {
522 if (ct) {
523 if (ct == numexits - 1)
524 WriteToRoomDescriptionStream(", and ");
525 else
526 WriteToRoomDescriptionStream("%s", sys[EXITS_DELIMITER]);
527 } else if (ct < 5 && numexits > 1)
528 WriteToRoomDescriptionStream("to the ");
529 WriteToRoomDescriptionStream("%s", sys[i]);
530 ct++;
531 }
532 WriteToRoomDescriptionStream(".\n");
533 }
534
535 static const char *IndefiniteArticle(const char *word)
536 {
537 char c = word[0];
538 char vowels[6] = "aiouey";
539 if (c == ' ')
540 return "\0";
541 for (int i = 0; i < 6; i++)
542 if (vowels[i] == c)
543 return " an ";
544 return " a ";
545 }
546
547 void Look(int transcript)
548 {
549 showing_inventory = 0;
550 found_match = 1;
551 if (IsSet(DRAWBIT)) {
552 ResetBit(DRAWBIT);
553 DrawCurrentRoom();
554 }
555
556 char *buf = MemAlloc(1000);
557 buf = memset(buf, 0, 1000);
558 room_description_stream = glk_stream_open_memory(buf, 1000, filemode_Write, 0);
559
560 Room *r;
561 int ct;
562
563 int dark = IsSet(DARKBIT);
564 for (int i = 0; i <= GameHeader.NumItems; i++) {
565 if (Items[i].Flag & 2) {
566 if (Items[i].Location == MyLoc || Items[i].Location == CARRIED)
567 dark = 0;
568 }
569 }
570
571 if (dark) {
572 WriteToRoomDescriptionStream("%s", sys[TOO_DARK_TO_SEE]);
573 FlushRoomDescription(buf, transcript);
574 return;
575 }
576
577 r = &Rooms[MyLoc];
578
579 if (!r->Text)
580 return;
581 /* An initial asterisk means the room description should not */
582 /* start with "You are" or equivalent */
583 if (*r->Text == '*') {
584 WriteToRoomDescriptionStream("%s", r->Text + 1);
585 } else {
586 WriteToRoomDescriptionStream("%s%s", sys[YOU_ARE], r->Text);
587 }
588
589 ct = 0;
590 int numobj = 0;
591 for (int i = 0; i <= GameHeader.NumItems; i++)
592 if (Items[i].Location == MyLoc && Items[i].Text[0] != 0)
593 numobj++;
594 for (int i = 0; i <= GameHeader.NumItems; i++) {
595 if (Items[i].Location == MyLoc && Items[i].Text[0] != 0) {
596 if (ct == 0) {
597 WriteToRoomDescriptionStream("%s", sys[YOU_SEE]);
598 } else if (ct == numobj - 1) {
599 WriteToRoomDescriptionStream(", and");
600 } else {
601 WriteToRoomDescriptionStream("%s", sys[ITEM_DELIMITER]);
602 }
603 WriteToRoomDescriptionStream("%s%s", IndefiniteArticle(Items[i].Text), Items[i].Text);
604 ct++;
605 }
606 }
607
608 WriteToRoomDescriptionStream(".");
609
610 ListExits();
611
612 if ((Options & FORCE_INVENTORY) && !(Options & FORCE_INVENTORY_OFF)) {
613 WriteToRoomDescriptionStream("\n");
614 ListInventory(1);
615 }
616
617 WriteToRoomDescriptionStream(" ");
618 FlushRoomDescription(buf, transcript);
619 }
620
621 void Output(const char *string)
622 {
623 Display(Bottom, "%s", string);
624 }
625
626 void SystemMessage(SysMessageType message)
627 {
628 if (!lastwasnewline)
629 Output(" ");
630 lastwasnewline = 0;
631 Output(sys[message]);
632 }
633
634 static winid_t FindGlkWindowWithRock(glui32 rock)
635 {
636 winid_t win;
637 glui32 rockptr;
638 for (win = glk_window_iterate(NULL, &rockptr); win;
639 win = glk_window_iterate(win, &rockptr)) {
640 if (rockptr == rock)
641 return win;
642 }
643 return 0;
644 }
645
646 void OpenTopWindow(void)
647 {
648 Top = FindGlkWindowWithRock(GLK_STATUS_ROCK);
649 if (Top == NULL) {
650 if (split_screen) {
651 Top = glk_window_open(Bottom, winmethod_Above | winmethod_Fixed,
652 TopHeight, wintype_TextGrid, GLK_STATUS_ROCK);
653 if (Top == NULL) {
654 split_screen = 0;
655 Top = Bottom;
656 } else {
657 glk_window_get_size(Top, &TopWidth, NULL);
658 }
659 } else {
660 Top = Bottom;
661 }
662 }
663 }
664
665 static void DisplayInit(void)
666 {
667 Bottom = glk_window_open(0, 0, 0, wintype_TextBuffer, GLK_BUFFER_ROCK);
668 OpenTopWindow();
669 OpenGraphicsWindow();
670 }
671
672 static void OutputNumber(int a)
673 {
674 if (lastwasnewline) {
675 Display(Bottom, "%d", a);
676 lastwasnewline = 0;
677 } else {
678 Display(Bottom, " %d", a);
679 }
680 }
681
682 static void Delay(float seconds)
683 {
684 if (Options & NO_DELAYS || AnimationRunning)
685 return;
686
687 event_t ev;
688
689 if (!glk_gestalt(gestalt_Timer, 0))
690 return;
691
692 glk_request_char_event(Bottom);
693 glk_cancel_char_event(Bottom);
694
695 SetTimer(1000 * seconds);
696
697 do {
698 glk_select(&ev);
699 Updates(ev);
700 } while (ev.type != evtype_Timer);
701
702 if (!AnimationRunning && !ColorCyclingRunning)
703 SetTimer(0);
704 }
705
706 int RandomPercent(int n)
707 {
708 uint64_t rv = (uint64_t)rand() << 6;
709 rv &= 0xffffffff;
710 rv %= 100;
711 if (rv < n)
712 return (1);
713 return (0);
714 }
715
716 static int CountItemsInRoom(int room)
717 {
718 int ct = 0;
719 int n = 0;
720 if (room == 0)
721 room = CARRIED;
722 while (ct <= GameHeader.NumItems) {
723 if (Items[ct].Location == room)
724 n++;
725 ct++;
726 }
727 if (room == CARRIED)
728 Counters[33] = n;
729 return (n);
730 }
731
732 static int MatchUpItem(int noun, int loc)
733 {
734 for (int i = 0; i <= GameHeader.NumItems; i++)
735 if (Items[i].Dictword == noun && (Items[i].Location == loc || loc == -1) && (Items[i].Flag & 1))
736 return i;
737 return (0);
738 }
739
740 static void PrintMessage(int index)
741 {
742 if (JustRestarted && Transcript) {
743 glk_put_string_stream(Transcript, "\n\n");
744 JustRestarted = 0;
745 }
746 const char *message = Messages[index];
747 debug_print("Print message %d: \"%s\"\n", index, message);
748 if (lastwasnewline)
749 pendingcomma = 0;
750 if (message != NULL && message[0] != 0) {
751 int i = 0;
752 if (message[0] != '\\' && message[0] != ' ') {
753 if (pendingcomma)
754 Output(",");
755 if (!lastwasnewline)
756 Output(" ");
757 } else {
758 while (message[i] == '\\')
759 i++;
760 }
761 pendingcomma = 0;
762 while (message[i] != 0 && !(message[i] == ' ' && message[i + 1] == 0)) {
763 if (message[i] == ',' && message[i + 1] == 0)
764 pendingcomma = 1;
765 else
766 Display(Bottom, "%c", message[i]);
767 i++;
768 }
769 lastwasnewline = 0;
770 }
771 }
772
773 static void PrintNoun(void)
774 {
775 DictWord *dict = Nouns;
776 for (int i = 0; dict->Word != NULL; i++) {
777 if (dict->Group == CurrentNoun) {
778 Display(Bottom, "%s%s", lastwasnewline ? "" : " ", dict->Word);
779 lastwasnewline = 0;
780 return;
781 }
782 dict++;
783 }
784 }
785
786 static int GetAnyDictWord(int group, DictWord *dict)
787 {
788 for (int i = 0; dict->Word != NULL; i++) {
789 if (dict->Group == group) {
790 return i;
791 }
792 dict++;
793 }
794 return 0;
795 }
796
797 int GetDictWord(int group)
798 {
799 DictWord *dict = Nouns;
800 for (int i = 0; dict->Word != NULL; i++) {
801 if (dict->Group == group) {
802 return i;
803 }
804 dict++;
805 }
806 return 0;
807 }
808
809 static void PlayerIsDead(void)
810 {
811 debug_print("Player is dead\n");
812 SystemMessage(IM_DEAD);
813 ResetBit(DARKBIT);
814 SetBit(DRAWBIT);
815 MyLoc = Counters[35];
816 Counters[17] = Counters[17] & 0x0f;
817 Look(0);
818 }
819
820 void CheckForObjectImage(int obj)
821 {
822 for (int i = 0; i <= GameHeader.NumObjImg; i++)
823 if (ObjectImages[i].Object == obj) {
824 SetBit(DRAWBIT);
825 return;
826 }
827 }
828
829 static void PutItemAInRoomB(int itemA, int roomB)
830 {
831 debug_print("Item %d (%s) is put in room %d. MyLoc: %d (%s)\n", itemA, Items[itemA].Text, roomB, MyLoc, Rooms[MyLoc].Text);
832 Items[itemA].Location = roomB;
833 if (roomB == MyLoc)
834 CheckForObjectImage(itemA);
835 }
836
837 static void SwapCounters(int index)
838 {
839 debug_print("Main counter (47) is swapped with counter %d\n", index);
840 if (index > 63) {
841 debug_print("ERROR! parameter out of range. Max 63, got %d\n", index);
842 index = 63;
843 }
844 int temp = CurrentCounter;
845
846 CurrentCounter = Counters[index];
847 Counters[index] = temp;
848 debug_print("Value of new selected counter is %d\n", CurrentCounter);
849 }
850
851 static void SwapItemLocations(int itemA, int itemB)
852 {
853 int temp = Items[itemA].Location;
854 Items[itemA].Location = Items[itemB].Location;
855 Items[itemB].Location = temp;
856 }
857
858 static void MoveItemAToLocOfItemB(int itemA, int itemB)
859 {
860 Items[itemA].Location = Items[itemB].Location;
861 }
862
863 static void DoneIt(void)
864 {
865 Output("\n");
866 lastwasnewline = 1;
867 SystemMessage(PLAY_AGAIN);
868 Output(" ");
869 if (YesOrNo()) {
870 should_restart = 1;
871 } else {
872 CleanupAndExit();
873 }
874 }
875
876 static void WriteToLowerWindow(const char *fmt, ...)
877 {
878 va_list ap;
879 char msg[2048];
880
881 int size = sizeof msg;
882
883 va_start(ap, fmt);
884 vsnprintf(msg, size, fmt, ap);
885 va_end(ap);
886
887 glk_put_string_stream(glk_window_get_stream(Bottom), msg);
888 if (Transcript)
889 glk_put_string_stream(Transcript, msg);
890 }
891
892 static void ListInventory(int upper)
893 {
894 int i, ct = 0;
895 int numcarried = 0;
896
897 for (i = 0; i <= GameHeader.NumItems; i++) {
898 if (Items[i].Location == CARRIED && Items[i].Text[0] != 0)
899 numcarried++;
900 }
901
902 void (*print_function)(const char *fmt, ...);
903 if (upper) {
904 print_function = WriteToRoomDescriptionStream;
905 } else {
906 print_function = WriteToLowerWindow;
907 }
908
909 if (upper)
910 print_function("%s", sys[INVENTORY]);
911 else
912 SystemMessage(INVENTORY);
913
914 for (i = 0; i <= GameHeader.NumItems; i++) {
915 if (Items[i].Location == CARRIED) {
916 if (Items[i].Text[0] == 0) {
917 debug_print("Invisible item in inventory: %d\n", i);
918 i++;
919 continue;
920 }
921
922 if (ct) {
923 if (ct == numcarried - 1)
924 print_function(", and");
925 else
926 print_function("%s", sys[ITEM_DELIMITER]);
927 }
928
929 print_function("%s%s", IndefiniteArticle(Items[i].Text), Items[i].Text);
930 ct++;
931 }
932 }
933 if (ct == 0)
934 print_function("%s", sys[NOTHING]);
935 else
936 print_function(".");
937
938 if (upper)
939 print_function("\n");
940 }
941
942 static void ClearScreen(void)
943 {
944 glk_window_clear(Bottom);
945 }
946
947 void DrawApple2ImageFromVideoMem(void);
948
949 static void SysCommand(int arg1, int arg2)
950 {
951 switch (arg1) {
952 case 1:
953 SystemMessage(RESUME_A_SAVED_GAME);
954 if (YesOrNo())
955 LoadGame();
956 break;
957 case 2:
958 debug_print("Add special picture %d to animate buffer\n", Counters[arg2]);
959 AddSpecialImage(Counters[arg2]);
960 break;
961 case 3:
962 debug_print("Clear animate buffer\n");
963 ClearAnimationBuffer();
964 break;
965 case 4:
966 debug_print("Animate counter %d (%d)\n", arg2, Counters[arg2]);
967 Animate(Counters[arg2]);
968 break;
969 case 5:
970 debug_print("Unpack special picture %d (Set animation background)\n", arg2);
971 AnimationBackground = arg2;
972 break;
973 case 6:
974 debug_print("Beep and wait for key\n");
975 AnyKey(1, 1);
976 break;
977 case 7:
978 debug_print("DrawItemImage %d\n", Counters[arg2]);
979 DrawItemImage(Counters[arg2]);
980 if (CurrentSys == SYS_APPLE2)
981 DrawApple2ImageFromVideoMem();
982 break;
983 case 8:
984 debug_print("DrawRoomImage %d\n", Counters[arg2]);
985 DrawRoomImage(Counters[arg2]);
986 break;
987 case 9: {
988 debug_print("Swap item %d flags with counter 63\n", arg2);
989 int temp = Counters[63];
990 Counters[63] = Items[arg2].Flag;
991 Items[arg2].Flag = temp;
992 break;
993 }
994 case 10:
995 debug_print("Add item image %d to animate buffer\n", Counters[arg2]);
996 AddItemImage(Counters[arg2]);
997 break;
998 case 11:
999 debug_print("Add room image %d to animate buffer\n", Counters[arg2]);
1000 AddRoomImage(Counters[arg2]);
1001 break;
1002 default:
1003 debug_print("Unknown system command %d\n", arg1);
1004 break;
1005 }
1006 }
1007
1008 typedef enum {
1009 NO_PAREN,
1010 LEFT_PAREN,
1011 RIGHT_PAREN
1012 } ParenType;
1013
1014 static ParenType SetLogicControlFlags(int mode, int *not_mode, int *not_continuous, int *or_mode, int *fuzzy_match)
1015 {
1016 ParenType paren = NO_PAREN;
1017 debug_print("Mode %d, ", mode);
1018 switch (mode) {
1019 case 0:
1020 *or_mode = 0;
1021 break;
1022 case 1:
1023 debug_print("OR mode!\n");
1024 *or_mode = 1;
1025 break;
1026 case 2:
1027 Fatal("Unimplemented XOR mode");
1028 case 3:
1029 debug_print("Negate single!\n");
1030 *not_mode = 1;
1031 break;
1032 case 4:
1033 debug_print("Negate multiple!\n");
1034 *not_continuous = 1;
1035 *not_mode = 1;
1036 break;
1037 case 5:
1038 debug_print("Cancel negate!\n");
1039 *not_continuous = 0;
1040 *not_mode = 0;
1041 break;
1042 case 6:
1043 debug_print("Left paren!\n");
1044 paren = LEFT_PAREN;
1045 break;
1046 case 7:
1047 debug_print("Right paren!\n");
1048 paren = RIGHT_PAREN;
1049 break;
1050 case 8:
1051 debug_print("Keep going (Always true)!\n");
1052 break;
1053 case 9:
1054 debug_print("Fuzzy match!\n");
1055 *fuzzy_match = 1;
1056 break;
1057 case 10:
1058 debug_print("Strict match!\n");
1059 *fuzzy_match = 0;
1060 break;
1061 default:
1062 debug_print("Unhandled logic control flag %d\n", mode);
1063 }
1064 return paren;
1065 }
1066
1067 int CalculateConditionResult(int x, int y, int or_condition)
1068 {
1069 if (or_condition == 0) {
1070 return (x && y);
1071 }
1072
1073 return (x || y);
1074 }
1075
1076 int parens_depth = 0;
1077 int parens_stack[5];
1078
1079 static ActionResultType TestConditions(uint16_t *ptr)
1080 {
1081 int negate_condition = 0;
1082 int negate_multiple = 0;
1083 int or_condition = 0;
1084 int fuzzy_match = 0;
1085 int last_result = 1;
1086 int current_result = 1;
1087 int one_success = 0;
1088
1089 int cc = 0;
1090
1091 int reached_end = 0;
1092
1093 int cv = 0, dv = 0, dv2, originaldv;
1094
1095 while (ptr[cc] != 255 && !reached_end) {
1096 cv = ptr[cc++];
1097 dv = ptr[cc++];
1098
1099 originaldv = dv;
1100
1101 if (dv == 998) {
1102 dv = NounObject;
1103 } else if (dv == 999) {
1104 dv = Noun2Object;
1105 } else if (dv == 997) {
1106 Fatal("With list unimplemented");
1107 }
1108
1109 debug_print("Testing condition %d: ", cv);
1110 current_result = 1;
1111
1112 switch (cv) {
1113 case 0:
1114 break;
1115 case 1:
1116 debug_print("Does the player carry %s?\n", Items[dv].Text);
1117 if (Items[dv].Location != CARRIED) {
1118 current_result = 0;
1119 }
1120 break;
1121 case 2:
1122 if (dv < 0 || dv > GameHeader.NumItems) {
1123 debug_print("Parameter out of range! (%d)\n", dv);
1124 current_result = 0;
1125 break;
1126 }
1127
1128 debug_print("Is %s in location?\n", Items[dv].Text);
1129 if (Items[dv].Location != MyLoc) {
1130 current_result = 0;
1131 }
1132 break;
1133 case 3:
1134 debug_print("Is %s held or in location?\n", Items[dv].Text);
1135 if (Items[dv].Location != CARRIED && Items[dv].Location != MyLoc) {
1136 current_result = 0;
1137 }
1138 break;
1139 case 4:
1140 debug_print("Is location room %d, %s?\n", dv, Rooms[dv].Text);
1141 if (MyLoc != dv)
1142 current_result = 0;
1143 break;
1144 case 5:
1145 cc++;
1146 dv2 = ptr[cc++];
1147 debug_print("Is description of room %d (counter %d) (%d) == Message %d?\n", Counters[dv], dv, Rooms[Counters[dv]].Exits[6], dv2);
1148 if (Rooms[Counters[dv]].Exits[6] != dv2)
1149 current_result = 0;
1150 break;
1151 case 8:
1152 debug_print("Is bitflag %d set?\n", dv);
1153 if (!IsSet(dv)) {
1154 current_result = 0;
1155 }
1156 break;
1157 case 9:
1158 debug_print("Is bitflag %d NOT set?\n", dv);
1159 if (IsSet(dv)) {
1160 current_result = 0;
1161 }
1162 break;
1163 case 10:
1164 debug_print("Does the player carry anything?\n");
1165 if (CountItemsInRoom(dv) == 0) {
1166 current_result = 0;
1167 }
1168 break;
1169 case 13:
1170 debug_print("Is %s (%d) in play?\n", Items[dv].Text, dv);
1171 if (Items[dv].Location == 0) {
1172 current_result = 0;
1173 }
1174 break;
1175 case 14:
1176 debug_print("Is %s NOT in play?\n", Items[dv].Text);
1177 if (Items[dv].Location) {
1178 current_result = 0;
1179 }
1180 break;
1181 case 15:
1182 debug_print("Is CurrentCounter <= %d?\n", dv);
1183 if (CurrentCounter > dv) {
1184 current_result = 0;
1185 }
1186 break;
1187 case 16:
1188 debug_print("Is CurrentCounter > %d?\n", dv);
1189 if (CurrentCounter <= dv) {
1190 current_result = 0;
1191 }
1192 break;
1193 case 17:
1194 cc++;
1195 dv2 = ptr[cc++];
1196 debug_print("Is Counter %d == Counter %d?\n", dv, dv2);
1197
1198 if (Counters[dv] != Counters[dv2]) {
1199 current_result = 0;
1200 }
1201 break;
1202 case 18:
1203 cc++;
1204 dv2 = ptr[cc++];
1205 debug_print("Is counter %d (%d) greater than counter %d (%d)?\n", dv, Counters[dv], dv2, Counters[dv2]);
1206 if (Counters[dv] <= Counters[dv2]) {
1207 current_result = 0;
1208 }
1209 break;
1210 case 19:
1211 debug_print("Is current counter == %d?\n", dv);
1212 if (CurrentCounter != dv) {
1213 current_result = 0;
1214 }
1215 break;
1216 case 20:
1217 cc++;
1218 dv2 = ptr[cc++];
1219 debug_print("Is counter %d (%d) == %d?\n", dv, Counters[dv], dv2);
1220 if (Counters[dv] != dv2)
1221 current_result = 0;
1222 break;
1223
1224 case 21:
1225 cc++;
1226 dv2 = ptr[cc++];
1227 debug_print("Is counter %d (%d) >= %d?\n", dv, Counters[dv], dv2);
1228 if (Counters[dv] < dv2)
1229 current_result = 0;
1230 break;
1231 case 22:
1232 debug_print("Is counter %d (%d) == 0?\n", dv, Counters[dv]);
1233 if (Counters[dv] != 0)
1234 current_result = 0;
1235 break;
1236 case 23:
1237 cc++;
1238 dv2 = ptr[cc++];
1239 debug_print("Is item %d (%s) in room (counter %d) %d?\n", dv, Items[dv].Text, dv2, Counters[dv2]);
1240 if (Items[dv].Location != Counters[dv2])
1241 current_result = 0;
1242 break;
1243 case 26:
1244 cc++;
1245 dv2 = ptr[cc++];
1246 debug_print("Is object %d in room %d?\n", dv, dv2);
1247 if (Items[dv].Location != dv2)
1248 current_result = 0;
1249
1250 break;
1251 case 28:
1252 cc++;
1253 dv2 = ptr[cc++];
1254 if (dv < 1 || dv2 < 1 || dv > GameHeader.NumItems + 1 || dv2 > GameHeader.NumItems + 1)
1255 debug_print("Is dictword of item (dv) %d == dictword group (dv2) %d?\n", dv, dv2);
1256 else
1257 debug_print("Is dictword (%d) of item %d (%s) == dictword (%d) of item %d (%s)?\n", Items[dv].Dictword, dv, Items[dv].Text, Items[dv2].Dictword, dv2, Items[dv2].Text);
1258 if (originaldv == 999) {
1259 if (CurrentNoun2 == dv2)
1260 break;
1261 current_result = 0;
1262 } else if (originaldv == 998) {
1263 if (CurrentNoun == dv2)
1264 break;
1265 current_result = 0;
1266 } else if (originaldv == 997) {
1267 Fatal("With list unimplemented");
1268 } else {
1269 if (Items[dv].Dictword == 0)
1270 break;
1271 if (dv > GameHeader.NumItems + 1 || dv2 > GameHeader.NumItems + 1 || Items[dv].Dictword != Items[dv2].Dictword) {
1272 current_result = 0;
1273 if (dv > GameHeader.NumItems + 1 || dv2 > GameHeader.NumItems + 1)
1274 debug_print("Error: Argument out of bounds\n!");
1275 }
1276 }
1277 break;
1278 case 29:
1279 cc++;
1280 dv2 = ptr[cc++];
1281 if (dv2 == 998)
1282 dv2 = CurrentNoun;
1283 else if (dv2 == 999)
1284 dv2 = CurrentNoun2;
1285 else if (dv2 == 997)
1286 Fatal("With list unimplemented");
1287 debug_print("Is dictword of object %d (%s) %d? (%s)\n", dv, Nouns[GetDictWord(Items[NounObject].Dictword)].Word, dv2, Nouns[GetDictWord(dv2)].Word);
1288 if (fuzzy_match) {
1289 debug_print("(Fuzzy match)\n");
1290 char *dictword1 = Nouns[GetDictWord(Items[NounObject].Dictword)].Word;
1291 char *dictword2 = Nouns[GetDictWord(dv2)].Word;
1292 if (!CompareUpToHashSign(dictword1, dictword2))
1293 current_result = 0;
1294 } else {
1295 debug_print("(Exact match)\n");
1296 if (Items[NounObject].Dictword != dv2) {
1297 current_result = 0;
1298 }
1299 }
1300 break;
1301 case 30:
1302 cc++;
1303 dv2 = ptr[cc++];
1304 if (dv > GameHeader.NumItems)
1305 debug_print("Bug! dv Out of bounds! dv:%d GameHeader.NumItems:%d\n", dv, GameHeader.NumItems);
1306 debug_print("Is Object flag %d & %d != 0\n", dv, dv2);
1307 if ((Items[dv].Flag & dv2) == 0)
1308 current_result = 0;
1309 break;
1310 case 31: /* logics control flags */
1311 {
1312
1313 if (dv == 1 && one_success == 0) {
1314 last_result = 0;
1315 }
1316
1317 ParenType paren = SetLogicControlFlags(dv, &negate_condition, &negate_multiple, &or_condition, &fuzzy_match);
1318
1319 if (paren == LEFT_PAREN) {
1320 if (parens_depth >= 4)
1321 Fatal("Too many nested parentheses in conditions");
1322 parens_stack[parens_depth] = last_result;
1323 debug_print("left parent.n\nSet parens_stack[%d] to last result %d\n", parens_depth, last_result);
1324 last_result = (or_condition == 0);
1325 parens_depth++;
1326 } else if (paren == RIGHT_PAREN) {
1327 if (parens_depth <= 0)
1328 Fatal("Mismatched parentheses");
1329 parens_depth--;
1330 debug_print("right parens.\n\nGetting pushed result %d from parens_stack[%d]\n", parens_stack[parens_depth], parens_depth);
1331 current_result = last_result;
1332 last_result = parens_stack[parens_depth];
1333 last_result = CalculateConditionResult(last_result, current_result, or_condition);
1334 }
1335 break;
1336 }
1337 default:
1338 debug_print("Unknown condition %d, arg == %d\n", cv, dv);
1339 current_result = 0;
1340 break;
1341 }
1342
1343 if (cv != 31) {
1344 if (negate_condition) {
1345 debug_print("Negating condition!\n");
1346 if (!current_result)
1347 debug_print("Was fail, now success!\n");
1348 else
1349 debug_print("Was success, now fail!\n");
1350 current_result = (current_result == 0);
1351 if (!negate_multiple)
1352 negate_condition = 0;
1353 }
1354
1355 if (current_result == 1 && cv != 31) {
1356 debug_print("YES\n");
1357 }
1358
1359 last_result = CalculateConditionResult(last_result, current_result, or_condition);
1360 if (last_result)
1361 one_success = 1;
1362 }
1363 }
1364
1365 if (last_result == 1)
1366 return ACT_SUCCESS;
1367 else
1368 return ACT_FAILURE;
1369 }
1370
1371 static void PrintFlagInfo(int arg)
1372 {
1373 switch (arg) {
1374 case 15:
1375 debug_print("15, darkbit\n");
1376 break;
1377 case 33:
1378 debug_print("33, a command matched on vocabulary, but its conditions failed\n");
1379 break;
1380 case 34:
1381 debug_print("34, room picture changed\n");
1382 break;
1383 case 35:
1384 debug_print("35, graphics on/off\n");
1385 break;
1386 case 60:
1387 debug_print("60, first action matches regardless of input\n");
1388 break;
1389 case 63:
1390 debug_print("63, skip automatics (stop time)\n");
1391 break;
1392 default:
1393 break;
1394 }
1395 }
1396
1397 void SetCountersFromInput(void) {
1398 VerbCounter = CurrentVerb;
1399 NounCounter = CurrentNoun;
1400 AdverbCounter = CurrentAdverb;
1401 PartpCounter = CurrentPartp;
1402 PrepCounter = CurrentPrep;
1403 Noun2Counter = CurrentNoun2;
1404 }
1405
1406 static ActionResultType PerformLine(int ct)
1407 {
1408 debug_print("\nPerforming line %d: (", ct);
1409 if (Actions[ct].Verb) {
1410 debug_print("%s %s) ", Verbs[GetAnyDictWord(Actions[ct].Verb, Verbs)].Word, Nouns[GetAnyDictWord(Actions[ct].NounOrChance, Nouns)].Word);
1411 } else {
1412 debug_print("0, %d) ", Actions[ct].NounOrChance);
1413 }
1414 int continuation = 0, dead = 0, done = 0;
1415 int loop = 0;
1416
1417 int cc = 0;
1418
1419 if (TestConditions(Actions[ct].Conditions) == ACT_FAILURE) {
1420 return ACT_FAILURE;
1421 }
1422
1423 #if defined(__clang__)
1424 #pragma mark Commands
1425 #endif
1426
1427 /* Commands */
1428 cc = 0;
1429 uint8_t *commands = Actions[ct].Commands;
1430 int length = Actions[ct].CommandLength;
1431 while (cc <= length) {
1432 int cmd = commands[cc++];
1433 int16_t arg1 = 0, arg2 = 0, arg3 = 0,
1434 ca1 = 0, ca2 = 0, ca3 = 0;
1435
1436 int object = 0;
1437 int plus_one_arg = 0;
1438
1439 if (cc <= length) {
1440 arg1 = commands[cc];
1441 object = arg1;
1442 if (cc + 1 <= length) {
1443 arg2 = commands[cc + 1];
1444 if (cc + 2 <= length) {
1445 arg3 = commands[cc + 2];
1446 }
1447 }
1448
1449 if (arg1 < 64)
1450 ca1 = Counters[arg1];
1451 if (arg2 < 64)
1452 ca2 = Counters[arg2];
1453 if (arg3 < 64)
1454 ca3 = Counters[arg3];
1455
1456 if (arg1 & 128) {
1457 arg1 = (arg1 & 127) * 256 + arg2;
1458 arg2 = arg3;
1459 plus_one_arg = 1;
1460 }
1461 if (arg1 == 998) {
1462 arg1 = CurrentNoun;
1463 object = NounObject;
1464 } else if (arg1 == 999) {
1465 arg1 = CurrentNoun2;
1466 object = Noun2Object;
1467 } else if (arg1 == 997) {
1468 Fatal("With list unimplemented");
1469 }
1470 }
1471
1472 debug_print("\nPerforming command %d: ", cmd);
1473 if (cmd >= 1 && cmd < 52) {
1474 PrintMessage(cmd);
1475 } else
1476 switch (cmd) {
1477 case 0: /* NOP */
1478 break;
1479 case 52:
1480 if (CountItemsInRoom(0) >= GameHeader.MaxCarry) {
1481 SystemMessage(YOURE_CARRYING_TOO_MUCH);
1482 lastwasnewline = 1;
1483 return ACT_SUCCESS;
1484 }
1485 Items[object].Location = CARRIED;
1486 CheckForObjectImage(object);
1487 cc += 1 + plus_one_arg;
1488 break;
1489 case 53:
1490 debug_print("Item %d (\"%s\") is now in location.\n", object,
1491 Items[object].Text);
1492 Items[object].Location = MyLoc;
1493 CheckForObjectImage(object);
1494 cc += 1 + plus_one_arg;
1495 break;
1496 case 54:
1497 debug_print("Player location is now room %d (%s).\n", arg1,
1498 Rooms[arg1].Text);
1499 MyLoc = commands[cc++];
1500 SetBit(DRAWBIT);
1501 break;
1502 case 55:
1503 debug_print("The command is changed to ");
1504 PrintDictWord(arg1, Verbs);
1505 debug_print(" ");
1506 PrintDictWord(arg2, Nouns);
1507 debug_print(".\n");
1508
1509 CurrentVerb = arg1;
1510 CurrentNoun = arg2;
1511 CurrentPartp = 0;
1512 CurrentPrep = 0;
1513 CurrentNoun2 = 0;
1514 CurrentAdverb = 0;
1515
1516 SetCountersFromInput();
1517
1518 keep_going = 1;
1519 done = 1;
1520 found_match = 0;
1521 cc += 2;
1522 break;
1523 case 56:
1524 SetBit(DARKBIT);
1525 break;
1526 case 57:
1527 ResetBit(DARKBIT);
1528 break;
1529 case 58:
1530 debug_print("Bitflag %d is set\n", arg1);
1531 #ifdef DEBUG_ACTIONS
1532 PrintFlagInfo(arg1);
1533 #endif
1534 SetBit(commands[cc++]);
1535 break;
1536 case 59:
1537 debug_print("Item %d (%s) is removed from play.\n", object,
1538 Items[object].Text);
1539 Items[object].Location = 0;
1540 CheckForObjectImage(object);
1541 cc += 1 + plus_one_arg;
1542 break;
1543 case 60:
1544 debug_print("BitFlag %d is cleared\n", arg1);
1545 PrintFlagInfo(arg1);
1546 ResetBit(commands[cc++]);
1547 break;
1548 case 61:
1549 PlayerIsDead();
1550 break;
1551 case 62:
1552 cc += 1 + plus_one_arg;
1553 PutItemAInRoomB(object, commands[cc++]);
1554 break;
1555 case 63:
1556 debug_print("Dead\n");
1557 DoneIt();
1558 dead = 1;
1559 break;
1560 case 64:
1561 debug_print("Counter %d == %d\n", arg2, arg1);
1562 Counters[arg2] = arg1;
1563 cc += 2 + plus_one_arg;
1564 break;
1565 case 65:
1566 debug_print("Multiply: Counter %d = Counter %d (%d) * Counter %d (%d) == %d\n", arg2, arg1, ca1, arg2, ca2, ca1 * ca2);
1567 Counters[arg2] = ca1 * ca2;
1568 cc += 2;
1569 break;
1570 case 66:
1571 ListInventory(0);
1572 if (CurrentGame == CLAYMORGUE)
1573 UpdateClaymorgueInventory();
1574 break;
1575 case 67:
1576 debug_print("Set bitflag 0\n");
1577 SetBit(0);
1578 break;
1579 case 68:
1580 debug_print("Clear bitflag 0\n");
1581 ResetBit(0);
1582 break;
1583 case 69:
1584 debug_print("Done (stop reading lines)\n");
1585 done = 1;
1586 break;
1587 case 70:
1588 ClearScreen();
1589 break;
1590 case 71:
1591 SaveGame();
1592 break;
1593 case 72:
1594 cc += 1 + plus_one_arg;
1595 CheckForObjectImage(object);
1596 CheckForObjectImage(commands[cc]);
1597 SwapItemLocations(object, commands[cc++]);
1598 break;
1599 case 73:
1600 debug_print("Continue with next line\n");
1601 continuation = 1;
1602 break;
1603 case 74:
1604 Items[object].Location = CARRIED;
1605 CheckForObjectImage(object);
1606 cc += 1 + plus_one_arg;
1607 break;
1608 case 75:
1609 cc += 1 + plus_one_arg;
1610 CheckForObjectImage(object);
1611 MoveItemAToLocOfItemB(object, commands[cc++]);
1612 break;
1613 case 76:
1614 debug_print("LOOK\n");
1615 Look(1);
1616 break;
1617 case 77:
1618 if (CurrentCounter >= 1)
1619 CurrentCounter--;
1620 debug_print("decrementing current counter. Current counter is now %d.\n",
1621 CurrentCounter);
1622 break;
1623 case 78:
1624 OutputNumber(CurrentCounter);
1625 break;
1626 case 79:
1627 debug_print("CurrentCounter is set to %d.\n", arg1);
1628 CurrentCounter = arg1;
1629 cc += 1 + plus_one_arg;
1630 break;
1631 case 80:
1632 debug_print("Counter %d is set to location of object %d.\n", arg2, object);
1633 Counters[arg2] = Items[object].Location;
1634 cc += 2 + plus_one_arg;
1635 break;
1636 case 81:
1637 SwapCounters(commands[cc++]);
1638 break;
1639 case 82:
1640 debug_print("Add %d to current counter(%d)\n", arg1, CurrentCounter);
1641 CurrentCounter += arg1;
1642 cc += 1 + plus_one_arg;
1643 break;
1644 case 83:
1645 CurrentCounter -= arg1;
1646 if (CurrentCounter < -1)
1647 CurrentCounter = -1;
1648 cc += 1 + plus_one_arg;
1649 break;
1650 case 84:
1651 PrintNoun();
1652 break;
1653 case 85:
1654 debug_print("Print name of item %d (%s)\n", object, Items[object].Text);
1655 Display(Bottom, " %s", Items[object].Text);
1656 cc += 1 + plus_one_arg;
1657 break;
1658 case 86:
1659 debug_print("Output dictword of item (%d) + space.\n", arg1);
1660 Display(Bottom, "%s ", Nouns[GetDictWord(Items[arg1].Dictword)].Word);
1661 cc++;
1662 break;
1663 case 88:
1664 debug_print("Delay\n");
1665 Delay(1);
1666 break;
1667 case 89:
1668 debug_print("Draw current room image\n");
1669 DrawCurrentRoom();
1670 ResetBit(DRAWBIT);
1671 break;
1672 case 90:
1673 debug_print("Draw closeup image %d\n", arg1);
1674 DrawCloseup(commands[cc++]);
1675 SetBit(DRAWBIT);
1676 AnyKey(0, 1);
1677 break;
1678 case 91:
1679 debug_print("Divide: Counter %d = Counter %d (%d) / counter %d (%d), Counter %d = Counter %d (%d) / counter %d (%d)\n", arg2, arg2, ca2, arg1, ca1, arg3, arg2, ca2, arg1, ca1);
1680 if (ca1) {
1681 Counters[arg3] = ca2 % ca1;
1682 Counters[arg2] = ca2 / ca1;
1683 }
1684 cc += 3;
1685 break;
1686 case 92:
1687 debug_print("Domore reset\n");
1688 keep_going = 0;
1689 break;
1690 case 93:
1691 debug_print("Delay Counter %d (%d) * .25 seconds (%f)\n", arg1, Counters[arg1], Counters[arg1] * 0.25);
1692 if (CurrentGame == CLAYMORGUE)
1693 Delay(Counters[arg1] * 0.125);
1694 else
1695 Delay(Counters[arg1] * 0.25);
1696 cc++;
1697 break;
1698 case 94:
1699 debug_print("Counter %d = exit %d from room %d\n", arg1, ca3, ca2);
1700 Counters[arg1] = Rooms[ca2].Exits[ca3];
1701 cc += 3;
1702 break;
1703 case 95:
1704 debug_print("Exit %d of room %d is set to %d\n", ca2, ca1, ca3);
1705 Rooms[ca1].Exits[ca2] = ca3;
1706 cc += 3;
1707 break;
1708 case 97:
1709 debug_print("Swap counters %d %d \n", arg1, arg2);
1710 /* Draw room image after jumping off Claymorgue crate */
1711 if (arg1 == 32 && ca2 != MyLoc)
1712 SetBit(DRAWBIT);
1713 Counters[arg1] = ca2;
1714 Counters[arg2] = ca1;
1715 cc += 2;
1716 break;
1717 case 98:
1718 debug_print("Counter %d = counter %d\n", arg2, arg1);
1719 Counters[arg2] = ca1;
1720 cc += 2;
1721 break;
1722 case 99:
1723 debug_print("Counter %d is set to %d \n", arg2, arg1);
1724 Counters[arg2] = arg1;
1725 cc += 2 + plus_one_arg;
1726 break;
1727 case 100:
1728 debug_print("Add %d to counter %d\n", arg1, arg2);
1729 Counters[arg2] += arg1;
1730 cc += 2 + plus_one_arg;
1731 break;
1732 case 101:
1733 debug_print("Decrease counter %d by %d\n", arg2, arg1);
1734 Counters[arg2] -= arg1;
1735 cc += 2 + plus_one_arg;
1736 break;
1737 case 102:
1738 debug_print("Print counter %d\n", arg1);
1739 OutputNumber(Counters[arg1]);
1740 cc++;
1741 break;
1742 case 103:
1743 debug_print("ABS counter %d\n", arg1);
1744 if (ca1 < 0)
1745 Counters[arg1] = -ca1;
1746 cc++;
1747 break;
1748 case 104:
1749 debug_print("NEG counter %d\n", arg1);
1750 Counters[arg1] = -Counters[arg1];
1751 cc++;
1752 break;
1753 case 105:
1754 debug_print("AND counter %d with counter %d\n", arg2, arg1);
1755 Counters[arg2] = ca1 & ca2;
1756 cc += 2;
1757 break;
1758 case 106:
1759 debug_print("OR counter %d with counter %d\n", arg2, arg1);
1760 Counters[arg2] = ca1 | ca2;
1761 cc += 2;
1762 break;
1763 case 107:
1764 debug_print("XOR counter %d with counter %d\n", arg2, arg1);
1765 Counters[arg2] = ca1 ^ ca2;
1766 cc += 2;
1767 break;
1768 case 108:
1769 debug_print("Put random number (1 to 100) in counter %d\n", arg1);
1770 uint64_t rv = (uint64_t)rand() << 6;
1771 rv &= 0xffffffff;
1772 rv %= 100 + 1;
1773 Counters[arg1] = rv;
1774 cc++;
1775 break;
1776 case 109:
1777 debug_print("Clear counter %d\n", arg1);
1778 Counters[arg1] = 0;
1779 cc++;
1780 break;
1781 case 110:
1782 debug_print("System command %d %d\n", arg1, arg2);
1783 SysCommand(arg1, arg2);
1784 cc += 2;
1785 break;
1786 case 111:
1787 debug_print("Start over\n");
1788 keep_going = 1;
1789 done = 1;
1790 startover = 1;
1791 break;
1792 case 112:
1793 debug_print("Start loop\n");
1794 loop = 1;
1795 break;
1796 case 113:
1797 debug_print("Loop back\n");
1798 return ACT_LOOP;
1799 case 114:
1800 // 114 and 115 are now functionally the same, so at least one of them is wrong.
1801 // 114 is supposed to be instant while 115 is supposed to
1802 // do a 114 at the next loopback (113).
1803 // Things seems to work fine this way, however, and I'm not even sure what
1804 // the difference would be in practice.
1805 debug_print("Remove a loop from stack\n");
1806 loops[loop_index] = 0;
1807 if (loop_index > 0)
1808 loop_index--;
1809 break;
1810 case 115:
1811 debug_print("Remove a loop from stack at next loopback\n");
1812 if (loop_index > 0)
1813 loop_index--;
1814 break;
1815 case 116:
1816 debug_print("Continue looking for commands\n");
1817 debug_print("found_match = 0, domore = 1, done = 1\n");
1818 found_match = 0;
1819 keep_going = 1;
1820 done = 1;
1821 break;
1822 case 117:
1823 debug_print("Set found_match to 1\n");
1824 found_match = 1;
1825 SetBit(MATCHBIT);
1826 break;
1827 case 118:
1828 debug_print("Set done to 1\n");
1829 done = 1;
1830 break;
1831 case 119:
1832 cc++;
1833 if (arg1 >= 128) {
1834 arg1 = commands[cc++] - 76;
1835 }
1836 debug_print("Set command prompt to string arg %d (%s)\n", arg1, Messages[arg1]);
1837 ProtagonistString = arg1;
1838 break;
1839 case 120:
1840 debug_print("counter 48: verb, counter 49: noun, counter 50: preposition, counter 51: adverb, counter 52: participle, counter 53: noun 2\n");
1841 SetCountersFromInput();
1842 break;
1843 case 121:
1844 debug_print("Set input words to counters 48 to 53\n");
1845 CurrentVerb = VerbCounter;
1846 CurrentNoun = NounCounter;
1847 CurrentAdverb = AdverbCounter;
1848 CurrentPartp = PartpCounter;
1849 CurrentPrep = PrepCounter;
1850 CurrentNoun2 = Noun2Counter;
1851 keep_going = 1;
1852 done = 1;
1853 found_match = 0;
1854 break;
1855 case 122:
1856 debug_print("Print object %d with article\n", object);
1857 Display(Bottom, "%s%s", IndefiniteArticle(Items[object].Text), Items[object].Text);
1858 cc += 1 + plus_one_arg;
1859 break;
1860 case 123:
1861 debug_print("Add counter %d to counter %d.\n", arg1, arg2);
1862 Counters[arg2] += ca1;
1863 cc += 2;
1864 break;
1865 case 124:
1866 debug_print("Reset all loops.\n");
1867 loop_index = 0;
1868 break;
1869 case 125:
1870 debug_print("Flag %d = Flag %d.\n", arg2, arg1);
1871 if (IsSet(arg1))
1872 SetBit(arg2);
1873 else
1874 ResetBit(arg2);
1875 cc += 2;
1876 break;
1877 case 126:
1878 debug_print("Counter %d = Counter (Counter %d (%d))\n", arg1, arg2, ca2);
1879 Counters[arg1] = Counters[ca2];
1880 cc += 2;
1881 break;
1882 case 127:
1883 debug_print("Counter (Counter %d (%d)) = Counter %d\n", arg2, ca2, arg1);
1884 Counters[ca2] = Counters[arg1];
1885 cc += 2;
1886 break;
1887 case 128:
1888 PrintMessage(commands[cc++] - 76);
1889 break;
1890 default:
1891 if (cc < length - 1)
1892 debug_print("Unknown action %d [Param begins %d %d]\n", cmd,
1893 commands[cc], commands[cc + 1]);
1894 break;
1895 }
1896 }
1897
1898 if (dead) {
1899 debug_print("PerformLine: Returning ACT_GAMEOVER\n");
1900 return ACT_GAMEOVER;
1901 } else if (loop) {
1902 debug_print("PerformLine: Returning ACT_LOOP_BEGIN\n");
1903 return ACT_LOOP_BEGIN;
1904 } else if (continuation) {
1905 debug_print("PerformLine: Returning ACT_CONTINUE\n");
1906 return ACT_CONTINUE;
1907 } else if (done) {
1908 debug_print("PerformLine: Returning ACT_DONE\n");
1909 return ACT_DONE;
1910 } else {
1911 debug_print("PerformLine: Returning ACT_SUCCESS\n");
1912 return ACT_SUCCESS;
1913 }
1914 }
1915
1916 static int IsExtraWordMatch(int ct)
1917 {
1918 /* If the action has no "extra words" the command must contain no participle */
1919 if (Actions[ct].NumWords == 0) {
1920 return (CurrentPartp == 0);
1921 }
1922
1923 int foundprep = 0;
1924 int foundpartp = 0;
1925 int foundadverb = 0;
1926
1927 int matchedprep = 0;
1928 int matchedpartp = 0;
1929 int matchedadverb = 0;
1930
1931 debug_print("Action %d (%s %s) has %d extra words\n", ct, Verbs[GetAnyDictWord(Actions[ct].Verb, Verbs)].Word, Nouns[GetAnyDictWord(Actions[ct].NounOrChance, Nouns)].Word, Actions[ct].NumWords);
1932
1933 for (int i = 0; i < Actions[ct].NumWords; i++) {
1934 uint8_t word = Actions[ct].Words[i];
1935 debug_print("Extra word %d: %d ", i, word);
1936 uint8_t wordval = word & 63;
1937 switch (word >> 6) {
1938 case 1: /* adverb */
1939 debug_print("(adverb \"%s\")\n", Adverbs[GetAnyDictWord(wordval, Adverbs)].Word);
1940 foundadverb = 1;
1941 if (wordval == CurrentAdverb || wordval == 0 || (wordval == 1 && CurrentAdverb == 0))
1942 matchedadverb = 1;
1943 debug_print("Matched adverb %d\n", wordval);
1944 break;
1945 case 2: /* participle */
1946 debug_print("(participle \"%s\")\n", Prepositions[GetAnyDictWord(wordval, Prepositions)].Word);
1947 i++;
1948 foundpartp = 1;
1949 uint8_t n2 = Actions[ct].Words[i];
1950 debug_print("(object (word %d) \"%s\")\n", i, Nouns[GetAnyDictWord(n2, Nouns)].Word);
1951 if (CurrentPartp == 0 && wordval > 1 && !IsNextParticiple(wordval, n2)) {
1952 break;
1953 }
1954 if (wordval == CurrentPartp || wordval == 0 || (wordval == 1 && CurrentPartp == 0)) { /* 1 means NONE */
1955 debug_print("Matched participle %d\n", wordval);
1956 if (n2 == CurrentNoun2 || n2 == 0) {
1957 debug_print("Matched object %d (%s)\n", n2, Nouns[GetDictWord(n2)].Word);
1958 matchedpartp = 1;
1959 }
1960 }
1961 break;
1962 case 3: /* preposition */
1963 debug_print("(preposition \"%s\")\n", Prepositions[GetAnyDictWord(wordval, Prepositions)].Word);
1964 foundprep = 1;
1965 if (CurrentPrep == wordval || wordval == 0 || (wordval == 1 && CurrentPrep == 0)) {
1966 debug_print("Matched preposition %d\n", wordval);
1967 matchedprep = 1;
1968 }
1969 break;
1970 default:
1971 debug_print("(unknown type)\n");
1972 debug_print("word >> 6: %d\n", word >> 6);
1973 break;
1974 }
1975 }
1976
1977 if ((foundprep && !matchedprep) || (foundpartp && !matchedpartp) || (foundadverb && !matchedadverb)) {
1978 debug_print("IsExtraWordMatch failed\n");
1979 return 0;
1980 }
1981
1982 return 1;
1983 }
1984
1985 static int IsImplicitMatch(int ct, int doagain)
1986 {
1987
1988 if (RandomPercent(Actions[ct].NounOrChance)) {
1989 return 1;
1990 }
1991
1992 if (doagain)
1993 return 1;
1994
1995 return 0;
1996 }
1997
1998 static int IsMatch(int ct, int doagain)
1999 {
2000
2001 int verbvalue = Actions[ct].Verb;
2002 int nounvalue = Actions[ct].NounOrChance;
2003
2004 if (verbvalue != CurrentVerb && !(doagain && verbvalue == 0))
2005 return 0;
2006
2007 if (verbvalue == 0) {
2008 if (RandomPercent(nounvalue)) {
2009 return 1;
2010 } else if (nounvalue != 0) {
2011 return 0;
2012 }
2013 }
2014
2015 if (!(doagain && verbvalue == 0) && !IsExtraWordMatch(ct)) {
2016 return 0;
2017 }
2018
2019 if (verbvalue == CurrentVerb && verbvalue != 0 && (nounvalue == CurrentNoun || nounvalue == 0)) {
2020 found_match = 1;
2021 return 1;
2022 }
2023
2024 if (doagain)
2025 return 1;
2026
2027 return 0;
2028 }
2029
2030 static CommandResultType PerformImplicit(void)
2031 {
2032 int ct = 0;
2033 CommandResultType result = ER_RAN_ALL_LINES_NO_MATCH;
2034 int chain_on = 0;
2035 startover = 0;
2036 loop_index = 0;
2037
2038 while (ct <= GameHeader.NumActions) {
2039 int verbvalue = Actions[ct].Verb;
2040
2041 if (verbvalue != 0)
2042 break;
2043
2044 if (IsImplicitMatch(ct, chain_on)) {
2045 ActionResultType actresult = PerformLine(ct);
2046
2047 if (actresult != ACT_FAILURE) {
2048 result = ER_SUCCESS;
2049 switch (actresult) {
2050 case ACT_CONTINUE:
2051 chain_on = 1;
2052 break;
2053 case ACT_DONE:
2054 chain_on = 0;
2055 loops[loop_index] = 0;
2056 if (loop_index)
2057 loop_index--;
2058 break;
2059 case ACT_LOOP_BEGIN:
2060 loop_index++;
2061 if (loop_index >= MAX_LOOPS)
2062 Fatal("Loop stack overflow");
2063 loops[loop_index] = ct;
2064 chain_on = 1;
2065 break;
2066 case ACT_LOOP:
2067 if (loop_index) {
2068 ct = loops[loop_index];
2069 }
2070 break;
2071 case ACT_GAMEOVER:
2072 return ER_SUCCESS;
2073 default:
2074 break;
2075 }
2076 }
2077 }
2078
2079 ct++;
2080
2081 if (startover) {
2082 ct = 0;
2083 startover = 0;
2084 }
2085
2086 if (ct <= GameHeader.NumActions && (Actions[ct].Verb + Actions[ct].NounOrChance != 0))
2087 chain_on = 0;
2088
2089 if (IsSet(STOPTIMEBIT) && chain_on == 0) {
2090 ResetBit(STOPTIMEBIT);
2091 return result;
2092 }
2093 }
2094
2095 return result;
2096 }
2097
2098 static CommandResultType PerformExplicit(void)
2099 {
2100 int ct = 0;
2101 CommandResultType result = ER_RAN_ALL_LINES_NO_MATCH;
2102 int chain_on = 0;
2103 keep_going = 1;
2104 startover = 0;
2105 loop_index = 0;
2106 found_match = 0;
2107 ResetBit(MATCHBIT);
2108 NounObject = MatchUpItem(CurrentNoun, -1);
2109 Noun2Object = MatchUpItem(CurrentNoun2, -1);
2110
2111 while (ct <= GameHeader.NumActions) {
2112 int verbvalue, nounvalue;
2113 verbvalue = Actions[ct].Verb;
2114 nounvalue = Actions[ct].NounOrChance;
2115
2116 if (chain_on && verbvalue != 0) {
2117 chain_on = 0;
2118 }
2119
2120 if (IsMatch(ct, chain_on)) {
2121 ActionResultType actresult = PerformLine(ct);
2122
2123 if (actresult != ACT_FAILURE) {
2124 if (actresult != ACT_DONE)
2125 ResetBit(MATCHBIT);
2126 if (found_match) {
2127 keep_going = 0;
2128 result = ER_SUCCESS;
2129 } else {
2130 result = ER_RAN_ALL_LINES;
2131 }
2132
2133 switch (actresult) {
2134 case ACT_CONTINUE:
2135 chain_on = 1;
2136 break;
2137 case ACT_DONE:
2138 chain_on = 0;
2139 loops[loop_index] = 0;
2140 if (loop_index)
2141 loop_index--;
2142 break;
2143 case ACT_LOOP_BEGIN:
2144 loop_index++;
2145 if (loop_index >= MAX_LOOPS)
2146 Fatal("Loop stack overflow");
2147 loops[loop_index] = ct;
2148 chain_on = 1;
2149 break;
2150 case ACT_LOOP:
2151 if (loop_index) {
2152 ct = loops[loop_index];
2153 }
2154 break;
2155 case ACT_GAMEOVER:
2156 return ER_SUCCESS;
2157 default:
2158 break;
2159 }
2160 } else {
2161 if (verbvalue == CurrentVerb && (nounvalue == CurrentNoun || nounvalue == 0))
2162 SetBit(MATCHBIT);
2163 }
2164 }
2165
2166 ct++;
2167
2168 if (startover) {
2169 ct = 0;
2170 startover = 0;
2171 }
2172
2173 if (ct <= GameHeader.NumActions && (Actions[ct].Verb != 0)) {
2174 chain_on = 0;
2175 }
2176
2177 if (found_match && !chain_on && !keep_going)
2178 break;
2179 }
2180
2181 if (result == ER_RAN_ALL_LINES_NO_MATCH && IsSet(MATCHBIT))
2182 result = ER_RAN_ALL_LINES;
2183
2184 return result;
2185 }
2186
2187 glkunix_argumentlist_t glkunix_arguments[10];
2188
2189 int glkunix_startup_code(glkunix_startup_t *data)
2190 {
2191 int argc = data->argc;
2192 char **argv = data->argv;
2193
2194 if (argc < 1)
2195 return 0;
2196
2197 #ifdef GARGLK
2198 garglk_set_program_name("Plus 1.0");
2199 garglk_set_program_info("Plus 1.0 by Petter Sjölund");
2200 #endif
2201
2202 if (argc == 2) {
2203 game_file = argv[1];
2204
2205 const char *s;
2206 DirPathLength = 0;
2207 if ((s = strrchr(game_file, '/')) != NULL || (s = strrchr(game_file, '\\')) != NULL) {
2208 DirPathLength = (int)(s - game_file + 1);
2209 #ifdef GARGLK
2210 garglk_set_story_name(s + 1);
2211 } else {
2212 garglk_set_story_name(game_file);
2213 #endif
2214 }
2215 if (DirPathLength) {
2216 DirPath = MemAlloc(DirPathLength + 1);
2217 memcpy(DirPath, game_file, DirPathLength);
2218 DirPath[DirPathLength] = 0;
2219 debug_print("Directory path: \"%s\"\n", DirPath);
2220 }
2221 }
2222
2223 return 1;
2224 }
2225
2226 void ResizeTitleImage(void)
2227 {
2228 glui32 graphwidth, graphheight, optimal_width, optimal_height;
2229 #ifdef SPATTERLIGHT
2230 glk_window_set_background_color(Graphics, gbgcol);
2231 glk_window_clear(Graphics);
2232 #endif
2233 glk_window_get_size(Graphics, &graphwidth, &graphheight);
2234 pixel_size = OptimalPictureSize(&optimal_width, &optimal_height);
2235 x_offset = ((int)graphwidth - (int)optimal_width) / 2;
2236 right_margin = optimal_width + x_offset;
2237 y_offset = ((int)graphheight - (int)optimal_height) / 3;
2238 }
2239
2240 void DrawTitleImage(void)
2241 {
2242 DisplayInit();
2243 #ifdef SPATTERLIGHT
2244 if (!gli_enable_graphics)
2245 return;
2246 #endif
2247 glk_window_close(Top, NULL);
2248 Top = NULL;
2249 glk_window_close(Bottom, NULL);
2250 Bottom = NULL;
2251
2252 ResizeTitleImage();
2253
2254 if (glk_gestalt_ext(gestalt_GraphicsCharInput, 0, NULL, 0)) {
2255 glk_request_char_event(Graphics);
2256 } else {
2257 Bottom = glk_window_open(Graphics, winmethod_Below | winmethod_Fixed,
2258 2, wintype_TextBuffer, GLK_BUFFER_ROCK);
2259 glk_request_char_event(Bottom);
2260 }
2261
2262 if (DrawImageWithName("S000")) {
2263
2264 if (CurrentSys == SYS_APPLE2)
2265 DrawApple2ImageFromVideoMem();
2266
2267 event_t ev;
2268 do {
2269 glk_select(&ev);
2270 if (ev.type == evtype_Arrange) {
2271 #ifdef SPATTERLIGHT
2272 if (!gli_enable_graphics)
2273 break;
2274 #endif
2275 ResizeTitleImage();
2276 glk_window_clear(Graphics);
2277 DrawImageWithName("S000");
2278 if (CurrentSys == SYS_APPLE2)
2279 DrawApple2ImageFromVideoMem();
2280 } else if (ev.type == evtype_Timer) {
2281 if (ColorCyclingRunning)
2282 UpdateColorCycling();
2283 }
2284 } while (ev.type != evtype_CharInput);
2285 }
2286
2287 if (Bottom != NULL)
2288 glk_window_close(Bottom, NULL);
2289 glk_window_close(Graphics, NULL);
2290 Graphics = NULL;
2291 DisplayInit();
2292 }
2293
2294 void glk_main(void)
2295 {
2296 if (game_file == NULL)
2297 Fatal("No game file");
2298
2299 for (int i = 0; i < MAX_SYSMESS; i++) {
2300 sys[i] = sysdict[i];
2301 if (sysdict_i_am[i])
2302 sys[i] = sysdict_i_am[i];
2303 }
2304
2305 FILE *f = fopen(game_file, "r");
2306 if (f == NULL)
2307 Fatal("Cannot open game");
2308
2309 if (LoadDatabasePlaintext(f, DEBUG_ACTIONS) == UNKNOWN_GAME) {
2310 fseek(f, 0, SEEK_END);
2311 memlen = ftell(f);
2312 if (memlen == -1) {
2313 fclose(f);
2314 Fatal("Game file empty");
2315 }
2316
2317 fseek(f, 0, SEEK_SET);
2318 mem = malloc(memlen);
2319 if (!mem) {
2320 Fatal("Out of memory");
2321 }
2322
2323 memlen = fread(mem, 1, memlen, f);
2324 fclose(f);
2325
2326 if (!DetectAtari8(&mem, &memlen)) {
2327 if (!DetectST(&mem, &memlen) && !DetectApple2(&mem, &memlen) && !DetectC64(&mem, &memlen)) {
2328 Fatal("Could not detect game type");
2329 }
2330
2331 if (!LoadDatabaseBinary()) {
2332 Fatal("Could not load binary database");
2333 }
2334 }
2335
2336 if (CurrentSys == SYS_APPLE2)
2337 LookForApple2Images();
2338 }
2339
2340 #ifdef SPATTERLIGHT
2341 UpdateSettings();
2342 if (gli_determinism)
2343 srand(1234);
2344 else
2345 #endif
2346 srand((unsigned int)time(NULL));
2347
2348 DrawTitleImage();
2349 UpdateSettings();
2350
2351 InitAnimationBuffer();
2352 InitialState = SaveCurrentState();
2353
2354 while (1) {
2355 glk_tick();
2356
2357 if (should_restart)
2358 RestartGame();
2359
2360 if (IsSet(STOPTIMEBIT) || JustRestored) {
2361 ResetBit(STOPTIMEBIT);
2362 } else {
2363 PerformImplicit();
2364 if (!should_restart)
2365 SaveUndo();
2366 }
2367
2368 Look(0);
2369
2370 if (should_restart)
2371 continue;
2372
2373 // For Thing in tar image
2374 if (JustRestored && SavedImgType == IMG_OBJECT) {
2375 DrawItemImage(SavedImgIndex);
2376 }
2377
2378 JustRestored = 0;
2379 JustRestarted = 0;
2380
2381 if (GetInput() == 1)
2382 continue;
2383
2384 SetCountersFromInput();
2385
2386 LastVerb = CurrentVerb;
2387 LastNoun = CurrentNoun;
2388 LastPrep = CurrentPrep;
2389 LastPartp = CurrentPartp;
2390 LastNoun2 = CurrentNoun2;
2391 LastAdverb = CurrentAdverb;
2392
2393 ClearFrames();
2394
2395 CommandResultType result = PerformExplicit();
2396
2397 if (result == ER_RAN_ALL_LINES_NO_MATCH || result == ER_RAN_ALL_LINES || IsSet(MATCHBIT)) {
2398 if (result == ER_RAN_ALL_LINES_NO_MATCH)
2399 SystemMessage(I_DONT_UNDERSTAND);
2400 else
2401 SystemMessage(YOU_CANT_DO_THAT_YET);
2402 StopProcessingCommand();
2403 }
2404
2405 JustStarted = 0;
2406 }
2407 }