Implement and document state-changes messages in YAML.
[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 "database.h"
11 #include "linenoise/linenoise.h"
12 #include "newdb.h"
13
14 void* xmalloc(size_t size)
15 {
16     void* ptr = malloc(size);
17     if (ptr == NULL) {
18         // LCOV_EXCL_START
19         // exclude from coverage analysis because we can't simulate an out of memory error in testing
20         fprintf(stderr, "Out of memory!\n");
21         exit(EXIT_FAILURE);
22         // LCOV_EXCL_STOP 
23     }
24     return (ptr);
25 }
26
27 void packed_to_token(long packed, char token[6])
28 {
29     // Unpack and map back to ASCII.
30     for (int i = 0; i < 5; ++i) {
31         char advent = (packed >> i * 6) & 63;
32         token[4 - i] = advent_to_ascii[(int) advent];
33     }
34
35     // Ensure the last character is \0.
36     token[5] = '\0';
37
38     // Replace trailing whitespace with \0.
39     for (int i = 4; i >= 0; --i) {
40         if (token[i] == ' ' || token[i] == '\t')
41             token[i] = '\0';
42         else
43             break;
44     }
45 }
46
47 /* Hide the fact that wods are corrently packed longs */
48
49 bool wordeq(token_t a, token_t b)
50 {
51     return a == b;
52 }
53
54 bool wordempty(token_t a)
55 {
56     return a == 0;
57 }
58
59 void wordclear(token_t *v)
60 {
61     *v = 0;
62 }
63
64 /*  I/O routines (speak, pspeak, rspeak, GETIN, YES) */
65
66 void vspeak(const char* msg, va_list ap)
67 {
68     // Do nothing if we got a null pointer.
69     if (msg == NULL)
70         return;
71
72     // Do nothing if we got an empty string.
73     if (strlen(msg) == 0)
74         return;
75
76     // Print a newline if the global game.blklin says to.
77     if (game.blklin == true)
78         printf("\n");
79
80     int msglen = strlen(msg);
81
82     // Rendered string
83     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
84     char* rendered = xmalloc(size);
85     char* renderp = rendered;
86
87     // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
88     long previous_arg = 0;
89     for (int i = 0; i < msglen; i++) {
90         if (msg[i] != '%') {
91             *renderp++ = msg[i];
92             size--;
93         } else {
94             long arg = va_arg(ap, long);
95             if (arg == -1)
96               arg = 0;
97             i++;
98             // Integer specifier. In order to accommodate the fact that PARMS can have both legitimate integers *and* packed tokens, stringify everything. Future work may eliminate the need for this.
99             if (msg[i] == 'd') {
100                 int ret = snprintf(renderp, size, "%ld", arg);
101                 if (ret < size) {
102                     renderp += ret;
103                     size -= ret;
104                 }
105             }
106
107             // Unmodified string specifier.
108             if (msg[i] == 's') {
109                 packed_to_token(arg, renderp); /* unpack directly to destination */
110                 size_t len = strlen(renderp);
111                 renderp += len;
112                 size -= len;
113             }
114
115             // Singular/plural specifier.
116             if (msg[i] == 'S') {
117                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
118                     *renderp++ = 's';
119                     size--;
120                 }
121             }
122
123             // All-lowercase specifier.
124             if (msg[i] == 'L' || msg[i] == 'C') {
125                 packed_to_token(arg, renderp); /* unpack directly to destination */
126                 int len = strlen(renderp);
127                 for (int j = 0; j < len; ++j) {
128                     renderp[j] = tolower(renderp[j]);
129                 }
130                 if (msg[i] == 'C') // First char uppercase, rest lowercase.
131                     renderp[0] = toupper(renderp[0]);
132                 renderp += len;
133                 size -= len;
134             }
135
136             previous_arg = arg;
137         }
138     }
139     *renderp = 0;
140
141     // Print the message.
142     printf("%s\n", rendered);
143
144     free(rendered);
145 }
146
147 void speak(const char* msg, ...)
148 {
149     va_list ap;
150     va_start(ap, msg);
151     vspeak(msg, ap);
152     va_end(ap);
153 }
154
155 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
156 /* Find the skip+1st message from msg and print it.  Modes are:
157  * feel = for inventory, what you can touch
158  * look = the long description for the state the object is in
159  * listen = the sound for the state the object is in
160  * study = text on the object. */
161 {
162     va_list ap;
163     va_start(ap, skip);
164     switch (mode) {
165     case touch:
166         vspeak(objects[msg].inventory, ap);
167         break;
168     case look: 
169         vspeak(objects[msg].descriptions[skip], ap);
170         break;
171     case hear:
172         vspeak(objects[msg].sounds[skip], ap);
173         break;
174     case study:
175         vspeak(objects[msg].texts[skip], ap);
176         break;
177     case change:
178         vspeak(objects[msg].changes[skip], ap);
179         break;
180     }
181     va_end(ap);
182 }
183
184 void rspeak(vocab_t i, ...)
185 /* Print the i-th "random" message (section 6 of database). */
186 {
187     va_list ap;
188     va_start(ap, i);
189     vspeak(arbitrary_messages[i], ap);
190     va_end(ap);
191 }
192
193 bool GETIN(FILE *input,
194            long *pword1, long *pword1x,
195            long *pword2, long *pword2x)
196 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
197  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
198  *  case we need to print out the whole word in an error message.  Any number of
199  *  blanks may follow the word.  If a second word appears, it is returned in
200  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
201 {
202     long junk;
203
204     for (;;) {
205         if (game.blklin)
206             fputc('\n', stdout);;
207         if (!MAPLIN(input))
208             return false;
209         *pword1 = GETTXT(true, true, true);
210         if (game.blklin && *pword1 < 0)
211             continue;
212         *pword1x = GETTXT(false, true, true);
213         do {
214             junk = GETTXT(false, true, true);
215         } while
216         (junk > 0);
217         *pword2 = GETTXT(true, true, true);
218         *pword2x = GETTXT(false, true, true);
219         do {
220             junk = GETTXT(false, true, true);
221         } while
222         (junk > 0);
223         if (GETTXT(true, true, true) <= 0)
224             return true;
225         rspeak(TWO_WORDS);
226     }
227 }
228
229 void echo_input(FILE* destination, char* input_prompt, char* input)
230 {
231     size_t len = strlen(input_prompt) + strlen(input) + 1;
232     char* prompt_and_input = (char*) xmalloc(len);
233     strcpy(prompt_and_input, input_prompt);
234     strcat(prompt_and_input, input);
235     fprintf(destination, "%s\n", prompt_and_input);
236     free(prompt_and_input);
237 }
238
239 char* get_input()
240 {
241     // Set up the prompt
242     char input_prompt[] = "> ";
243     if (!prompt)
244         input_prompt[0] = '\0';
245
246     // Print a blank line if game.blklin tells us to.
247     if (game.blklin == true)
248         printf("\n");
249
250     char* input;
251     while (true) {
252         if (editline)
253             input = linenoise(input_prompt);
254         else {
255             input = NULL;
256             size_t n = 0;
257             if (isatty(0))
258             // LCOV_EXCL_START
259             // Should be unreachable in tests, as they will use a non-interactive shell.
260                 printf("%s", input_prompt);
261             // LCOV_EXCL_STOP 
262             IGNORE(getline(&input, &n, stdin));
263         }
264
265         if (input == NULL) // Got EOF; return with it.
266             return(input);
267         else if (input[0] == '#') // Ignore comments.
268             continue;
269         else // We have a 'normal' line; leave the loop.
270             break;
271     }
272
273     // Strip trailing newlines from the input
274     input[strcspn(input, "\n")] = 0;
275
276     linenoiseHistoryAdd(input);
277
278     if (!isatty(0))
279         echo_input(stdout, input_prompt, input);
280
281     if (logfp)
282         echo_input(logfp, input_prompt, input);
283
284     return (input);
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     char* reply;
292     bool outcome;
293
294     for (;;) {
295         speak(question);
296
297         reply = get_input();
298         if (reply == NULL) {
299             // LCOV_EXCL_START
300             // Should be unreachable. Reply should never be NULL
301             linenoiseFree(reply);
302             exit(EXIT_SUCCESS);
303             // LCOV_EXCL_STOP 
304         }
305
306         char* firstword = (char*) xmalloc(strlen(reply)+1);
307         sscanf(reply, "%s", firstword);
308
309         for (int i = 0; i < (int)strlen(firstword); ++i)
310             firstword[i] = tolower(firstword[i]);
311
312         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
313         int y = strncmp("y", firstword, sizeof("y") - 1);
314         int no = strncmp("no", firstword, sizeof("no") - 1);
315         int n = strncmp("n", firstword, sizeof("n") - 1);
316
317         free(firstword);
318
319         if (yes == 0 || y == 0) {
320             speak(yes_response);
321             outcome = true;
322             break;
323         } else if (no == 0 || n == 0) {
324             speak(no_response);
325             outcome = false;
326             break;
327         } else
328             rspeak(PLEASE_ANSWER);
329     }
330     linenoiseFree(reply);
331     return (outcome);
332 }
333
334 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
335
336 long GETTXT(bool skip, bool onewrd, bool upper)
337 /*  Take characters from an input line and pack them into 30-bit words.
338  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
339  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
340  *  end of the line, the word is filled up with blanks (which encode as 0's).
341  *  If we're already at end of line when TEXT is called, we return -1. */
342 {
343     long text;
344     static long splitting = -1;
345
346     if (LNPOSN != splitting)
347         splitting = -1;
348     text = -1;
349     while (true) {
350         if (LNPOSN > LNLENG)
351             return (text);
352         if ((!skip) || INLINE[LNPOSN] != 0)
353             break;
354         ++LNPOSN;
355     }
356
357     text = 0;
358     for (int I = 1; I <= TOKLEN; I++) {
359         text = text * 64;
360         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
361             continue;
362         char current = INLINE[LNPOSN];
363         if (current < ascii_to_advent['%']) {
364             splitting = -1;
365             if (upper && current >= ascii_to_advent['a'])
366                 current = current - 26;
367             text = text + current;
368             ++LNPOSN;
369             continue;
370         }
371         if (splitting != LNPOSN) {
372             text = text + ascii_to_advent['%'];
373             splitting = LNPOSN;
374             continue;
375         }
376
377         text = text + current - ascii_to_advent['%'];
378         splitting = -1;
379         ++LNPOSN;
380     }
381
382     return text;
383 }
384
385 token_t MAKEWD(long letters)
386 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
387  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
388  *  the one that GETTXT would return given those characters plus
389  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
390  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
391  *  increment a letter by 5 by adding 50 to the next pair of
392  *  digits. */
393 {
394     long i = 1, word = 0;
395
396     for (long k = letters; k != 0; k = k / 100) {
397         word = word + i * (MOD(k, 50) + 10);
398         i = i * 64;
399         if (MOD(k, 100) > 50)word = word + i * 5;
400     }
401     i = 64L * 64L * 64L * 64L * 64L / i;
402     word = word * i;
403     return word;
404 }
405
406 /*  Data structure  routines */
407
408 long vocab(long id, long init)
409 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
410  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
411  *  up a keyword variable, and not finding it constitutes a bug.  It also means
412  *  that only KTAB values which taken over 1000 equal INIT may be considered.
413  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
414  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
415 {
416     long lexeme;
417
418     for (long i = 1; i <= TABSIZ; i++) {
419         if (KTAB[i] == -1) {
420             lexeme = -1;
421             if (init < 0)
422                 return (lexeme);
423             BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND); // LCOV_EXCL_LINE
424         }
425         if (init >= 0 && KTAB[i] / 1000 != init)
426             continue;
427         if (ATAB[i] == id) {
428             lexeme = KTAB[i];
429             if (init >= 0)
430                 lexeme = MOD(lexeme, 1000);
431             return (lexeme);
432         }
433     }
434     BUG(RAN_OFF_END_OF_VOCABULARY_TABLE); // LCOV_EXCL_LINE
435 }
436
437 void juggle(long object)
438 /*  Juggle an object by picking it up and putting it down again, the purpose
439  *  being to get the object to the front of the chain of things at its loc. */
440 {
441     long i, j;
442
443     i = game.place[object];
444     j = game.fixed[object];
445     move(object, i);
446     move(object + NOBJECTS, j);
447 }
448
449 void move(long object, long where)
450 /*  Place any object anywhere by picking it up and dropping it.  May
451  *  already be toting, in which case the carry is a no-op.  Mustn't
452  *  pick up objects which are not at any loc, since carry wants to
453  *  remove objects from game.atloc chains. */
454 {
455     long from;
456
457     if (object > NOBJECTS)
458         from = game.fixed[object - NOBJECTS];
459     else
460         from = game.place[object];
461     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
462         carry(object, from);
463     drop(object, where);
464 }
465
466 long put(long object, long where, long pval)
467 /*  PUT is the same as MOVE, except it returns a value used to set up the
468  *  negated game.prop values for the repository objects. */
469 {
470     move(object, where);
471     return (-1) - pval;;
472 }
473
474 void carry(long object, long where)
475 /*  Start toting an object, removing it from the list of things at its former
476  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
477  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
478 {
479     long temp;
480
481     if (object <= NOBJECTS) {
482         if (game.place[object] == CARRIED)
483             return;
484         game.place[object] = CARRIED;
485         ++game.holdng;
486     }
487     if (game.atloc[where] == object) {
488         game.atloc[where] = game.link[object];
489         return;
490     }
491     temp = game.atloc[where];
492     while (game.link[temp] != object) {
493         temp = game.link[temp];
494     }
495     game.link[temp] = game.link[object];
496 }
497
498 void drop(long object, long where)
499 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
500  *  game.holdng if the object was being toted. */
501 {
502     if (object > NOBJECTS)
503         game.fixed[object - NOBJECTS] = where;
504     else {
505         if (game.place[object] == CARRIED)
506             --game.holdng;
507         game.place[object] = where;
508     }
509     if (where <= 0)
510         return;
511     game.link[object] = game.atloc[where];
512     game.atloc[where] = object;
513 }
514
515 long atdwrf(long where)
516 /*  Return the index of first dwarf at the given location, zero if no dwarf is
517  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
518  *  the pirate (6th dwarf). */
519 {
520     long at;
521
522     at = 0;
523     if (game.dflag < 2)
524         return (at);
525     at = -1;
526     for (long i = 1; i <= NDWARVES - 1; i++) {
527         if (game.dloc[i] == where)
528             return i;
529         if (game.dloc[i] != 0)
530             at = 0;
531     }
532     return (at);
533 }
534
535 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
536  *  randrange, RNDVOC) */
537
538 long setbit(long bit)
539 /*  Returns 2**bit for use in constructing bit-masks. */
540 {
541     return (1L << bit);
542 }
543
544 bool tstbit(long mask, int bit)
545 /*  Returns true if the specified bit is set in the mask. */
546 {
547     return (mask & (1 << bit)) != 0;
548 }
549
550 void set_seed(long seedval)
551 /* Set the LCG seed */
552 {
553     game.lcg_x = (unsigned long) seedval % game.lcg_m;
554 }
555
556 unsigned long get_next_lcg_value(void)
557 /* Return the LCG's current value, and then iterate it. */
558 {
559     unsigned long old_x = game.lcg_x;
560     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
561     return old_x;
562 }
563
564 long randrange(long range)
565 /* Return a random integer from [0, range). */
566 {
567     return range * get_next_lcg_value() / game.lcg_m;
568 }
569
570 long rndvoc(long second, long force)
571 /*  Searches the vocabulary ATAB for a word whose second character is
572  *  char, and changes that word such that each of the other four
573  *  characters is a random letter.  If force is non-zero, it is used
574  *  as the new word.  Returns the new word. */
575 {
576     long rnd = force;
577
578     if (rnd == 0) {
579         for (int i = 1; i <= 5; i++) {
580             long j = 11 + randrange(26);
581             if (i == 2)
582                 j = second;
583             rnd = rnd * 64 + j;
584         }
585     }
586
587     long div = 64L * 64L * 64L;
588     for (int i = 1; i <= TABSIZ; i++) {
589         if (MOD(ATAB[i] / div, 64L) == second) {
590             ATAB[i] = rnd;
591             break;
592         }
593     }
594
595     return rnd;
596 }
597
598
599 /*  Machine dependent routines (MAPLIN, SAVEIO) */
600
601 bool MAPLIN(FILE *fp)
602 {
603     bool eof;
604
605     /* Read a line of input, from the specified input source.
606      * This logic is complicated partly because it has to serve
607      * several cases with different requirements and partly because
608      * of a quirk in linenoise().
609      *
610      * The quirk shows up when you paste a test log from the clipboard
611      * to the program's command prompt.  While fgets (as expected)
612      * consumes it a line at a time, linenoise() returns the first
613      * line and discards the rest.  Thus, there needs to be an
614      * editline (-s) option to fall back to fgets while still
615      * prompting.  Note that linenoise does behave properly when
616      * fed redirected stdin.
617      *
618      * The logging is a bit of a mess because there are two distinct cases
619      * in which you want to echo commands.  One is when shipping them to
620      * a log under the -l option, in which case you want to suppress
621      * prompt generation (so test logs are unadorned command sequences).
622      * On the other hand, if you redirected stdin and are feeding the program
623      * a logfile, you *do* want prompt generation - it makes checkfiles
624      * easier to read when the commands are marked by a preceding prompt.
625      */
626     do {
627         if (!editline) {
628             if (prompt)
629                 fputs("> ", stdout);
630             IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
631             eof = (feof(fp));
632         } else {
633             char *cp = linenoise("> ");
634             eof = (cp == NULL);
635             if (!eof) {
636                 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
637                 linenoiseHistoryAdd(rawbuf);
638                 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
639                 linenoiseFree(cp);
640             }
641         }
642     } while
643     (!eof && rawbuf[0] == '#');
644     if (eof) {
645         if (logfp && fp == stdin)
646             fclose(logfp);
647         return false;
648     } else {
649         FILE *efp = NULL;
650         if (logfp && fp == stdin)
651             efp = logfp;
652         else if (!isatty(0))
653             efp = stdout;
654         if (efp != NULL) {
655             if (prompt && efp == stdout)
656                 fputs("> ", efp);
657             IGNORE(fputs(rawbuf, efp));
658         }
659         strcpy(INLINE + 1, rawbuf);
660         /*  translate the chars to integers in the range 0-126 and store
661          *  them in the common array "INLINE".  Integer values are as follows:
662          *     0   = space [ASCII CODE 40 octal, 32 decimal]
663          *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
664          *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
665          *   11-36 = upper-case letters
666          *   37-62 = lower-case letters
667          *    63   = percent (%) [ASCII 45 octal, 37 decimal]
668          *   64-73 = digits, 0 through 9
669          *  Remaining characters can be translated any way that is convenient;
670          *  The above mappings are required so that certain special
671          *  characters are known to fit in 6 bits and/or can be easily spotted.
672          *  Array elements beyond the end of the line should be filled with 0,
673          *  and LNLENG should be set to the index of the last character.
674          *
675          *  If the data file uses a character other than space (e.g., tab) to
676          *  separate numbers, that character should also translate to 0.
677          *
678          *  This procedure may use the map1,map2 arrays to maintain
679          *  static data for he mapping.  MAP2(1) is set to 0 when the
680          *  program starts and is not changed thereafter unless the
681          *  routines in this module choose to do so. */
682         LNLENG = 0;
683         for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
684             long val = INLINE[i];
685             INLINE[i] = ascii_to_advent[val];
686             if (INLINE[i] != 0)
687                 LNLENG = i;
688         }
689         LNPOSN = 1;
690         return true;
691     }
692 }
693
694 void datime(long* d, long* t)
695 {
696     struct timeval tv;
697     gettimeofday(&tv, NULL);
698     *d = (long) tv.tv_sec;
699     *t = (long) tv.tv_usec;
700 }
701
702 // LCOV_EXCL_START
703 void bug(enum bugtype num, const char *error_string)
704 {
705     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
706     exit(EXIT_FAILURE);
707 }
708 // LCOV_EXCL_STOP
709
710 /* end */