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