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