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