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