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