Improve comments.
[open-adventure.git] / misc.c
1 /*
2  * I/O and support riutines.
3  *
4  * Copyright (c) 1977, 2005 by Will Crowther and Don Woods
5  * Copyright (c) 2017 by Eric S. Raymond
6  * SPDX-License-Identifier: BSD-2-clause
7  */
8
9 #include <unistd.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdarg.h>
14 #include <sys/time.h>
15 #include <ctype.h>
16 #include <editline/readline.h>
17 #include <inttypes.h>
18
19 #include "advent.h"
20 #include "dungeon.h"
21
22 static void* xcalloc(size_t size)
23 {
24     void* ptr = calloc(size, 1);
25     if (ptr == NULL) {
26         // LCOV_EXCL_START
27         // exclude from coverage analysis because we can't simulate an out of memory error in testing
28         fprintf(stderr, "Out of memory!\n");
29         exit(EXIT_FAILURE);
30         // LCOV_EXCL_STOP
31     }
32     return (ptr);
33 }
34
35 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
36
37 static void vspeak(const char* msg, bool blank, va_list ap)
38 /* Engine for various speak functions */
39 {
40     // Do nothing if we got a null pointer.
41     if (msg == NULL)
42         return;
43
44     // Do nothing if we got an empty string.
45     if (strlen(msg) == 0)
46         return;
47
48     if (blank == true)
49         printf("\n");
50
51     int msglen = strlen(msg);
52
53     // Rendered string
54     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
55     char* rendered = xcalloc(size);
56     char* renderp = rendered;
57
58     // Handle format specifiers (including the custom %S) by
59     // adjusting the parameter accordingly, and replacing the
60     // specifier with %s.
61     bool pluralize = false;
62     for (int i = 0; i < msglen; i++) {
63         if (msg[i] != '%') {
64             /* Ugh.  Least obtrusive way to deal with artifacts "on the floor"
65              * being dropped outside of both cave and building. */
66             if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
67                 strcpy(renderp, "ground");
68                 renderp += 6;
69                 i += 4;
70                 size -= 5;
71             } else {
72                 *renderp++ = msg[i];
73                 size--;
74             }
75         } else {
76             i++;
77             // Integer specifier.
78             if (msg[i] == 'd') {
79                 int32_t arg = va_arg(ap, int32_t);
80                 int ret = snprintf(renderp, size, "%" PRId32, arg);
81                 if (ret < size) {
82                     renderp += ret;
83                     size -= ret;
84                 }
85                 pluralize = (arg != 1);
86             }
87
88             // Unmodified string specifier.
89             if (msg[i] == 's') {
90                 char *arg = va_arg(ap, char *);
91                 strncat(renderp, arg, size - 1);
92                 size_t len = strlen(renderp);
93                 renderp += len;
94                 size -= len;
95             }
96
97             // Singular/plural specifier.
98             if (msg[i] == 'S') {
99                 // look at the *previous* numeric parameter
100                 if (pluralize) {
101                     *renderp++ = 's';
102                     size--;
103                 }
104             }
105
106             // LCOV_EXCL_START - doesn't occur in test suite.
107             /* Version specifier */
108             if (msg[i] == 'V') {
109                 strcpy(renderp, VERSION);
110                 size_t len = strlen(VERSION);
111                 renderp += len;
112                 size -= len;
113             }
114             // LCOV_EXCL_STOP
115         }
116     }
117     *renderp = 0;
118
119     // Print the message.
120     printf("%s\n", rendered);
121
122     free(rendered);
123 }
124
125 void speak(const char* msg, ...)
126 /* speak a specified string */
127 {
128     va_list ap;
129     va_start(ap, msg);
130     vspeak(msg, true, ap);
131     va_end(ap);
132 }
133
134 void sspeak(const int msg, ...)
135 /* Speak a message from the arbitrary-messages list */
136 {
137     va_list ap;
138     va_start(ap, msg);
139     fputc('\n', stdout);
140     vprintf(arbitrary_messages[msg], ap);
141     fputc('\n', stdout);
142     va_end(ap);
143 }
144
145 void pspeak(vocab_t msg, enum speaktype mode, bool blank, int skip, ...)
146 /* Find the skip+1st message from msg and print it.  Modes are:
147  * feel = for inventory, what you can touch
148  * look = the full description for the state the object is in
149  * listen = the sound for the state the object is in
150  * study = text on the object. */
151 {
152     va_list ap;
153     va_start(ap, skip);
154     switch (mode) {
155     case touch:
156         vspeak(objects[msg].inventory, blank, ap);
157         break;
158     case look:
159         vspeak(objects[msg].descriptions[skip], blank, ap);
160         break;
161     case hear:
162         vspeak(objects[msg].sounds[skip], blank, ap);
163         break;
164     case study:
165         vspeak(objects[msg].texts[skip], blank, ap);
166         break;
167     case change:
168         vspeak(objects[msg].changes[skip], blank, ap);
169         break;
170     }
171     va_end(ap);
172 }
173
174 void rspeak(vocab_t i, ...)
175 /* Print the i-th "random" message (section 6 of database). */
176 {
177     va_list ap;
178     va_start(ap, i);
179     vspeak(arbitrary_messages[i], true, ap);
180     va_end(ap);
181 }
182
183 void echo_input(FILE* destination, const char* input_prompt, const char* input)
184 {
185     size_t len = strlen(input_prompt) + strlen(input) + 1;
186     char* prompt_and_input = (char*) xcalloc(len);
187     strcpy(prompt_and_input, input_prompt);
188     strcat(prompt_and_input, input);
189     fprintf(destination, "%s\n", prompt_and_input);
190     free(prompt_and_input);
191 }
192
193 static int word_count(char* str)
194 {
195     char delims[] = " \t";
196     int count = 0;
197     int inblanks = true;
198
199     for (char *s = str; *s; s++)
200         if (inblanks) {
201             if (strchr(delims, *s) == 0) {
202                 ++count;
203                 inblanks = false;
204             }
205         } else {
206             if (strchr(delims, *s) != 0) {
207                 inblanks = true;
208             }
209         }
210
211     return (count);
212 }
213
214 static char* get_input(void)
215 {
216     // Set up the prompt
217     char input_prompt[] = PROMPT;
218     if (!settings.prompt)
219         input_prompt[0] = '\0';
220
221     // Print a blank line
222     printf("\n");
223
224     char* input;
225     while (true) {
226         input = myreadline(input_prompt);
227
228         if (input == NULL) // Got EOF; return with it.
229             return (input);
230         if (input[0] == '#') { // Ignore comments.
231             free(input);
232             continue;
233         }
234         // We have a 'normal' line; leave the loop.
235         break;
236     }
237
238     // Strip trailing newlines from the input
239     input[strcspn(input, "\n")] = 0;
240
241     add_history(input);
242
243     if (!isatty(0))
244         echo_input(stdout, input_prompt, input);
245
246     if (settings.logfp)
247         echo_input(settings.logfp, "", input);
248
249     return (input);
250 }
251
252 bool silent_yes_or_no(void)
253 {
254     bool outcome = false;
255
256     for (;;) {
257         char* reply = get_input();
258         if (reply == NULL) {
259             // LCOV_EXCL_START
260             // Should be unreachable. Reply should never be NULL
261             free(reply);
262             exit(EXIT_SUCCESS);
263             // LCOV_EXCL_STOP
264         }
265         if (strlen(reply) == 0) {
266             free(reply);
267             rspeak(PLEASE_ANSWER);
268             continue;
269         }
270
271         char* firstword = (char*) xcalloc(strlen(reply) + 1);
272         sscanf(reply, "%s", firstword);
273
274         free(reply);
275
276         for (int i = 0; i < (int)strlen(firstword); ++i)
277             firstword[i] = tolower(firstword[i]);
278
279         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
280         int y = strncmp("y", firstword, sizeof("y") - 1);
281         int no = strncmp("no", firstword, sizeof("no") - 1);
282         int n = strncmp("n", firstword, sizeof("n") - 1);
283
284         free(firstword);
285
286         if (yes == 0 ||
287             y == 0) {
288             outcome = true;
289             break;
290         } else if (no == 0 ||
291                    n == 0) {
292             outcome = false;
293             break;
294         } else
295             rspeak(PLEASE_ANSWER);
296     }
297     return (outcome);
298 }
299
300
301 bool yes_or_no(const char* question, const char* yes_response, const char* no_response)
302 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
303  *  if no, print Z and return false. */
304 {
305     bool outcome = false;
306
307     for (;;) {
308         speak(question);
309
310         char* reply = get_input();
311         if (reply == NULL) {
312             // LCOV_EXCL_START
313             // Should be unreachable. Reply should never be NULL
314             free(reply);
315             exit(EXIT_SUCCESS);
316             // LCOV_EXCL_STOP
317         }
318
319         if (strlen(reply) == 0) {
320             free(reply);
321             rspeak(PLEASE_ANSWER);
322             continue;
323         }
324
325         char* firstword = (char*) xcalloc(strlen(reply) + 1);
326         sscanf(reply, "%s", firstword);
327
328         free(reply);
329
330         for (int i = 0; i < (int)strlen(firstword); ++i)
331             firstword[i] = tolower(firstword[i]);
332
333         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
334         int y = strncmp("y", firstword, sizeof("y") - 1);
335         int no = strncmp("no", firstword, sizeof("no") - 1);
336         int n = strncmp("n", firstword, sizeof("n") - 1);
337
338         free(firstword);
339
340         if (yes == 0 ||
341             y == 0) {
342             speak(yes_response);
343             outcome = true;
344             break;
345         } else if (no == 0 ||
346                    n == 0) {
347             speak(no_response);
348             outcome = false;
349             break;
350         } else
351             rspeak(PLEASE_ANSWER);
352
353     }
354
355     return (outcome);
356 }
357
358 /*  Data structure  routines */
359
360 static int get_motion_vocab_id(const char* word)
361 // Return the first motion number that has 'word' as one of its words.
362 {
363     for (int i = 0; i < NMOTIONS; ++i) {
364         for (int j = 0; j < motions[i].words.n; ++j) {
365             if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
366                     strchr(ignore, word[0]) == NULL ||
367                     !settings.oldstyle))
368                 return (i);
369         }
370     }
371     // If execution reaches here, we didn't find the word.
372     return (WORD_NOT_FOUND);
373 }
374
375 static int get_object_vocab_id(const char* word)
376 // Return the first object number that has 'word' as one of its words.
377 {
378     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
379         for (int j = 0; j < objects[i].words.n; ++j) {
380             if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
381                 return (i);
382         }
383     }
384     // If execution reaches here, we didn't find the word.
385     return (WORD_NOT_FOUND);
386 }
387
388 static int get_action_vocab_id(const char* word)
389 // Return the first motion number that has 'word' as one of its words.
390 {
391     for (int i = 0; i < NACTIONS; ++i) {
392         for (int j = 0; j < actions[i].words.n; ++j) {
393             if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
394                     strchr(ignore, word[0]) == NULL ||
395                     !settings.oldstyle))
396                 return (i);
397         }
398     }
399     // If execution reaches here, we didn't find the word.
400     return (WORD_NOT_FOUND);
401 }
402
403 static bool is_valid_int(const char *str)
404 /* Returns true if the string passed in is represents a valid integer,
405  * that could then be parsed by atoi() */
406 {
407     // Handle negative number
408     if (*str == '-')
409         ++str;
410
411     // Handle empty string or just "-". Should never reach this
412     // point, because this is only used with transitive verbs.
413     if (!*str)
414         return false; // LCOV_EXCL_LINE
415
416     // Check for non-digit chars in the rest of the stirng.
417     while (*str) {
418         if (!isdigit(*str))
419             return false;
420         else
421             ++str;
422     }
423
424     return true;
425 }
426
427 static void get_vocab_metadata(const char* word, vocab_t* id, word_type_t* type)
428 {
429     /* Check for an empty string */
430     if (strncmp(word, "", sizeof("")) == 0) {
431         *id = WORD_EMPTY;
432         *type = NO_WORD_TYPE;
433         return;
434     }
435
436     vocab_t ref_num;
437
438     ref_num = get_motion_vocab_id(word);
439     if (ref_num != WORD_NOT_FOUND) {
440         *id = ref_num;
441         *type = MOTION;
442         return;
443     }
444
445     ref_num = get_object_vocab_id(word);
446     if (ref_num != WORD_NOT_FOUND) {
447         *id = ref_num;
448         *type = OBJECT;
449         return;
450     }
451
452     ref_num = get_action_vocab_id(word);
453     if (ref_num != WORD_NOT_FOUND) {
454         *id = ref_num;
455         *type = ACTION;
456         return;
457     }
458
459     // Check for the reservoir magic word.
460     if (strcasecmp(word, game.zzword) == 0) {
461         *id = PART;
462         *type = ACTION;
463         return;
464     }
465
466     // Check words that are actually numbers.
467     if (is_valid_int(word)) {
468         *id = WORD_EMPTY;
469         *type = NUMERIC;
470         return;
471     }
472
473     *id = WORD_NOT_FOUND;
474     *type = NO_WORD_TYPE;
475     return;
476 }
477
478 static void tokenize(char* raw, command_t *cmd)
479 {
480     /*
481      * Be caereful about modifing this. We do not want to nuke the
482      * the speech part or ID from the previous turn.
483      */
484     memset(&cmd->word[0].raw, '\0', sizeof(cmd->word[0].raw));
485     memset(&cmd->word[1].raw, '\0', sizeof(cmd->word[1].raw));
486
487     /* Bound prefix on the %s would be needed to prevent buffer
488      * overflow.  but we shortstop this more simply by making each
489      * raw-input buffer as int as the entire input buffer. */
490     sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
491
492     /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
493      * effect on raw tokens of packing them into sixbit characters, 5
494      * to a 32-bit word.  This is something the FORTRAN version did
495      * becuse archaic FORTRAN had no string types.  Don Wood's
496      * mechanical translation of 2.5 to C retained the packing and
497      * thus this misfeature.
498      *
499      * It's philosophically questionable whether this is the right
500      * thing to do even in oldstyle mode.  On one hand, the text
501      * mangling was not authorial intent, but a result of limitations
502      * in their tools. On the other, not simulating this misbehavior
503      * goes against the goal of making oldstyle as accurate as
504      * possible an emulation of the original UI.
505      */
506     if (settings.oldstyle) {
507         cmd->word[0].raw[TOKLEN + TOKLEN] = cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
508         for (size_t i = 0; i < strlen(cmd->word[0].raw); i++)
509             cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
510         for (size_t i = 0; i < strlen(cmd->word[1].raw); i++)
511             cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
512     }
513
514     /* populate command with parsed vocabulary metadata */
515     get_vocab_metadata(cmd->word[0].raw, &(cmd->word[0].id), &(cmd->word[0].type));
516     get_vocab_metadata(cmd->word[1].raw, &(cmd->word[1].id), &(cmd->word[1].type));
517     cmd->state = TOKENIZED;
518 }
519
520 bool get_command_input(command_t *command)
521 /* Get user input on stdin, parse and map to command */
522 {
523     char inputbuf[LINESIZE];
524     char* input;
525
526     for (;;) {
527         input = get_input();
528         if (input == NULL)
529             return false;
530         if (word_count(input) > 2) {
531             rspeak(TWO_WORDS);
532             free(input);
533             continue;
534         }
535         if (strcmp(input, "") != 0)
536             break;
537         free(input);
538     }
539
540     strncpy(inputbuf, input, LINESIZE - 1);
541     free(input);
542
543     tokenize(inputbuf, command);
544
545 #ifdef GDEBUG
546     /* Needs to stay synced with enum word_type_t */
547     const char *types[] = {"NO_WORD_TYPE", "MOTION", "OBJECT", "ACTION", "NUMERIC"};
548     /* needs to stay synced with enum speechpart */
549     const char *roles[] = {"unknown", "intransitive", "transitive"};
550     printf("Command: role = %s type1 = %s, id1 = %d, type2 = %s, id2 = %d\n",
551            roles[command->part],
552            types[command->word[0].type],
553            command->word[0].id,
554            types[command->word[1].type],
555            command->word[1].id);
556 #endif
557
558     command->state = GIVEN;
559     return true;
560 }
561
562 void clear_command(command_t *cmd)
563 /* Resets the state of the command to empty */
564 {
565     cmd->verb = ACT_NULL;
566     cmd->part = unknown;
567     game.oldobj = cmd->obj;
568     cmd->obj = NO_OBJECT;
569     cmd->state = EMPTY;
570 }
571
572
573 void juggle(obj_t object)
574 /*  Juggle an object by picking it up and putting it down again, the purpose
575  *  being to get the object to the front of the chain of things at its loc. */
576 {
577     loc_t i, j;
578
579     i = game.place[object];
580     j = game.fixed[object];
581     move(object, i);
582     move(object + NOBJECTS, j);
583 }
584
585 void move(obj_t object, loc_t where)
586 /*  Place any object anywhere by picking it up and dropping it.  May
587  *  already be toting, in which case the carry is a no-op.  Mustn't
588  *  pick up objects which are not at any loc, since carry wants to
589  *  remove objects from game.atloc chains. */
590 {
591     loc_t from;
592
593     if (object > NOBJECTS)
594         from = game.fixed[object - NOBJECTS];
595     else
596         from = game.place[object];
597     /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
598     if (from != LOC_NOWHERE && from != CARRIED)
599         carry(object, from);
600     drop(object, where);
601 }
602
603 loc_t put(obj_t object, loc_t where, int pval)
604 /*  put() is the same as move(), except it returns a value used to set up the
605  *  negated game.prop values for the repository objects. */
606 {
607     move(object, where);
608     return STASHED(pval);
609 }
610
611 void carry(obj_t object, loc_t where)
612 /*  Start toting an object, removing it from the list of things at its former
613  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
614  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
615 {
616     int temp;
617
618     if (object <= NOBJECTS) {
619         if (game.place[object] == CARRIED)
620             return;
621         game.place[object] = CARRIED;
622
623         if (object != BIRD)
624             ++game.holdng;
625     }
626     if (game.atloc[where] == object) {
627         game.atloc[where] = game.link[object];
628         return;
629     }
630     temp = game.atloc[where];
631     while (game.link[temp] != object) {
632         temp = game.link[temp];
633     }
634     game.link[temp] = game.link[object];
635 }
636
637 void drop(obj_t object, loc_t where)
638 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
639  *  game.holdng if the object was being toted. No state change on the object. */
640 {
641     if (object > NOBJECTS)
642         game.fixed[object - NOBJECTS] = where;
643     else {
644         if (game.place[object] == CARRIED)
645             if (object != BIRD)
646                 /* The bird has to be weightless.  This ugly hack (and the
647                  * corresponding code in the drop function) brought to you
648                  * by the fact that when the bird is caged, we need to be able
649                  * to either 'take bird' or 'take cage' and have the right thing
650                  * happen.
651                  */
652                 --game.holdng;
653         game.place[object] = where;
654     }
655     if (where == LOC_NOWHERE ||
656         where == CARRIED)
657         return;
658     game.link[object] = game.atloc[where];
659     game.atloc[where] = object;
660 }
661
662 int atdwrf(loc_t where)
663 /*  Return the index of first dwarf at the given location, zero if no dwarf is
664  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
665  *  the pirate (6th dwarf). */
666 {
667     int at;
668
669     at = 0;
670     if (game.dflag < 2)
671         return at;
672     at = -1;
673     for (int i = 1; i <= NDWARVES - 1; i++) {
674         if (game.dloc[i] == where)
675             return i;
676         if (game.dloc[i] != 0)
677             at = 0;
678     }
679     return at;
680 }
681
682 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
683  *  randrange) */
684
685 int setbit(int bit)
686 /*  Returns 2**bit for use in constructing bit-masks. */
687 {
688     return (1L << bit);
689 }
690
691 bool tstbit(int mask, int bit)
692 /*  Returns true if the specified bit is set in the mask. */
693 {
694     return (mask & (1 << bit)) != 0;
695 }
696
697 void set_seed(int32_t seedval)
698 /* Set the LCG seed */
699 {
700     game.lcg_x = seedval % LCG_M;
701     if (game.lcg_x < 0) {
702         game.lcg_x = LCG_M + game.lcg_x;
703     }
704     // once seed is set, we need to generate the Z`ZZZ word
705     for (int i = 0; i < 5; ++i) {
706         game.zzword[i] = 'A' + randrange(26);
707     }
708     game.zzword[1] = '\''; // force second char to apostrophe
709     game.zzword[5] = '\0';
710 }
711
712 static int32_t get_next_lcg_value(void)
713 /* Return the LCG's current value, and then iterate it. */
714 {
715     int32_t old_x = game.lcg_x;
716     game.lcg_x = (LCG_A * game.lcg_x + LCG_C) % LCG_M;
717     return old_x;
718 }
719
720 int32_t randrange(int32_t range)
721 /* Return a random integer from [0, range). */
722 {
723     return range * get_next_lcg_value() / LCG_M;
724 }
725
726 // LCOV_EXCL_START
727 void bug(enum bugtype num, const char *error_string)
728 {
729     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
730     exit(EXIT_FAILURE);
731 }
732 // LCOV_EXCL_STOP
733
734 void state_change(obj_t obj, int state)
735 /* Object must have a change-message list for this to be useful; only some do */
736 {
737     game.prop[obj] = state;
738     pspeak(obj, change, true, state);
739 }
740
741 /* end */