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