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