09244625cfe0c536bb866fcf17eccf21356d5e48
[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         fprintf(stderr, "Out of memory!\n");
18         exit(EXIT_FAILURE);
19     }
20     return (ptr);
21 }
22
23 char* xstrdup(const char* s)
24 {
25     char* ptr = strdup(s);
26     if (ptr == NULL) {
27         fprintf(stderr, "Out of memory!\n");
28         exit(EXIT_FAILURE);
29     }
30     return (ptr);
31 }
32
33 void packed_to_token(long packed, char token[6])
34 {
35     // Unpack and map back to ASCII.
36     for (int i = 0; i < 5; ++i) {
37         char advent = (packed >> i * 6) & 63;
38         token[4 - i] = advent_to_ascii[(int) advent];
39     }
40
41     // Ensure the last character is \0.
42     token[5] = '\0';
43
44     // Replace trailing whitespace with \0.
45     for (int i = 4; i >= 0; --i) {
46         if (token[i] == ' ' || token[i] == '\t')
47             token[i] = '\0';
48         else
49             break;
50     }
51 }
52
53 void token_to_packed(char token[6], long* packed)
54 {
55   *packed = 0;
56   for (size_t i = 0; i < 5; ++i)
57     {
58       if (token[4 - i] == '\0')
59         continue;       
60       char mapped = ascii_to_advent[(int) token[4 - i]];
61       *packed |= (mapped << (6 * i));
62     }
63 }
64
65 /* Hide the fact that wods are corrently packed longs */
66
67 bool wordeq(token_t a, token_t b)
68 {
69     return a == b;
70 }
71
72 bool wordempty(token_t a)
73 {
74     return a == 0;
75 }
76
77 void wordclear(token_t *v)
78 {
79     *v = 0;
80 }
81
82 /*  I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
83
84 void speak(const char* msg)
85 {
86     // Do nothing if we got a null pointer.
87     if (msg == NULL)
88         return;
89
90     // Do nothing if we got an empty string.
91     if (strlen(msg) == 0)
92         return;
93
94     // Print a newline if the global game.blklin says to.
95     if (game.blklin == true)
96         printf("\n");
97
98     // Create a copy of our string, so we can edit it.
99     char* copy = xstrdup(msg);
100
101     // Staging area for stringified parameters.
102     char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
103
104     // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
105     int pi = 0; // parameter index
106     for (int i = 0; i < (int)strlen(msg); ++i) {
107         if (msg[i] == '%') {
108             ++pi;
109
110             // 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.
111             if (msg[i + 1] == 'd') {
112                 copy[i + 1] = 's';
113                 sprintf(parameters[pi], "%ld", PARMS[pi]);
114             }
115
116             // Unmodified string specifier.
117             if (msg[i + 1] == 's') {
118                 packed_to_token(PARMS[pi], parameters[pi]);
119             }
120
121             // Singular/plural specifier.
122             if (msg[i + 1] == 'S') {
123                 copy[i + 1] = 's';
124                 if (PARMS[pi - 1] > 1) { // look at the *previous* parameter (which by necessity must be numeric)
125                     sprintf(parameters[pi], "%s", "s");
126                 } else {
127                     sprintf(parameters[pi], "%s", "");
128                 }
129             }
130
131             // All-lowercase specifier.
132             if (msg[i + 1] == 'L') {
133                 copy[i + 1] = 's';
134                 packed_to_token(PARMS[pi], parameters[pi]);
135                 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
136                     parameters[pi][j] = tolower(parameters[pi][j]);
137                 }
138             }
139
140             // First char uppercase, rest lowercase.
141             if (msg[i + 1] == 'C') {
142                 copy[i + 1] = 's';
143                 packed_to_token(PARMS[pi], parameters[pi]);
144                 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
145                     parameters[pi][j] = tolower(parameters[pi][j]);
146                 }
147                 parameters[pi][0] = toupper(parameters[pi][0]);
148             }
149         }
150     }
151
152     // Render the final string.
153     char rendered[2000]; // FIXME: to be replaced with dynamic allocation
154     sprintf(rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
155
156     // Print the message.
157     printf("%s\n", rendered);
158
159     free(copy);
160 }
161
162 void PSPEAK(vocab_t msg, int skip)
163 /*  Find the skip+1st message from msg and print it.  msg should be
164  *  the index of the inventory message for object.  (INVEN+N+1 message
165  *  is game.prop=N message). */
166 {
167     if (skip >= 0)
168         speak(object_descriptions[msg].longs[skip]);
169     else
170         speak(object_descriptions[msg].inventory);
171 }
172
173 void RSPEAK(vocab_t i)
174 /* Print the i-th "random" message (section 6 of database). */
175 {
176     speak(arbitrary_messages[i]);
177 }
178
179 void SETPRM(long first, long p1, long p2)
180 /*  Stores parameters into the PRMCOM parms array for use by speak.  P1 and P2
181  *  are stored into PARMS(first) and PARMS(first+1). */
182 {
183     if (first >= MAXPARMS)
184         BUG(TOO_MANY_PARAMETERS_GIVEN_TO_SETPRM);
185     else {
186         PARMS[first] = p1;
187         PARMS[first + 1] = p2;
188     }
189 }
190
191 bool GETIN(FILE *input,
192            long *pword1, long *pword1x,
193            long *pword2, long *pword2x)
194 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
195  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
196  *  case we need to print out the whole word in an error message.  Any number of
197  *  blanks may follow the word.  If a second word appears, it is returned in
198  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
199 {
200     long junk;
201
202     for (;;) {
203         if (game.blklin)
204             fputc('\n', stdout);;
205         if (!MAPLIN(input))
206             return false;
207         *pword1 = GETTXT(true, true, true);
208         if (game.blklin && *pword1 < 0)
209             continue;
210         *pword1x = GETTXT(false, true, true);
211         do {
212             junk = GETTXT(false, true, true);
213         } while
214         (junk > 0);
215         *pword2 = GETTXT(true, true, true);
216         *pword2x = GETTXT(false, true, true);
217         do {
218             junk = GETTXT(false, true, true);
219         } while
220         (junk > 0);
221         if (GETTXT(true, true, true) <= 0)
222             return true;
223         RSPEAK(TWO_WORDS);
224     }
225 }
226
227 void echo_input(FILE* destination, char* input_prompt, char* input)
228 {
229     size_t len = strlen(input_prompt) + strlen(input) + 1;
230     char* prompt_and_input = (char*) xmalloc(len);
231     strcpy(prompt_and_input, input_prompt);
232     strcat(prompt_and_input, input);
233     fprintf(destination, "%s\n", prompt_and_input);
234     free(prompt_and_input);
235 }
236
237 char* get_input()
238 {
239     // Set up the prompt
240     char input_prompt[] = "> ";
241     if (!prompt)
242         input_prompt[0] = '\0';
243
244     // Print a blank line if game.blklin tells us to.
245     if (game.blklin == true)
246         printf("\n");
247
248     char* input;
249     while (true) {
250         if (editline)
251             input = linenoise(input_prompt);
252         else {
253             input = NULL;
254             size_t n = 0;
255             if (isatty(0))
256                 printf("%s", input_prompt);
257             IGNORE(getline(&input, &n, stdin));
258         }
259
260         if (input == NULL) // Got EOF; return with it.
261             return(input);
262         else if (input[0] == '#') // Ignore comments.
263             continue;
264         else // We have a 'normal' line; leave the loop.
265             break;
266     }
267
268     // Strip trailing newlines from the input
269     input[strcspn(input, "\n")] = 0;
270
271     linenoiseHistoryAdd(input);
272
273     if (!isatty(0))
274         echo_input(stdout, input_prompt, input);
275
276     if (logfp)
277         echo_input(logfp, input_prompt, input);
278
279     return (input);
280 }
281
282 bool YES(const char* question, const char* yes_response, const char* no_response)
283 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
284  *  if no, print Z and return false. */
285 {
286     char* reply;
287     bool outcome;
288
289     for (;;) {
290         speak(question);
291
292         reply = get_input();
293         if (reply == NULL) {
294           linenoiseFree(reply);
295           exit(EXIT_SUCCESS);
296         }
297
298         char* firstword = (char*) xmalloc(strlen(reply)+1);
299         sscanf(reply, "%s", firstword);
300
301         for (int i = 0; i < (int)strlen(firstword); ++i)
302             firstword[i] = tolower(firstword[i]);
303
304         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
305         int y = strncmp("y", firstword, sizeof("y") - 1);
306         int no = strncmp("no", firstword, sizeof("no") - 1);
307         int n = strncmp("n", firstword, sizeof("n") - 1);
308
309         free(firstword);
310
311         if (yes == 0 || y == 0) {
312             speak(yes_response);
313             outcome = true;
314             break;
315         } else if (no == 0 || n == 0) {
316             speak(no_response);
317             outcome = false;
318             break;
319         } else
320             RSPEAK(PLEASE_ANSWER);
321     }
322     linenoiseFree(reply);
323     return (outcome);
324 }
325
326 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
327
328 long GETTXT(bool skip, bool onewrd, bool upper)
329 /*  Take characters from an input line and pack them into 30-bit words.
330  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
331  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
332  *  end of the line, the word is filled up with blanks (which encode as 0's).
333  *  If we're already at end of line when TEXT is called, we return -1. */
334 {
335     long text;
336     static long splitting = -1;
337
338     if (LNPOSN != splitting)
339         splitting = -1;
340     text = -1;
341     while (true) {
342         if (LNPOSN > LNLENG)
343             return (text);
344         if ((!skip) || INLINE[LNPOSN] != 0)
345             break;
346         ++LNPOSN;
347     }
348
349     text = 0;
350     for (int I = 1; I <= TOKLEN; I++) {
351         text = text * 64;
352         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
353             continue;
354         char current = INLINE[LNPOSN];
355         if (current < ascii_to_advent['%']) {
356             splitting = -1;
357             if (upper && current >= ascii_to_advent['a'])
358                 current = current - 26;
359             text = text + current;
360             ++LNPOSN;
361             continue;
362         }
363         if (splitting != LNPOSN) {
364             text = text + ascii_to_advent['%'];
365             splitting = LNPOSN;
366             continue;
367         }
368
369         text = text + current - ascii_to_advent['%'];
370         splitting = -1;
371         ++LNPOSN;
372     }
373
374     return text;
375 }
376
377 token_t MAKEWD(long letters)
378 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
379  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
380  *  the one that GETTXT would return given those characters plus
381  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
382  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
383  *  increment a letter by 5 by adding 50 to the next pair of
384  *  digits. */
385 {
386     long i = 1, word = 0;
387
388     for (long k = letters; k != 0; k = k / 100) {
389         word = word + i * (MOD(k, 50) + 10);
390         i = i * 64;
391         if (MOD(k, 100) > 50)word = word + i * 5;
392     }
393     i = 64L * 64L * 64L * 64L * 64L / i;
394     word = word * i;
395     return word;
396 }
397
398 /*  Data structure  routines */
399
400 long VOCAB(long id, long init)
401 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
402  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
403  *  up a keyword variable, and not finding it constitutes a bug.  It also means
404  *  that only KTAB values which taken over 1000 equal INIT may be considered.
405  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
406  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
407 {
408     long lexeme;
409
410     for (long i = 1; i <= TABSIZ; i++) {
411         if (KTAB[i] == -1) {
412             lexeme = -1;
413             if (init < 0)
414                 return (lexeme);
415             BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND);
416         }
417         if (init >= 0 && KTAB[i] / 1000 != init)
418             continue;
419         if (ATAB[i] == id) {
420             lexeme = KTAB[i];
421             if (init >= 0)
422                 lexeme = MOD(lexeme, 1000);
423             return (lexeme);
424         }
425     }
426     BUG(RAN_OFF_END_OF_VOCABULARY_TABLE);
427 }
428
429 void JUGGLE(long object)
430 /*  Juggle an object by picking it up and putting it down again, the purpose
431  *  being to get the object to the front of the chain of things at its loc. */
432 {
433     long i, j;
434
435     i = game.place[object];
436     j = game.fixed[object];
437     MOVE(object, i);
438     MOVE(object + NOBJECTS, j);
439 }
440
441 void MOVE(long object, long where)
442 /*  Place any object anywhere by picking it up and dropping it.  May
443  *  already be toting, in which case the carry is a no-op.  Mustn't
444  *  pick up objects which are not at any loc, since carry wants to
445  *  remove objects from game.atloc chains. */
446 {
447     long from;
448
449     if (object > NOBJECTS)
450         from = game.fixed[object - NOBJECTS];
451     else
452         from = game.place[object];
453     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
454         CARRY(object, from);
455     DROP(object, where);
456 }
457
458 long PUT(long object, long where, long pval)
459 /*  PUT is the same as MOVE, except it returns a value used to set up the
460  *  negated game.prop values for the repository objects. */
461 {
462     MOVE(object, where);
463     return (-1) - pval;;
464 }
465
466 void CARRY(long object, long where)
467 /*  Start toting an object, removing it from the list of things at its former
468  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
469  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
470 {
471     long temp;
472
473     if (object <= NOBJECTS) {
474         if (game.place[object] == CARRIED)
475             return;
476         game.place[object] = CARRIED;
477         ++game.holdng;
478     }
479     if (game.atloc[where] == object) {
480         game.atloc[where] = game.link[object];
481         return;
482     }
483     temp = game.atloc[where];
484     while (game.link[temp] != object) {
485         temp = game.link[temp];
486     }
487     game.link[temp] = game.link[object];
488 }
489
490 void DROP(long object, long where)
491 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
492  *  game.holdng if the object was being toted. */
493 {
494     if (object > NOBJECTS)
495         game.fixed[object - NOBJECTS] = where;
496     else {
497         if (game.place[object] == CARRIED)
498             --game.holdng;
499         game.place[object] = where;
500     }
501     if (where <= 0)
502         return;
503     game.link[object] = game.atloc[where];
504     game.atloc[where] = object;
505 }
506
507 long ATDWRF(long where)
508 /*  Return the index of first dwarf at the given location, zero if no dwarf is
509  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
510  *  the pirate (6th dwarf). */
511 {
512     long at;
513
514     at = 0;
515     if (game.dflag < 2)
516         return (at);
517     at = -1;
518     for (long i = 1; i <= NDWARVES - 1; i++) {
519         if (game.dloc[i] == where)
520             return i;
521         if (game.dloc[i] != 0)
522             at = 0;
523     }
524     return (at);
525 }
526
527 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
528  *  randrange, RNDVOC) */
529
530 long SETBIT(long bit)
531 /*  Returns 2**bit for use in constructing bit-masks. */
532 {
533     return (1 << bit);
534 }
535
536 bool TSTBIT(long mask, int bit)
537 /*  Returns true if the specified bit is set in the mask. */
538 {
539     return (mask & (1 << bit)) != 0;
540 }
541
542 void set_seed(long seedval)
543 /* Set the LCG seed */
544 {
545     game.lcg_x = (unsigned long) seedval % game.lcg_m;
546 }
547
548 unsigned long get_next_lcg_value(void)
549 /* Return the LCG's current value, and then iterate it. */
550 {
551     unsigned long old_x = game.lcg_x;
552     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
553     return old_x;
554 }
555
556 long randrange(long range)
557 /* Return a random integer from [0, range). */
558 {
559     return range * get_next_lcg_value() / game.lcg_m;
560 }
561
562 long RNDVOC(long second, long force)
563 /*  Searches the vocabulary ATAB for a word whose second character is
564  *  char, and changes that word such that each of the other four
565  *  characters is a random letter.  If force is non-zero, it is used
566  *  as the new word.  Returns the new word. */
567 {
568     long rnd = force;
569
570     if (rnd == 0) {
571         for (int i = 1; i <= 5; i++) {
572             long j = 11 + randrange(26);
573             if (i == 2)
574                 j = second;
575             rnd = rnd * 64 + j;
576         }
577     }
578
579     long div = 64L * 64L * 64L;
580     for (int i = 1; i <= TABSIZ; i++) {
581         if (MOD(ATAB[i] / div, 64L) == second) {
582             ATAB[i] = rnd;
583             break;
584         }
585     }
586
587     return rnd;
588 }
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
671          *  static data for he mapping.  MAP2(1) is set to 0 when the
672          *  program starts and is not changed thereafter unless the
673          *  routines in this module choose 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 void bug(enum bugtype num, const char *error_string)
695 {
696     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
697     exit(EXIT_FAILURE);
698 }
699
700 /* end */