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