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