Implement and document %V escape so version only needs to be set once.
[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     // Print the message.
247     printf("%s\n", rendered);
248
249     free(rendered);
250 }
251
252 void speak(const char* msg, ...)
253 {
254     va_list ap;
255     va_start(ap, msg);
256     vspeak(msg, ap);
257     va_end(ap);
258 }
259
260 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
261 /* Find the skip+1st message from msg and print it.  Modes are:
262  * feel = for inventory, what you can touch
263  * look = the long description for the state the object is in
264  * listen = the sound for the state the object is in
265  * study = text on the object. */
266 {
267     va_list ap;
268     va_start(ap, skip);
269     switch (mode) {
270     case touch:
271         vspeak(objects[msg].inventory, ap);
272         break;
273     case look:
274         vspeak(objects[msg].descriptions[skip], ap);
275         break;
276     case hear:
277         vspeak(objects[msg].sounds[skip], ap);
278         break;
279     case study:
280         vspeak(objects[msg].texts[skip], ap);
281         break;
282     case change:
283         vspeak(objects[msg].changes[skip], ap);
284         break;
285     }
286     va_end(ap);
287 }
288
289 void rspeak(vocab_t i, ...)
290 /* Print the i-th "random" message (section 6 of database). */
291 {
292     va_list ap;
293     va_start(ap, i);
294     vspeak(arbitrary_messages[i], ap);
295     va_end(ap);
296 }
297
298 void echo_input(FILE* destination, char* input_prompt, char* input)
299 {
300     size_t len = strlen(input_prompt) + strlen(input) + 1;
301     char* prompt_and_input = (char*) xmalloc(len);
302     strcpy(prompt_and_input, input_prompt);
303     strcat(prompt_and_input, input);
304     fprintf(destination, "%s\n", prompt_and_input);
305     free(prompt_and_input);
306 }
307
308 int word_count(char* s)
309 {
310     char* copy = xstrdup(s);
311     char delims[] = " \t";
312     int count = 0;
313     char* word;
314
315     word = strtok(copy, delims);
316     while (word != NULL) {
317         word = strtok(NULL, delims);
318         ++count;
319     }
320     free(copy);
321     return (count);
322 }
323
324 char* get_input()
325 {
326     // Set up the prompt
327     char input_prompt[] = "> ";
328     if (!prompt)
329         input_prompt[0] = '\0';
330
331     // Print a blank line if game.blklin tells us to.
332     if (game.blklin == true)
333         printf("\n");
334
335     char* input;
336     while (true) {
337         if (editline)
338             input = linenoise(input_prompt);
339         else {
340             input = NULL;
341             size_t n = 0;
342             if (isatty(0))
343                 // LCOV_EXCL_START
344                 // Should be unreachable in tests, as they will use a non-interactive shell.
345                 printf("%s", input_prompt);
346             // LCOV_EXCL_STOP
347             ssize_t numread = getline(&input, &n, stdin);
348             if (numread == -1) // Got EOF; return with it.
349                 return (NULL);
350         }
351
352         if (input == NULL) // Got EOF; return with it.
353             return (input);
354         else if (input[0] == '#') // Ignore comments.
355             continue;
356         else // We have a 'normal' line; leave the loop.
357             break;
358     }
359
360     // Strip trailing newlines from the input
361     input[strcspn(input, "\n")] = 0;
362
363     linenoiseHistoryAdd(input);
364
365     if (!isatty(0))
366         echo_input(stdout, input_prompt, input);
367
368     if (logfp)
369         echo_input(logfp, input_prompt, input);
370
371     return (input);
372 }
373
374 bool silent_yes()
375 {
376     char* reply;
377     bool outcome;
378
379     for (;;) {
380         reply = get_input();
381         if (reply == NULL) {
382             // LCOV_EXCL_START
383             // Should be unreachable. Reply should never be NULL
384             linenoiseFree(reply);
385             exit(EXIT_SUCCESS);
386             // LCOV_EXCL_STOP
387         }
388
389         char* firstword = (char*) xmalloc(strlen(reply) + 1);
390         sscanf(reply, "%s", firstword);
391
392         for (int i = 0; i < (int)strlen(firstword); ++i)
393             firstword[i] = tolower(firstword[i]);
394
395         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
396         int y = strncmp("y", firstword, sizeof("y") - 1);
397         int no = strncmp("no", firstword, sizeof("no") - 1);
398         int n = strncmp("n", firstword, sizeof("n") - 1);
399
400         free(firstword);
401
402         if (yes == 0 || y == 0) {
403             outcome = true;
404             break;
405         } else if (no == 0 || n == 0) {
406             outcome = false;
407             break;
408         } else
409             rspeak(PLEASE_ANSWER);
410     }
411     linenoiseFree(reply);
412     return (outcome);
413 }
414
415
416 bool yes(const char* question, const char* yes_response, const char* no_response)
417 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
418  *  if no, print Z and return false. */
419 {
420     char* reply;
421     bool outcome;
422
423     for (;;) {
424         speak(question);
425
426         reply = get_input();
427         if (reply == NULL) {
428             // LCOV_EXCL_START
429             // Should be unreachable. Reply should never be NULL
430             linenoiseFree(reply);
431             exit(EXIT_SUCCESS);
432             // LCOV_EXCL_STOP
433         }
434
435         char* firstword = (char*) xmalloc(strlen(reply) + 1);
436         sscanf(reply, "%s", firstword);
437
438         for (int i = 0; i < (int)strlen(firstword); ++i)
439             firstword[i] = tolower(firstword[i]);
440
441         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
442         int y = strncmp("y", firstword, sizeof("y") - 1);
443         int no = strncmp("no", firstword, sizeof("no") - 1);
444         int n = strncmp("n", firstword, sizeof("n") - 1);
445
446         free(firstword);
447
448         if (yes == 0 || y == 0) {
449             speak(yes_response);
450             outcome = true;
451             break;
452         } else if (no == 0 || n == 0) {
453             speak(no_response);
454             outcome = false;
455             break;
456         } else
457             rspeak(PLEASE_ANSWER);
458     }
459     linenoiseFree(reply);
460     return (outcome);
461 }
462
463 /*  Data structure  routines */
464
465 int get_motion_vocab_id(const char* word)
466 // Return the first motion number that has 'word' as one of its words.
467 {
468     for (int i = 0; i < NMOTIONS; ++i) {
469         for (int j = 0; j < motions[i].words.n; ++j) {
470             if (strcasecmp(word, motions[i].words.strs[j]) == 0)
471                 return (i);
472         }
473     }
474     // If execution reaches here, we didn't find the word.
475     return (WORD_NOT_FOUND);
476 }
477
478 int get_object_vocab_id(const char* word)
479 // Return the first object number that has 'word' as one of its words.
480 {
481     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
482         for (int j = 0; j < objects[i].words.n; ++j) {
483             if (strcasecmp(word, objects[i].words.strs[j]) == 0)
484                 return (i);
485         }
486     }
487     // If execution reaches here, we didn't find the word.
488     return (WORD_NOT_FOUND);
489 }
490
491 int get_action_vocab_id(const char* word)
492 // Return the first motion number that has 'word' as one of its words.
493 {
494     for (int i = 0; i < NACTIONS; ++i) {
495         for (int j = 0; j < actions[i].words.n; ++j) {
496             if (strcasecmp(word, actions[i].words.strs[j]) == 0)
497                 return (i);
498         }
499     }
500     // If execution reaches here, we didn't find the word.
501     return (WORD_NOT_FOUND);
502 }
503
504 int get_special_vocab_id(const char* word)
505 // Return the first special number that has 'word' as one of its words.
506 {
507     for (int i = 0; i < NSPECIALS; ++i) {
508         for (int j = 0; j < specials[i].words.n; ++j) {
509             if (strcasecmp(word, specials[i].words.strs[j]) == 0)
510                 return (i);
511         }
512     }
513     // If execution reaches here, we didn't find the word.
514     return (WORD_NOT_FOUND);
515 }
516
517 long get_vocab_id(const char* word)
518 // Search the vocab categories in order for the supplied word.
519 {
520     long ref_num;
521
522     ref_num = get_motion_vocab_id(word);
523     if (ref_num != WORD_NOT_FOUND)
524         return (ref_num + 0); // FIXME: replace with a proper hash
525
526     ref_num = get_object_vocab_id(word);
527     if (ref_num != WORD_NOT_FOUND)
528         return (ref_num + 1000); // FIXME: replace with a proper hash
529
530     ref_num = get_action_vocab_id(word);
531     if (ref_num != WORD_NOT_FOUND)
532         return (ref_num + 2000); // FIXME: replace with a proper hash
533
534     ref_num = get_special_vocab_id(word);
535     if (ref_num != WORD_NOT_FOUND)
536         return (ref_num + 3000); // FIXME: replace with a proper hash
537
538     // Check for the reservoir magic word.
539     if (strcasecmp(word, game.zzword) == 0)
540         return (PART + 2000); // FIXME: replace with a proper hash
541
542     return (WORD_NOT_FOUND);
543 }
544
545 void juggle(long object)
546 /*  Juggle an object by picking it up and putting it down again, the purpose
547  *  being to get the object to the front of the chain of things at its loc. */
548 {
549     long i, j;
550
551     i = game.place[object];
552     j = game.fixed[object];
553     move(object, i);
554     move(object + NOBJECTS, j);
555 }
556
557 void move(long object, long where)
558 /*  Place any object anywhere by picking it up and dropping it.  May
559  *  already be toting, in which case the carry is a no-op.  Mustn't
560  *  pick up objects which are not at any loc, since carry wants to
561  *  remove objects from game.atloc chains. */
562 {
563     long from;
564
565     if (object > NOBJECTS)
566         from = game.fixed[object - NOBJECTS];
567     else
568         from = game.place[object];
569     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
570         carry(object, from);
571     drop(object, where);
572 }
573
574 long put(long object, long where, long pval)
575 /*  PUT is the same as MOVE, except it returns a value used to set up the
576  *  negated game.prop values for the repository objects. */
577 {
578     move(object, where);
579     return (-1) - pval;;
580 }
581
582 void carry(long object, long where)
583 /*  Start toting an object, removing it from the list of things at its former
584  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
585  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
586 {
587     long temp;
588
589     if (object <= NOBJECTS) {
590         if (game.place[object] == CARRIED)
591             return;
592         game.place[object] = CARRIED;
593         ++game.holdng;
594     }
595     if (game.atloc[where] == object) {
596         game.atloc[where] = game.link[object];
597         return;
598     }
599     temp = game.atloc[where];
600     while (game.link[temp] != object) {
601         temp = game.link[temp];
602     }
603     game.link[temp] = game.link[object];
604 }
605
606 void drop(long object, long where)
607 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
608  *  game.holdng if the object was being toted. */
609 {
610     if (object > NOBJECTS)
611         game.fixed[object - NOBJECTS] = where;
612     else {
613         if (game.place[object] == CARRIED)
614             --game.holdng;
615         game.place[object] = where;
616     }
617     if (where <= 0)
618         return;
619     game.link[object] = game.atloc[where];
620     game.atloc[where] = object;
621 }
622
623 long atdwrf(long where)
624 /*  Return the index of first dwarf at the given location, zero if no dwarf is
625  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
626  *  the pirate (6th dwarf). */
627 {
628     long at;
629
630     at = 0;
631     if (game.dflag < 2)
632         return (at);
633     at = -1;
634     for (long i = 1; i <= NDWARVES - 1; i++) {
635         if (game.dloc[i] == where)
636             return i;
637         if (game.dloc[i] != 0)
638             at = 0;
639     }
640     return (at);
641 }
642
643 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
644  *  randrange, RNDVOC) */
645
646 long setbit(long bit)
647 /*  Returns 2**bit for use in constructing bit-masks. */
648 {
649     return (1L << bit);
650 }
651
652 bool tstbit(long mask, int bit)
653 /*  Returns true if the specified bit is set in the mask. */
654 {
655     return (mask & (1 << bit)) != 0;
656 }
657
658 void set_seed(long seedval)
659 /* Set the LCG seed */
660 {
661     game.lcg_x = (unsigned long) seedval % game.lcg_m;
662 }
663
664 unsigned long get_next_lcg_value(void)
665 /* Return the LCG's current value, and then iterate it. */
666 {
667     unsigned long old_x = game.lcg_x;
668     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
669     return old_x;
670 }
671
672 long randrange(long range)
673 /* Return a random integer from [0, range). */
674 {
675     return range * get_next_lcg_value() / game.lcg_m;
676 }
677
678 void make_zzword(char zzword[6])
679 {
680     for (int i = 0; i < 5; ++i) {
681         zzword[i] = 'A' + randrange(26);
682     }
683     zzword[1] = '\''; // force second char to apostrophe
684     zzword[5] = '\0';
685 }
686
687 void datime(long* d, long* t)
688 {
689     struct timeval tv;
690     gettimeofday(&tv, NULL);
691     *d = (long) tv.tv_sec;
692     *t = (long) tv.tv_usec;
693 }
694
695 // LCOV_EXCL_START
696 void bug(enum bugtype num, const char *error_string)
697 {
698     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
699     exit(EXIT_FAILURE);
700 }
701 // LCOV_EXCL_STOP
702
703 /* end */