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